clang 23.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"
15#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/Template.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
146 return D;
147
148 return nullptr;
149}
150
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
242 if (isa<FunctionTemplateDecl>(FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
280 R.suppressDiagnostics();
281 } else {
282 if (!D) {
283 D = getAsTemplateNameDecl(*R.begin());
284 assert(D && "unambiguous result is not a template name");
285 }
286
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
300 Template);
301 }
302
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
307 R.suppressDiagnostics();
308 } else {
312 TemplateKind =
314 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
318 }
319 }
320
322 S->getTemplateParamParent() == nullptr)
323 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(Template);
328 return TemplateKind;
329}
330
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
345 R.suppressDiagnostics();
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
351 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
352 if (!TD || !getAsTypeTemplateDecl(TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
358 *Template = TemplateTy::make(Name);
359 }
360 return true;
361}
362
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
379 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(IILoc, diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(IILoc, "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
391 bool AllowTypoCorrection) {
392 if (ATK)
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
412 "Caller should have completed object type");
413
414 // Template names cannot appear inside an Objective-C class or object type
415 // or a vector type.
416 //
417 // FIXME: This is wrong. For example:
418 //
419 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
420 // Vec<int> vi;
421 // vi.Vec<int>::~Vec<int>();
422 //
423 // ... should be accepted but we will not treat 'Vec' as a template name
424 // here. The right thing to do would be to check if the name is a valid
425 // vector component name, and look up a template name if not. And similarly
426 // for lookups into Objective-C class and object types, where the same
427 // problem can arise.
428 if (ObjectType->isObjCObjectOrInterfaceType() ||
429 ObjectType->isVectorType()) {
430 Found.clear();
431 return false;
432 }
433 } else if (SS.isNotEmpty()) {
434 // This nested-name-specifier occurs after another nested-name-specifier,
435 // so long into the context associated with the prior nested-name-specifier.
436 LookupCtx = computeDeclContext(SS, EnteringContext);
437 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
438
439 // The declaration context must be complete.
440 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
441 return true;
442 }
443
444 bool ObjectTypeSearchedInScope = false;
445 bool AllowFunctionTemplatesInLookup = true;
446 if (LookupCtx) {
447 // Perform "qualified" name lookup into the declaration context we
448 // computed, which is either the type of the base of a member access
449 // expression or the declaration context associated with a prior
450 // nested-name-specifier.
451 LookupQualifiedName(Found, LookupCtx);
452
453 // FIXME: The C++ standard does not clearly specify what happens in the
454 // case where the object type is dependent, and implementations vary. In
455 // Clang, we treat a name after a . or -> as a template-name if lookup
456 // finds a non-dependent member or member of the current instantiation that
457 // is a type template, or finds no such members and lookup in the context
458 // of the postfix-expression finds a type template. In the latter case, the
459 // name is nonetheless dependent, and we may resolve it to a member of an
460 // unknown specialization when we come to instantiate the template.
461 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
462 }
463
464 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
465 // C++ [basic.lookup.classref]p1:
466 // In a class member access expression (5.2.5), if the . or -> token is
467 // immediately followed by an identifier followed by a <, the
468 // identifier must be looked up to determine whether the < is the
469 // beginning of a template argument list (14.2) or a less-than operator.
470 // The identifier is first looked up in the class of the object
471 // expression. If the identifier is not found, it is then looked up in
472 // the context of the entire postfix-expression and shall name a class
473 // template.
474 if (S)
475 LookupName(Found, S);
476
477 if (!ObjectType.isNull()) {
478 // FIXME: We should filter out all non-type templates here, particularly
479 // variable templates and concepts. But the exclusion of alias templates
480 // and template template parameters is a wording defect.
481 AllowFunctionTemplatesInLookup = false;
482 ObjectTypeSearchedInScope = true;
483 }
484
485 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
486 }
487
488 if (Found.isAmbiguous())
489 return false;
490
491 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
492 !RequiredTemplate.hasTemplateKeyword()) {
493 // C++2a [temp.names]p2:
494 // A name is also considered to refer to a template if it is an
495 // unqualified-id followed by a < and name lookup finds either one or more
496 // functions or finds nothing.
497 //
498 // To keep our behavior consistent, we apply the "finds nothing" part in
499 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
500 // successfully form a call to an undeclared template-id.
501 bool AllFunctions =
502 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
504 });
505 if (AllFunctions || (Found.empty() && !IsDependent)) {
506 // If lookup found any functions, or if this is a name that can only be
507 // used for a function, then strongly assume this is a function
508 // template-id.
509 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
512 Found.clear();
513 return false;
514 }
515 }
516
517 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
518 // If we did not find any names, and this is not a disambiguation, attempt
519 // to correct any typos.
520 DeclarationName Name = Found.getLookupName();
521 Found.clear();
522 QualifiedLookupValidatorCCC FilterCCC(!SS.isEmpty());
523 FilterCCC.WantTypeSpecifiers = false;
524 FilterCCC.WantExpressionKeywords = false;
525 FilterCCC.WantRemainingKeywords = false;
526 FilterCCC.WantCXXNamedCasts = true;
527 if (TypoCorrection Corrected = CorrectTypo(
528 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
529 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
530 if (auto *ND = Corrected.getFoundDecl())
531 Found.addDecl(ND);
533 if (Found.isAmbiguous()) {
534 Found.clear();
535 } else if (!Found.empty()) {
536 // Do not erase the typo-corrected result to avoid duplicated
537 // diagnostics.
538 AllowFunctionTemplatesInLookup = true;
539 Found.setLookupName(Corrected.getCorrection());
540 if (LookupCtx) {
541 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
542 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543 Name.getAsString() == CorrectedStr;
544 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
545 << Name << LookupCtx << DroppedSpecifier
546 << SS.getRange());
547 } else {
548 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
549 }
550 }
551 }
552 }
553
554 NamedDecl *ExampleLookupResult =
555 Found.empty() ? nullptr : Found.getRepresentativeDecl();
556 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
557 if (Found.empty()) {
558 if (IsDependent) {
559 Found.setNotFoundInCurrentInstantiation();
560 return false;
561 }
562
563 // If a 'template' keyword was used, a lookup that finds only non-template
564 // names is an error.
565 if (ExampleLookupResult && RequiredTemplate) {
566 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
567 << Found.getLookupName() << SS.getRange()
568 << RequiredTemplate.hasTemplateKeyword()
569 << RequiredTemplate.getTemplateKeywordLoc();
570 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
571 diag::note_template_kw_refers_to_non_template)
572 << Found.getLookupName();
573 return true;
574 }
575
576 return false;
577 }
578
579 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
581 // C++03 [basic.lookup.classref]p1:
582 // [...] If the lookup in the class of the object expression finds a
583 // template, the name is also looked up in the context of the entire
584 // postfix-expression and [...]
585 //
586 // Note: C++11 does not perform this second lookup.
587 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
589 FoundOuter.setTemplateNameLookup(true);
590 LookupName(FoundOuter, S);
591 // FIXME: We silently accept an ambiguous lookup here, in violation of
592 // [basic.lookup]/1.
593 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
594
595 NamedDecl *OuterTemplate;
596 if (FoundOuter.empty()) {
597 // - if the name is not found, the name found in the class of the
598 // object expression is used, otherwise
599 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
600 !(OuterTemplate =
601 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
602 // - if the name is found in the context of the entire
603 // postfix-expression and does not name a class template, the name
604 // found in the class of the object expression is used, otherwise
605 FoundOuter.clear();
606 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
607 // - if the name found is a class template, it must refer to the same
608 // entity as the one found in the class of the object expression,
609 // otherwise the program is ill-formed.
610 if (!Found.isSingleResult() ||
611 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
612 OuterTemplate->getCanonicalDecl()) {
613 Diag(Found.getNameLoc(),
614 diag::ext_nested_name_member_ref_lookup_ambiguous)
615 << Found.getLookupName()
616 << ObjectType;
617 Diag(Found.getRepresentativeDecl()->getLocation(),
618 diag::note_ambig_member_ref_object_type)
619 << ObjectType;
620 Diag(FoundOuter.getFoundDecl()->getLocation(),
621 diag::note_ambig_member_ref_scope);
622
623 // Recover by taking the template that we found in the object
624 // expression's type.
625 }
626 }
627 }
628
629 return false;
630}
631
635 if (TemplateName.isInvalid())
636 return;
637
638 DeclarationNameInfo NameInfo;
639 CXXScopeSpec SS;
640 LookupNameKind LookupKind;
641
642 DeclContext *LookupCtx = nullptr;
643 NamedDecl *Found = nullptr;
644 bool MissingTemplateKeyword = false;
645
646 // Figure out what name we looked up.
647 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
648 NameInfo = DRE->getNameInfo();
649 SS.Adopt(DRE->getQualifierLoc());
650 LookupKind = LookupOrdinaryName;
651 Found = DRE->getFoundDecl();
652 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
653 NameInfo = ME->getMemberNameInfo();
654 SS.Adopt(ME->getQualifierLoc());
655 LookupKind = LookupMemberName;
656 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
657 Found = ME->getMemberDecl();
658 } else if (auto *DSDRE =
659 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
660 NameInfo = DSDRE->getNameInfo();
661 SS.Adopt(DSDRE->getQualifierLoc());
662 MissingTemplateKeyword = true;
663 } else if (auto *DSME =
664 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
665 NameInfo = DSME->getMemberNameInfo();
666 SS.Adopt(DSME->getQualifierLoc());
667 MissingTemplateKeyword = true;
668 } else {
669 llvm_unreachable("unexpected kind of potential template name");
670 }
671
672 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
673 // was missing.
674 if (MissingTemplateKeyword) {
675 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
676 << NameInfo.getName() << SourceRange(Less, Greater);
677 return;
678 }
679
680 // Try to correct the name by looking for templates and C++ named casts.
681 struct TemplateCandidateFilter : CorrectionCandidateCallback {
682 Sema &S;
683 TemplateCandidateFilter(Sema &S) : S(S) {
684 WantTypeSpecifiers = false;
685 WantExpressionKeywords = false;
686 WantRemainingKeywords = false;
687 WantCXXNamedCasts = true;
688 };
689 bool ValidateCandidate(const TypoCorrection &Candidate) override {
690 if (auto *ND = Candidate.getCorrectionDecl())
691 return S.getAsTemplateNameDecl(ND);
692 return Candidate.isKeyword();
693 }
694
695 std::unique_ptr<CorrectionCandidateCallback> clone() override {
696 return std::make_unique<TemplateCandidateFilter>(*this);
697 }
698 };
699
700 DeclarationName Name = NameInfo.getName();
701 TemplateCandidateFilter CCC(*this);
702 if (TypoCorrection Corrected =
703 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
704 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
705 auto *ND = Corrected.getFoundDecl();
706 if (ND)
707 ND = getAsTemplateNameDecl(ND);
708 if (ND || Corrected.isKeyword()) {
709 if (LookupCtx) {
710 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
711 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
712 Name.getAsString() == CorrectedStr;
713 diagnoseTypo(Corrected,
714 PDiag(diag::err_non_template_in_member_template_id_suggest)
715 << Name << LookupCtx << DroppedSpecifier
716 << SS.getRange(), false);
717 } else {
718 diagnoseTypo(Corrected,
719 PDiag(diag::err_non_template_in_template_id_suggest)
720 << Name, false);
721 }
722 if (Found)
723 Diag(Found->getLocation(),
724 diag::note_non_template_in_template_id_found);
725 return;
726 }
727 }
728
729 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
730 << Name << SourceRange(Less, Greater);
731 if (Found)
732 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
733}
734
737 SourceLocation TemplateKWLoc,
738 const DeclarationNameInfo &NameInfo,
739 bool isAddressOfOperand,
740 const TemplateArgumentListInfo *TemplateArgs) {
741 if (SS.isEmpty()) {
742 // FIXME: This codepath is only used by dependent unqualified names
743 // (e.g. a dependent conversion-function-id, or operator= once we support
744 // it). It doesn't quite do the right thing, and it will silently fail if
745 // getCurrentThisType() returns null.
746 QualType ThisType = getCurrentThisType();
747 if (ThisType.isNull())
748 return ExprError();
749
751 Context, /*Base=*/nullptr, ThisType,
752 /*IsArrow=*/!Context.getLangOpts().HLSL,
753 /*OperatorLoc=*/SourceLocation(),
754 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
755 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
756 }
757 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
758}
759
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 const TemplateArgumentListInfo *TemplateArgs) {
765 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
766 if (!SS.isValid())
767 return CreateRecoveryExpr(
768 SS.getBeginLoc(),
769 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
770
772 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
773 TemplateArgs);
774}
775
777 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
779 bool Final) {
780 // The template argument itself might be an expression, in which case we just
781 // return that expression. This happens when substituting into an alias
782 // template.
783 Expr *Replacement;
784 bool refParam = true;
786 Replacement = Arg.getAsExpr();
787 refParam = Replacement->isLValue();
788 if (refParam && Replacement->getType()->isRecordType()) {
789 QualType ParamType =
791 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)
792 : NTTP->getType();
793 if (const auto *PET = dyn_cast<PackExpansionType>(ParamType))
794 ParamType = PET->getPattern();
795 refParam = ParamType->isReferenceType();
796 }
797 } else {
798 ExprResult result =
799 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
800 if (result.isInvalid())
801 return ExprError();
802 Replacement = result.get();
804 }
805 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
806 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
807 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
808}
809
811 NamedDecl *Instantiation,
812 bool InstantiatedFromMember,
813 const NamedDecl *Pattern,
814 const NamedDecl *PatternDef,
816 bool Complain, bool *Unreachable) {
817 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
818 isa<VarDecl>(Instantiation));
819
820 bool IsEntityBeingDefined = false;
821 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
822 IsEntityBeingDefined = TD->isBeingDefined();
823
824 if (PatternDef && !IsEntityBeingDefined) {
825 NamedDecl *SuggestedDef = nullptr;
826 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
827 &SuggestedDef,
828 /*OnlyNeedComplete*/ false)) {
829 if (Unreachable)
830 *Unreachable = true;
831 // If we're allowed to diagnose this and recover, do so.
832 bool Recover = Complain && !isSFINAEContext();
833 if (Complain)
834 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
836 return !Recover;
837 }
838 return false;
839 }
840
841 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
842 return true;
843
844 CanQualType InstantiationTy;
845 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
846 InstantiationTy = Context.getCanonicalTagType(TD);
847 if (PatternDef) {
848 Diag(PointOfInstantiation,
849 diag::err_template_instantiate_within_definition)
850 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
851 << InstantiationTy;
852 // Not much point in noting the template declaration here, since
853 // we're lexically inside it.
854 Instantiation->setInvalidDecl();
855 } else if (InstantiatedFromMember) {
856 if (isa<FunctionDecl>(Instantiation)) {
857 Diag(PointOfInstantiation,
858 diag::err_explicit_instantiation_undefined_member)
859 << /*member function*/ 1 << Instantiation->getDeclName()
860 << Instantiation->getDeclContext();
861 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
862 } else {
863 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
864 Diag(PointOfInstantiation,
865 diag::err_implicit_instantiate_member_undefined)
866 << InstantiationTy;
867 Diag(Pattern->getLocation(), diag::note_member_declared_at);
868 }
869 } else {
870 if (isa<FunctionDecl>(Instantiation)) {
871 Diag(PointOfInstantiation,
872 diag::err_explicit_instantiation_undefined_func_template)
873 << Pattern;
874 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
875 } else if (isa<TagDecl>(Instantiation)) {
876 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
877 << (TSK != TSK_ImplicitInstantiation)
878 << InstantiationTy;
879 NoteTemplateLocation(*Pattern);
880 } else {
881 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
882 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
883 Diag(PointOfInstantiation,
884 diag::err_explicit_instantiation_undefined_var_template)
885 << Instantiation;
886 Instantiation->setInvalidDecl();
887 } else
888 Diag(PointOfInstantiation,
889 diag::err_explicit_instantiation_undefined_member)
890 << /*static data member*/ 2 << Instantiation->getDeclName()
891 << Instantiation->getDeclContext();
892 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
893 }
894 }
895
896 // In general, Instantiation isn't marked invalid to get more than one
897 // error for multiple undefined instantiations. But the code that does
898 // explicit declaration -> explicit definition conversion can't handle
899 // invalid declarations, so mark as invalid in that case.
901 Instantiation->setInvalidDecl();
902 return true;
903}
904
906 bool SupportedForCompatibility) {
907 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
908
909 // C++23 [temp.local]p6:
910 // The name of a template-parameter shall not be bound to any following.
911 // declaration whose locus is contained by the scope to which the
912 // template-parameter belongs.
913 //
914 // When MSVC compatibility is enabled, the diagnostic is always a warning
915 // by default. Otherwise, it an error unless SupportedForCompatibility is
916 // true, in which case it is a default-to-error warning.
917 unsigned DiagId =
918 getLangOpts().MSVCCompat
919 ? diag::ext_template_param_shadow
920 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
921 : diag::err_template_param_shadow);
922 const auto *ND = cast<NamedDecl>(PrevDecl);
923 Diag(Loc, DiagId) << ND->getDeclName();
925}
926
928 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
929 D = Temp->getTemplatedDecl();
930 return Temp;
931 }
932 return nullptr;
933}
934
936 SourceLocation EllipsisLoc) const {
937 assert(Kind == Template &&
938 "Only template template arguments can be pack expansions here");
939 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
940 "Template template argument pack expansion without packs");
942 Result.EllipsisLoc = EllipsisLoc;
943 return Result;
944}
945
947 const ParsedTemplateArgument &Arg) {
948
949 switch (Arg.getKind()) {
951 TypeSourceInfo *TSI;
952 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
953 if (!TSI)
954 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
956 }
957
959 Expr *E = Arg.getAsExpr();
960 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
961 }
962
965 TemplateArgument TArg;
966 if (Arg.getEllipsisLoc().isValid())
967 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
968 else
969 TArg = Template;
970 return TemplateArgumentLoc(
971 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
973 Arg.getNameLoc(), Arg.getEllipsisLoc());
974 }
975 }
976
977 llvm_unreachable("Unhandled parsed template argument");
978}
979
981 TemplateArgumentListInfo &TemplateArgs) {
982 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
983 TemplateArgs.addArgument(translateTemplateArgument(*this,
984 TemplateArgsIn[I]));
985}
986
988 SourceLocation Loc,
989 const IdentifierInfo *Name) {
990 NamedDecl *PrevDecl =
991 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
993 if (PrevDecl && PrevDecl->isTemplateParameter())
994 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
995}
996
998 TypeSourceInfo *TInfo;
999 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1000 if (T.isNull())
1001 return ParsedTemplateArgument();
1002 assert(TInfo && "template argument with no location");
1003
1004 // If we might have formed a deduced template specialization type, convert
1005 // it to a template template argument.
1006 if (getLangOpts().CPlusPlus17) {
1007 TypeLoc TL = TInfo->getTypeLoc();
1008 SourceLocation EllipsisLoc;
1009 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1010 EllipsisLoc = PET.getEllipsisLoc();
1011 TL = PET.getPatternLoc();
1012 }
1013
1014 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1015 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1016 CXXScopeSpec SS;
1017 SS.Adopt(DTST.getQualifierLoc());
1018 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1019 TemplateTy::make(Name),
1020 DTST.getTemplateNameLoc());
1021 if (EllipsisLoc.isValid())
1022 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1023 return Result;
1024 }
1025 }
1026
1027 // This is a normal type template argument. Note, if the type template
1028 // argument is an injected-class-name for a template, it has a dual nature
1029 // and can be used as either a type or a template. We handle that in
1030 // convertTypeTemplateArgumentToTemplate.
1032 ParsedType.get().getAsOpaquePtr(),
1033 TInfo->getTypeLoc().getBeginLoc());
1034}
1035
1037 SourceLocation EllipsisLoc,
1038 SourceLocation KeyLoc,
1039 IdentifierInfo *ParamName,
1040 SourceLocation ParamNameLoc,
1041 unsigned Depth, unsigned Position,
1042 SourceLocation EqualLoc,
1043 ParsedType DefaultArg,
1044 bool HasTypeConstraint) {
1045 assert(S->isTemplateParamScope() &&
1046 "Template type parameter not in template parameter scope!");
1047
1048 bool IsParameterPack = EllipsisLoc.isValid();
1050 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1051 KeyLoc, ParamNameLoc, Depth, Position,
1052 ParamName, Typename, IsParameterPack,
1053 HasTypeConstraint);
1054 Param->setAccess(AS_public);
1055
1056 if (Param->isParameterPack())
1057 if (auto *CSI = getEnclosingLambdaOrBlock())
1058 CSI->LocalPacks.push_back(Param);
1059
1060 if (ParamName) {
1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062
1063 // Add the template parameter into the current scope.
1064 S->AddDecl(Param);
1065 IdResolver.AddDecl(Param);
1066 }
1067
1068 // C++0x [temp.param]p9:
1069 // A default template-argument may be specified for any kind of
1070 // template-parameter that is not a template parameter pack.
1071 if (DefaultArg && IsParameterPack) {
1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073 DefaultArg = nullptr;
1074 }
1075
1076 // Handle the default argument, if provided.
1077 if (DefaultArg) {
1078 TypeSourceInfo *DefaultTInfo;
1079 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080
1081 assert(DefaultTInfo && "expected source information for type");
1082
1083 // Check for unexpanded parameter packs.
1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1086 return Param;
1087
1088 // Check the template argument itself.
1089 if (CheckTemplateArgument(DefaultTInfo)) {
1090 Param->setInvalidDecl();
1091 return Param;
1092 }
1093
1094 Param->setDefaultArgument(
1095 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1096 }
1097
1098 return Param;
1099}
1100
1101/// Convert the parser's template argument list representation into our form.
1104 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1105 TemplateId.RAngleLoc);
1106 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1107 TemplateId.NumArgs);
1108 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1109 return TemplateArgs;
1110}
1111
1113
1114 TemplateName TN = TypeConstr->Template.get();
1115 NamedDecl *CD = nullptr;
1116 bool IsTypeConcept = false;
1117 bool RequiresArguments = false;
1118 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1119 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1120 RequiresArguments =
1121 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1122 CD = TTP;
1123 } else {
1124 CD = TN.getAsTemplateDecl();
1125 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1126 RequiresArguments = cast<ConceptDecl>(CD)
1127 ->getTemplateParameters()
1128 ->getMinRequiredArguments() > 1;
1129 }
1130
1131 // C++2a [temp.param]p4:
1132 // [...] The concept designated by a type-constraint shall be a type
1133 // concept ([temp.concept]).
1134 if (!IsTypeConcept) {
1135 Diag(TypeConstr->TemplateNameLoc,
1136 diag::err_type_constraint_non_type_concept);
1137 return true;
1138 }
1139
1140 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1141 return true;
1142
1143 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1144
1145 if (!WereArgsSpecified && RequiresArguments) {
1146 Diag(TypeConstr->TemplateNameLoc,
1147 diag::err_type_constraint_missing_arguments)
1148 << CD;
1149 return true;
1150 }
1151 return false;
1152}
1153
1155 TemplateIdAnnotation *TypeConstr,
1156 TemplateTypeParmDecl *ConstrainedParameter,
1157 SourceLocation EllipsisLoc) {
1158 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1159 false);
1160}
1161
1163 TemplateIdAnnotation *TypeConstr,
1164 TemplateTypeParmDecl *ConstrainedParameter,
1165 SourceLocation EllipsisLoc,
1166 bool AllowUnexpandedPack) {
1167
1168 if (CheckTypeConstraint(TypeConstr))
1169 return true;
1170
1171 TemplateName TN = TypeConstr->Template.get();
1174
1175 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1176 TypeConstr->TemplateNameLoc);
1177
1178 TemplateArgumentListInfo TemplateArgs;
1179 if (TypeConstr->LAngleLoc.isValid()) {
1180 TemplateArgs =
1181 makeTemplateArgumentListInfo(*this, *TypeConstr);
1182
1183 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1184 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1186 return true;
1187 }
1188 }
1189 }
1190 return AttachTypeConstraint(
1192 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1193 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1194 ConstrainedParameter, EllipsisLoc);
1195}
1196
1197template <typename ArgumentLocAppender>
1200 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1201 SourceLocation RAngleLoc, QualType ConstrainedType,
1202 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1203 SourceLocation EllipsisLoc) {
1204
1205 TemplateArgumentListInfo ConstraintArgs;
1206 ConstraintArgs.addArgument(
1208 /*NTTPType=*/QualType(), ParamNameLoc));
1209
1210 ConstraintArgs.setRAngleLoc(RAngleLoc);
1211 ConstraintArgs.setLAngleLoc(LAngleLoc);
1212 Appender(ConstraintArgs);
1213
1214 // C++2a [temp.param]p4:
1215 // [...] This constraint-expression E is called the immediately-declared
1216 // constraint of T. [...]
1217 CXXScopeSpec SS;
1218 SS.Adopt(NS);
1219 ExprResult ImmediatelyDeclaredConstraint;
1220 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1221 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1222 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1223 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1224 /*DoCheckConstraintSatisfaction=*/
1226 }
1227 // We have a template template parameter
1228 else {
1229 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1230 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1231 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1232 }
1233 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1234 return ImmediatelyDeclaredConstraint;
1235
1236 // C++2a [temp.param]p4:
1237 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1238 //
1239 // We have the following case:
1240 //
1241 // template<typename T> concept C1 = true;
1242 // template<C1... T> struct s1;
1243 //
1244 // The constraint: (C1<T> && ...)
1245 //
1246 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1247 // any unqualified lookups for 'operator&&' here.
1248 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1249 /*LParenLoc=*/SourceLocation(),
1250 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1251 EllipsisLoc, /*RHS=*/nullptr,
1252 /*RParenLoc=*/SourceLocation(),
1253 /*NumExpansions=*/std::nullopt);
1254}
1255
1257 DeclarationNameInfo NameInfo,
1258 TemplateDecl *NamedConcept,
1259 NamedDecl *FoundDecl,
1260 const TemplateArgumentListInfo *TemplateArgs,
1261 TemplateTypeParmDecl *ConstrainedParameter,
1262 SourceLocation EllipsisLoc) {
1263 // C++2a [temp.param]p4:
1264 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1265 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1266 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1268 *TemplateArgs) : nullptr;
1269
1270 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1271
1272 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1273 *this, NS, NameInfo, NamedConcept, FoundDecl,
1274 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1275 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1276 ParamAsArgument, ConstrainedParameter->getLocation(),
1277 [&](TemplateArgumentListInfo &ConstraintArgs) {
1278 if (TemplateArgs)
1279 for (const auto &ArgLoc : TemplateArgs->arguments())
1280 ConstraintArgs.addArgument(ArgLoc);
1281 },
1282 EllipsisLoc);
1283 if (ImmediatelyDeclaredConstraint.isInvalid())
1284 return true;
1285
1286 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1287 /*TemplateKWLoc=*/SourceLocation{},
1288 /*ConceptNameInfo=*/NameInfo,
1289 /*FoundDecl=*/FoundDecl,
1290 /*NamedConcept=*/NamedConcept,
1291 /*ArgsWritten=*/ArgsAsWritten);
1292 ConstrainedParameter->setTypeConstraint(
1293 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1294 return false;
1295}
1296
1298 NonTypeTemplateParmDecl *NewConstrainedParm,
1299 NonTypeTemplateParmDecl *OrigConstrainedParm,
1300 SourceLocation EllipsisLoc) {
1301 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1303 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1304 diag::err_unsupported_placeholder_constraint)
1305 << NewConstrainedParm->getTypeSourceInfo()
1306 ->getTypeLoc()
1307 .getSourceRange();
1308 return true;
1309 }
1310 // FIXME: Concepts: This should be the type of the placeholder, but this is
1311 // unclear in the wording right now.
1312 DeclRefExpr *Ref =
1313 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1314 VK_PRValue, OrigConstrainedParm->getLocation());
1315 if (!Ref)
1316 return true;
1317 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1319 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1321 OrigConstrainedParm->getLocation(),
1322 [&](TemplateArgumentListInfo &ConstraintArgs) {
1323 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1324 ConstraintArgs.addArgument(TL.getArgLoc(I));
1325 },
1326 EllipsisLoc);
1327 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1328 !ImmediatelyDeclaredConstraint.isUsable())
1329 return true;
1330
1331 NewConstrainedParm->setPlaceholderTypeConstraint(
1332 ImmediatelyDeclaredConstraint.get());
1333 return false;
1334}
1335
1337 SourceLocation Loc) {
1338 if (TSI->getType()->isUndeducedType()) {
1339 // C++17 [temp.dep.expr]p3:
1340 // An id-expression is type-dependent if it contains
1341 // - an identifier associated by name lookup with a non-type
1342 // template-parameter declared with a type that contains a
1343 // placeholder type (7.1.7.4),
1345 if (!NewTSI)
1346 return QualType();
1347 TSI = NewTSI;
1348 }
1349
1350 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1351}
1352
1354 if (T->isDependentType())
1355 return false;
1356
1357 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1358 return true;
1359
1360 if (T->isStructuralType())
1361 return false;
1362
1363 // Structural types are required to be object types or lvalue references.
1364 if (T->isRValueReferenceType()) {
1365 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1366 return true;
1367 }
1368
1369 // Don't mention structural types in our diagnostic prior to C++20. Also,
1370 // there's not much more we can say about non-scalar non-class types --
1371 // because we can't see functions or arrays here, those can only be language
1372 // extensions.
1373 if (!getLangOpts().CPlusPlus20 ||
1374 (!T->isScalarType() && !T->isRecordType())) {
1375 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1376 return true;
1377 }
1378
1379 // Structural types are required to be literal types.
1380 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1381 return true;
1382
1383 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1384
1385 // Drill down into the reason why the class is non-structural.
1386 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1387 // All members are required to be public and non-mutable, and can't be of
1388 // rvalue reference type. Check these conditions first to prefer a "local"
1389 // reason over a more distant one.
1390 for (const FieldDecl *FD : RD->fields()) {
1391 if (FD->getAccess() != AS_public) {
1392 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1393 return true;
1394 }
1395 if (FD->isMutable()) {
1396 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1397 return true;
1398 }
1399 if (FD->getType()->isRValueReferenceType()) {
1400 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1401 << T;
1402 return true;
1403 }
1404 }
1405
1406 // All bases are required to be public.
1407 for (const auto &BaseSpec : RD->bases()) {
1408 if (BaseSpec.getAccessSpecifier() != AS_public) {
1409 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1410 << T << 1;
1411 return true;
1412 }
1413 }
1414
1415 // All subobjects are required to be of structural types.
1416 SourceLocation SubLoc;
1417 QualType SubType;
1418 int Kind = -1;
1419
1420 for (const FieldDecl *FD : RD->fields()) {
1421 QualType T = Context.getBaseElementType(FD->getType());
1422 if (!T->isStructuralType()) {
1423 SubLoc = FD->getLocation();
1424 SubType = T;
1425 Kind = 0;
1426 break;
1427 }
1428 }
1429
1430 if (Kind == -1) {
1431 for (const auto &BaseSpec : RD->bases()) {
1432 QualType T = BaseSpec.getType();
1433 if (!T->isStructuralType()) {
1434 SubLoc = BaseSpec.getBaseTypeLoc();
1435 SubType = T;
1436 Kind = 1;
1437 break;
1438 }
1439 }
1440 }
1441
1442 assert(Kind != -1 && "couldn't find reason why type is not structural");
1443 Diag(SubLoc, diag::note_not_structural_subobject)
1444 << T << Kind << SubType;
1445 T = SubType;
1446 RD = T->getAsCXXRecordDecl();
1447 }
1448
1449 return true;
1450}
1451
1453 SourceLocation Loc) {
1454 // We don't allow variably-modified types as the type of non-type template
1455 // parameters.
1456 if (T->isVariablyModifiedType()) {
1457 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1458 << T;
1459 return QualType();
1460 }
1461
1462 // C++ [temp.param]p4:
1463 //
1464 // A non-type template-parameter shall have one of the following
1465 // (optionally cv-qualified) types:
1466 //
1467 // -- integral or enumeration type,
1468 if (T->isIntegralOrEnumerationType() ||
1469 // -- pointer to object or pointer to function,
1470 T->isPointerType() ||
1471 // -- lvalue reference to object or lvalue reference to function,
1472 T->isLValueReferenceType() ||
1473 // -- pointer to member,
1474 T->isMemberPointerType() ||
1475 // -- std::nullptr_t, or
1476 T->isNullPtrType() ||
1477 // -- a type that contains a placeholder type.
1478 T->isUndeducedType()) {
1479 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1480 // are ignored when determining its type.
1481 return T.getUnqualifiedType();
1482 }
1483
1484 // C++ [temp.param]p8:
1485 //
1486 // A non-type template-parameter of type "array of T" or
1487 // "function returning T" is adjusted to be of type "pointer to
1488 // T" or "pointer to function returning T", respectively.
1489 if (T->isArrayType() || T->isFunctionType())
1490 return Context.getDecayedType(T);
1491
1492 // If T is a dependent type, we can't do the check now, so we
1493 // assume that it is well-formed. Note that stripping off the
1494 // qualifiers here is not really correct if T turns out to be
1495 // an array type, but we'll recompute the type everywhere it's
1496 // used during instantiation, so that should be OK. (Using the
1497 // qualified type is equally wrong.)
1498 if (T->isDependentType())
1499 return T.getUnqualifiedType();
1500
1501 // C++20 [temp.param]p6:
1502 // -- a structural type
1503 if (RequireStructuralType(T, Loc))
1504 return QualType();
1505
1506 if (!getLangOpts().CPlusPlus20) {
1507 // FIXME: Consider allowing structural types as an extension in C++17. (In
1508 // earlier language modes, the template argument evaluation rules are too
1509 // inflexible.)
1510 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1511 return QualType();
1512 }
1513
1514 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1515 return T.getUnqualifiedType();
1516}
1517
1519 unsigned Depth,
1520 unsigned Position,
1521 SourceLocation EqualLoc,
1522 Expr *Default) {
1524
1525 // Check that we have valid decl-specifiers specified.
1526 auto CheckValidDeclSpecifiers = [this, &D] {
1527 // C++ [temp.param]
1528 // p1
1529 // template-parameter:
1530 // ...
1531 // parameter-declaration
1532 // p2
1533 // ... A storage class shall not be specified in a template-parameter
1534 // declaration.
1535 // [dcl.typedef]p1:
1536 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1537 // of a parameter-declaration
1538 const DeclSpec &DS = D.getDeclSpec();
1539 auto EmitDiag = [this](SourceLocation Loc) {
1540 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1542 };
1544 EmitDiag(DS.getStorageClassSpecLoc());
1545
1547 EmitDiag(DS.getThreadStorageClassSpecLoc());
1548
1549 // [dcl.inline]p1:
1550 // The inline specifier can be applied only to the declaration or
1551 // definition of a variable or function.
1552
1553 if (DS.isInlineSpecified())
1554 EmitDiag(DS.getInlineSpecLoc());
1555
1556 // [dcl.constexpr]p1:
1557 // The constexpr specifier shall be applied only to the definition of a
1558 // variable or variable template or the declaration of a function or
1559 // function template.
1560
1561 if (DS.hasConstexprSpecifier())
1562 EmitDiag(DS.getConstexprSpecLoc());
1563
1564 // [dcl.fct.spec]p1:
1565 // Function-specifiers can be used only in function declarations.
1566
1567 if (DS.isVirtualSpecified())
1568 EmitDiag(DS.getVirtualSpecLoc());
1569
1570 if (DS.hasExplicitSpecifier())
1571 EmitDiag(DS.getExplicitSpecLoc());
1572
1573 if (DS.isNoreturnSpecified())
1574 EmitDiag(DS.getNoreturnSpecLoc());
1575 };
1576
1577 CheckValidDeclSpecifiers();
1578
1579 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1580 if (isa<AutoType>(T))
1582 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1583 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1584
1585 assert(S->isTemplateParamScope() &&
1586 "Non-type template parameter not in template parameter scope!");
1587 bool Invalid = false;
1588
1590 if (T.isNull()) {
1591 T = Context.IntTy; // Recover with an 'int' type.
1592 Invalid = true;
1593 }
1594
1596
1597 const IdentifierInfo *ParamName = D.getIdentifier();
1598 bool IsParameterPack = D.hasEllipsis();
1600 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1601 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1602 TInfo);
1603 Param->setAccess(AS_public);
1604
1606 if (TL.isConstrained()) {
1607 if (D.getEllipsisLoc().isInvalid() &&
1608 T->containsUnexpandedParameterPack()) {
1609 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1610 for (auto &Loc :
1611 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1614 }
1615 if (!Invalid &&
1616 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1617 Invalid = true;
1618 }
1619
1620 if (Invalid)
1621 Param->setInvalidDecl();
1622
1623 if (Param->isParameterPack())
1624 if (auto *CSI = getEnclosingLambdaOrBlock())
1625 CSI->LocalPacks.push_back(Param);
1626
1627 if (ParamName) {
1629 ParamName);
1630
1631 // Add the template parameter into the current scope.
1632 S->AddDecl(Param);
1633 IdResolver.AddDecl(Param);
1634 }
1635
1636 // C++0x [temp.param]p9:
1637 // A default template-argument may be specified for any kind of
1638 // template-parameter that is not a template parameter pack.
1639 if (Default && IsParameterPack) {
1640 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1641 Default = nullptr;
1642 }
1643
1644 // Check the well-formedness of the default template argument, if provided.
1645 if (Default) {
1646 // Check for unexpanded parameter packs.
1648 return Param;
1649
1650 Param->setDefaultArgument(
1652 TemplateArgument(Default, /*IsCanonical=*/false),
1653 QualType(), SourceLocation()));
1654 }
1655
1656 return Param;
1657}
1658
1659/// ActOnTemplateTemplateParameter - Called when a C++ template template
1660/// parameter (e.g. T in template <template <typename> class T> class array)
1661/// has been parsed. S is the current scope.
1663 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1664 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1665 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1666 unsigned Position, SourceLocation EqualLoc,
1668 assert(S->isTemplateParamScope() &&
1669 "Template template parameter not in template parameter scope!");
1670
1671 bool IsParameterPack = EllipsisLoc.isValid();
1672
1673 bool Invalid = false;
1675 Params,
1676 /*OldParams=*/nullptr,
1677 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1678 Invalid = true;
1679
1680 // Construct the parameter object.
1682 Context, Context.getTranslationUnitDecl(),
1683 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1684 Name, Kind, Typename, Params);
1685 Param->setAccess(AS_public);
1686
1687 if (Param->isParameterPack())
1688 if (auto *LSI = getEnclosingLambdaOrBlock())
1689 LSI->LocalPacks.push_back(Param);
1690
1691 // If the template template parameter has a name, then link the identifier
1692 // into the scope and lookup mechanisms.
1693 if (Name) {
1694 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1695
1696 S->AddDecl(Param);
1697 IdResolver.AddDecl(Param);
1698 }
1699
1700 if (Params->size() == 0) {
1701 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1702 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1703 Invalid = true;
1704 }
1705
1706 if (Invalid)
1707 Param->setInvalidDecl();
1708
1709 // C++0x [temp.param]p9:
1710 // A default template-argument may be specified for any kind of
1711 // template-parameter that is not a template parameter pack.
1712 if (IsParameterPack && !Default.isInvalid()) {
1713 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1715 }
1716
1717 if (!Default.isInvalid()) {
1718 // Check only that we have a template template argument. We don't want to
1719 // try to check well-formedness now, because our template template parameter
1720 // might have dependent types in its template parameters, which we wouldn't
1721 // be able to match now.
1722 //
1723 // If none of the template template parameter's template arguments mention
1724 // other template parameters, we could actually perform more checking here.
1725 // However, it isn't worth doing.
1727 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1728 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1729 << DefaultArg.getSourceRange();
1730 return Param;
1731 }
1732
1733 TemplateName Name =
1736 if (Template &&
1738 return Param;
1739 }
1740
1741 // Check for unexpanded parameter packs.
1743 DefaultArg.getArgument().getAsTemplate(),
1745 return Param;
1746
1747 Param->setDefaultArgument(Context, DefaultArg);
1748 }
1749
1750 return Param;
1751}
1752
1753namespace {
1754class ConstraintRefersToContainingTemplateChecker
1756 using inherited = ConstDynamicRecursiveASTVisitor;
1757 bool Result = false;
1758 const FunctionDecl *Friend = nullptr;
1759 unsigned TemplateDepth = 0;
1760
1761 // Check a record-decl that we've seen to see if it is a lexical parent of the
1762 // Friend, likely because it was referred to without its template arguments.
1763 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1764 CheckingRD = CheckingRD->getMostRecentDecl();
1765 if (!CheckingRD->isTemplated())
1766 return true;
1767
1768 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1769 DC && !DC->isFileContext(); DC = DC->getParent())
1770 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1771 if (CheckingRD == RD->getMostRecentDecl()) {
1772 Result = true;
1773 return false;
1774 }
1775
1776 return true;
1777 }
1778
1779 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1780 if (D->getDepth() < TemplateDepth)
1781 Result = true;
1782
1783 // Necessary because the type of the NTTP might be what refers to the parent
1784 // constriant.
1785 return TraverseType(D->getType());
1786 }
1787
1788public:
1789 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1790 unsigned TemplateDepth)
1791 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1792
1793 bool getResult() const { return Result; }
1794
1795 // This should be the only template parm type that we have to deal with.
1796 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1797 // FunctionParmPackExpr are all partially substituted, which cannot happen
1798 // with concepts at this point in translation.
1799 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1800 if (Type->getDecl()->getDepth() < TemplateDepth) {
1801 Result = true;
1802 return false;
1803 }
1804 return true;
1805 }
1806
1807 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1808 return TraverseDecl(E->getDecl());
1809 }
1810
1811 bool TraverseTypedefType(const TypedefType *TT,
1812 bool /*TraverseQualifier*/) override {
1813 return TraverseType(TT->desugar());
1814 }
1815
1816 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1817 // We don't care about TypeLocs. So traverse Types instead.
1818 return TraverseType(TL.getType(), TraverseQualifier);
1819 }
1820
1821 bool VisitTagType(const TagType *T) override {
1822 return TraverseDecl(T->getDecl());
1823 }
1824
1825 bool TraverseDecl(const Decl *D) override {
1826 assert(D);
1827 // FIXME : This is possibly an incomplete list, but it is unclear what other
1828 // Decl kinds could be used to refer to the template parameters. This is a
1829 // best guess so far based on examples currently available, but the
1830 // unreachable should catch future instances/cases.
1831 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1832 return TraverseType(TD->getUnderlyingType());
1833 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1834 return CheckNonTypeTemplateParmDecl(NTTPD);
1835 if (auto *VD = dyn_cast<ValueDecl>(D))
1836 return TraverseType(VD->getType());
1837 if (isa<TemplateDecl>(D))
1838 return true;
1839 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1840 return CheckIfContainingRecord(RD);
1841
1843 // No direct types to visit here I believe.
1844 } else
1845 llvm_unreachable("Don't know how to handle this declaration type yet");
1846 return true;
1847 }
1848};
1849} // namespace
1850
1852 const FunctionDecl *Friend, unsigned TemplateDepth,
1853 const Expr *Constraint) {
1854 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1855 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1856 Checker.TraverseStmt(Constraint);
1857 return Checker.getResult();
1858}
1859
1862 SourceLocation ExportLoc,
1863 SourceLocation TemplateLoc,
1864 SourceLocation LAngleLoc,
1865 ArrayRef<NamedDecl *> Params,
1866 SourceLocation RAngleLoc,
1867 Expr *RequiresClause) {
1868 if (ExportLoc.isValid())
1869 Diag(ExportLoc, diag::warn_template_export_unsupported);
1870
1871 for (NamedDecl *P : Params)
1873
1874 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1875 llvm::ArrayRef(Params), RAngleLoc,
1876 RequiresClause);
1877}
1878
1880 const CXXScopeSpec &SS) {
1881 if (SS.isSet())
1882 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1883}
1884
1885// Returns the template parameter list with all default template argument
1886// information.
1888 // Make sure we get the template parameter list from the most
1889 // recent declaration, since that is the only one that is guaranteed to
1890 // have all the default template argument information.
1891 Decl *D = TD->getMostRecentDecl();
1892 // C++11 N3337 [temp.param]p12:
1893 // A default template argument shall not be specified in a friend class
1894 // template declaration.
1895 //
1896 // Skip past friend *declarations* because they are not supposed to contain
1897 // default template arguments. Moreover, these declarations may introduce
1898 // template parameters living in different template depths than the
1899 // corresponding template parameters in TD, causing unmatched constraint
1900 // substitution.
1901 //
1902 // FIXME: Diagnose such cases within a class template:
1903 // template <class T>
1904 // struct S {
1905 // template <class = void> friend struct C;
1906 // };
1907 // template struct S<int>;
1909 D->getPreviousDecl())
1910 D = D->getPreviousDecl();
1911 return cast<TemplateDecl>(D)->getTemplateParameters();
1912}
1913
1915 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1916 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1917 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1918 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1919 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1920 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1921 assert(TemplateParams && TemplateParams->size() > 0 &&
1922 "No template parameters");
1923 assert(TUK != TagUseKind::Reference &&
1924 "Can only declare or define class templates");
1925 bool Invalid = false;
1926
1927 // Check that we can declare a template here.
1928 if (CheckTemplateDeclScope(S, TemplateParams))
1929 return true;
1930
1932 assert(Kind != TagTypeKind::Enum &&
1933 "can't build template of enumerated type");
1934
1935 // There is no such thing as an unnamed class template.
1936 if (!Name) {
1937 Diag(KWLoc, diag::err_template_unnamed_class);
1938 return true;
1939 }
1940
1941 // Find any previous declaration with this name. For a friend with no
1942 // scope explicitly specified, we only look for tag declarations (per
1943 // C++11 [basic.lookup.elab]p2).
1944 DeclContext *SemanticContext;
1945 LookupResult Previous(*this, Name, NameLoc,
1946 (SS.isEmpty() && TUK == TagUseKind::Friend)
1950 if (SS.isNotEmpty() && !SS.isInvalid()) {
1951 SemanticContext = computeDeclContext(SS, true);
1952 if (!SemanticContext) {
1953 // FIXME: Horrible, horrible hack! We can't currently represent this
1954 // in the AST, and historically we have just ignored such friend
1955 // class templates, so don't complain here.
1956 Diag(NameLoc, TUK == TagUseKind::Friend
1957 ? diag::warn_template_qualified_friend_ignored
1958 : diag::err_template_qualified_declarator_no_match)
1959 << SS.getScopeRep() << SS.getRange();
1960 return TUK != TagUseKind::Friend;
1961 }
1962
1963 if (RequireCompleteDeclContext(SS, SemanticContext))
1964 return true;
1965
1966 // If we're adding a template to a dependent context, we may need to
1967 // rebuilding some of the types used within the template parameter list,
1968 // now that we know what the current instantiation is.
1969 if (SemanticContext->isDependentContext()) {
1970 ContextRAII SavedContext(*this, SemanticContext);
1972 Invalid = true;
1973 }
1974
1975 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1976 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1977 /*TemplateId-*/ nullptr,
1978 /*IsMemberSpecialization*/ false);
1979
1980 LookupQualifiedName(Previous, SemanticContext);
1981 } else {
1982 SemanticContext = CurContext;
1983
1984 // C++14 [class.mem]p14:
1985 // If T is the name of a class, then each of the following shall have a
1986 // name different from T:
1987 // -- every member template of class T
1988 if (TUK != TagUseKind::Friend &&
1989 DiagnoseClassNameShadow(SemanticContext,
1990 DeclarationNameInfo(Name, NameLoc)))
1991 return true;
1992
1993 LookupName(Previous, S);
1994 }
1995
1996 if (Previous.isAmbiguous())
1997 return true;
1998
1999 // Let the template parameter scope enter the lookup chain of the current
2000 // class template. For example, given
2001 //
2002 // namespace ns {
2003 // template <class> bool Param = false;
2004 // template <class T> struct N;
2005 // }
2006 //
2007 // template <class Param> struct ns::N { void foo(Param); };
2008 //
2009 // When we reference Param inside the function parameter list, our name lookup
2010 // chain for it should be like:
2011 // FunctionScope foo
2012 // -> RecordScope N
2013 // -> TemplateParamScope (where we will find Param)
2014 // -> NamespaceScope ns
2015 //
2016 // See also CppLookupName().
2017 if (S->isTemplateParamScope())
2018 EnterTemplatedContext(S, SemanticContext);
2019
2020 NamedDecl *PrevDecl = nullptr;
2021 if (Previous.begin() != Previous.end())
2022 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2023
2024 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2025 // Maybe we will complain about the shadowed template parameter.
2026 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2027 // Just pretend that we didn't see the previous declaration.
2028 PrevDecl = nullptr;
2029 }
2030
2031 // If there is a previous declaration with the same name, check
2032 // whether this is a valid redeclaration.
2033 ClassTemplateDecl *PrevClassTemplate =
2034 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2035
2036 // We may have found the injected-class-name of a class template,
2037 // class template partial specialization, or class template specialization.
2038 // In these cases, grab the template that is being defined or specialized.
2039 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2040 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2041 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2042 PrevClassTemplate
2043 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2044 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2045 PrevClassTemplate
2047 ->getSpecializedTemplate();
2048 }
2049 }
2050
2051 if (TUK == TagUseKind::Friend) {
2052 // C++ [namespace.memdef]p3:
2053 // [...] When looking for a prior declaration of a class or a function
2054 // declared as a friend, and when the name of the friend class or
2055 // function is neither a qualified name nor a template-id, scopes outside
2056 // the innermost enclosing namespace scope are not considered.
2057 if (!SS.isSet()) {
2058 DeclContext *OutermostContext = CurContext;
2059 while (!OutermostContext->isFileContext())
2060 OutermostContext = OutermostContext->getLookupParent();
2061
2062 if (PrevDecl &&
2063 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2064 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2065 SemanticContext = PrevDecl->getDeclContext();
2066 } else {
2067 // Declarations in outer scopes don't matter. However, the outermost
2068 // context we computed is the semantic context for our new
2069 // declaration.
2070 PrevDecl = PrevClassTemplate = nullptr;
2071 SemanticContext = OutermostContext;
2072
2073 // Check that the chosen semantic context doesn't already contain a
2074 // declaration of this name as a non-tag type.
2076 DeclContext *LookupContext = SemanticContext;
2077 while (LookupContext->isTransparentContext())
2078 LookupContext = LookupContext->getLookupParent();
2079 LookupQualifiedName(Previous, LookupContext);
2080
2081 if (Previous.isAmbiguous())
2082 return true;
2083
2084 if (Previous.begin() != Previous.end())
2085 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2086 }
2087 }
2088 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2089 SemanticContext, S, SS.isValid()))
2090 PrevDecl = PrevClassTemplate = nullptr;
2091
2092 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2093 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2094 if (SS.isEmpty() &&
2095 !(PrevClassTemplate &&
2096 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2097 SemanticContext->getRedeclContext()))) {
2098 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2099 Diag(Shadow->getTargetDecl()->getLocation(),
2100 diag::note_using_decl_target);
2101 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2102 // Recover by ignoring the old declaration.
2103 PrevDecl = PrevClassTemplate = nullptr;
2104 }
2105 }
2106
2107 if (PrevClassTemplate) {
2108 // Ensure that the template parameter lists are compatible. Skip this check
2109 // for a friend in a dependent context: the template parameter list itself
2110 // could be dependent.
2111 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2113 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2114 : CurContext,
2115 CurContext, KWLoc),
2116 TemplateParams, PrevClassTemplate,
2117 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2119 return true;
2120
2121 // C++ [temp.class]p4:
2122 // In a redeclaration, partial specialization, explicit
2123 // specialization or explicit instantiation of a class template,
2124 // the class-key shall agree in kind with the original class
2125 // template declaration (7.1.5.3).
2126 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2128 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2129 Diag(KWLoc, diag::err_use_with_wrong_tag)
2130 << Name
2131 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2132 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2133 Kind = PrevRecordDecl->getTagKind();
2134 }
2135
2136 // Check for redefinition of this class template.
2137 if (TUK == TagUseKind::Definition) {
2138 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2139 // If we have a prior definition that is not visible, treat this as
2140 // simply making that previous definition visible.
2141 NamedDecl *Hidden = nullptr;
2142 bool HiddenDefVisible = false;
2143 if (SkipBody &&
2144 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2145 SkipBody->ShouldSkip = true;
2146 SkipBody->Previous = Def;
2147 if (!HiddenDefVisible && Hidden) {
2148 auto *Tmpl =
2149 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2150 assert(Tmpl && "original definition of a class template is not a "
2151 "class template?");
2154 }
2155 } else {
2156 Diag(NameLoc, diag::err_redefinition) << Name;
2157 Diag(Def->getLocation(), diag::note_previous_definition);
2158 // FIXME: Would it make sense to try to "forget" the previous
2159 // definition, as part of error recovery?
2160 return true;
2161 }
2162 }
2163 }
2164 } else if (PrevDecl) {
2165 // C++ [temp]p5:
2166 // A class template shall not have the same name as any other
2167 // template, class, function, object, enumeration, enumerator,
2168 // namespace, or type in the same scope (3.3), except as specified
2169 // in (14.5.4).
2170 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2171 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2172 return true;
2173 }
2174
2175 // Check the template parameter list of this declaration, possibly
2176 // merging in the template parameter list from the previous class
2177 // template declaration. Skip this check for a friend in a dependent
2178 // context, because the template parameter list might be dependent.
2179 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2181 TemplateParams,
2182 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2183 : nullptr,
2184 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2185 SemanticContext->isDependentContext())
2188 : TPC_Other,
2189 SkipBody))
2190 Invalid = true;
2191
2192 if (SS.isSet()) {
2193 // If the name of the template was qualified, we must be defining the
2194 // template out-of-line.
2195 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2196 Diag(NameLoc, TUK == TagUseKind::Friend
2197 ? diag::err_friend_decl_does_not_match
2198 : diag::err_member_decl_does_not_match)
2199 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2200 Invalid = true;
2201 }
2202 }
2203
2204 // If this is a templated friend in a dependent context we should not put it
2205 // on the redecl chain. In some cases, the templated friend can be the most
2206 // recent declaration tricking the template instantiator to make substitutions
2207 // there.
2208 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2209 bool ShouldAddRedecl =
2210 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2211
2213 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2214 PrevClassTemplate && ShouldAddRedecl
2215 ? PrevClassTemplate->getTemplatedDecl()
2216 : nullptr);
2217 SetNestedNameSpecifier(*this, NewClass, SS);
2218 if (NumOuterTemplateParamLists > 0)
2220 Context,
2221 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2222
2223 // Add alignment attributes if necessary; these attributes are checked when
2224 // the ASTContext lays out the structure.
2225 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2226 if (LangOpts.HLSL)
2227 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2230 }
2231
2232 ClassTemplateDecl *NewTemplate
2233 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2234 DeclarationName(Name), TemplateParams,
2235 NewClass);
2236
2237 if (ShouldAddRedecl)
2238 NewTemplate->setPreviousDecl(PrevClassTemplate);
2239
2240 NewClass->setDescribedClassTemplate(NewTemplate);
2241
2242 if (ModulePrivateLoc.isValid())
2243 NewTemplate->setModulePrivate();
2244
2245 // If we are providing an explicit specialization of a member that is a
2246 // class template, make a note of that.
2247 if (PrevClassTemplate &&
2248 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2249 PrevClassTemplate->setMemberSpecialization();
2250
2251 // Set the access specifier.
2252 if (!Invalid && TUK != TagUseKind::Friend &&
2253 NewTemplate->getDeclContext()->isRecord())
2254 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2255
2256 // Set the lexical context of these templates
2258 NewTemplate->setLexicalDeclContext(CurContext);
2259
2260 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2261 NewClass->startDefinition();
2262
2263 ProcessDeclAttributeList(S, NewClass, Attr);
2264
2265 if (PrevClassTemplate)
2266 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2267
2271
2272 if (TUK != TagUseKind::Friend) {
2273 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2274 Scope *Outer = S;
2275 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2276 Outer = Outer->getParent();
2277 PushOnScopeChains(NewTemplate, Outer);
2278 } else {
2279 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2280 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2281 NewClass->setAccess(PrevClassTemplate->getAccess());
2282 }
2283
2284 NewTemplate->setObjectOfFriendDecl();
2285
2286 // Friend templates are visible in fairly strange ways.
2287 if (!CurContext->isDependentContext()) {
2288 DeclContext *DC = SemanticContext->getRedeclContext();
2289 DC->makeDeclVisibleInContext(NewTemplate);
2290 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2291 PushOnScopeChains(NewTemplate, EnclosingScope,
2292 /* AddToContext = */ false);
2293 }
2294
2296 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2297 Friend->setAccess(AS_public);
2298 CurContext->addDecl(Friend);
2299 }
2300
2301 if (PrevClassTemplate)
2302 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2303
2304 if (Invalid) {
2305 NewTemplate->setInvalidDecl();
2306 NewClass->setInvalidDecl();
2307 }
2308
2309 ActOnDocumentableDecl(NewTemplate);
2310
2311 if (SkipBody && SkipBody->ShouldSkip)
2312 return SkipBody->Previous;
2313
2314 return NewTemplate;
2315}
2316
2317/// Diagnose the presence of a default template argument on a
2318/// template parameter, which is ill-formed in certain contexts.
2319///
2320/// \returns true if the default template argument should be dropped.
2323 SourceLocation ParamLoc,
2324 SourceRange DefArgRange) {
2325 switch (TPC) {
2326 case Sema::TPC_Other:
2328 return false;
2329
2332 // C++ [temp.param]p9:
2333 // A default template-argument shall not be specified in a
2334 // function template declaration or a function template
2335 // definition [...]
2336 // If a friend function template declaration specifies a default
2337 // template-argument, that declaration shall be a definition and shall be
2338 // the only declaration of the function template in the translation unit.
2339 // (C++98/03 doesn't have this wording; see DR226).
2340 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2341 << DefArgRange;
2342 return false;
2343
2345 // C++0x [temp.param]p9:
2346 // A default template-argument shall not be specified in the
2347 // template-parameter-lists of the definition of a member of a
2348 // class template that appears outside of the member's class.
2349 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2350 << DefArgRange;
2351 return true;
2352
2355 // C++ [temp.param]p9:
2356 // A default template-argument shall not be specified in a
2357 // friend template declaration.
2358 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2359 << DefArgRange;
2360 return true;
2361
2362 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2363 // for friend function templates if there is only a single
2364 // declaration (and it is a definition). Strange!
2365 }
2366
2367 llvm_unreachable("Invalid TemplateParamListContext!");
2368}
2369
2370/// Check for unexpanded parameter packs within the template parameters
2371/// of a template template parameter, recursively.
2374 // A template template parameter which is a parameter pack is also a pack
2375 // expansion.
2376 if (TTP->isParameterPack())
2377 return false;
2378
2380 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2381 NamedDecl *P = Params->getParam(I);
2382 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2383 if (!TTP->isParameterPack())
2384 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2385 if (TC->hasExplicitTemplateArgs())
2386 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2389 return true;
2390 continue;
2391 }
2392
2393 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2394 if (!NTTP->isParameterPack() &&
2395 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2396 NTTP->getTypeSourceInfo(),
2398 return true;
2399
2400 continue;
2401 }
2402
2403 if (TemplateTemplateParmDecl *InnerTTP
2404 = dyn_cast<TemplateTemplateParmDecl>(P))
2405 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2406 return true;
2407 }
2408
2409 return false;
2410}
2411
2413 TemplateParameterList *OldParams,
2415 SkipBodyInfo *SkipBody) {
2416 bool Invalid = false;
2417
2418 // C++ [temp.param]p10:
2419 // The set of default template-arguments available for use with a
2420 // template declaration or definition is obtained by merging the
2421 // default arguments from the definition (if in scope) and all
2422 // declarations in scope in the same way default function
2423 // arguments are (8.3.6).
2424 bool SawDefaultArgument = false;
2425 SourceLocation PreviousDefaultArgLoc;
2426
2427 // Dummy initialization to avoid warnings.
2428 TemplateParameterList::iterator OldParam = NewParams->end();
2429 if (OldParams)
2430 OldParam = OldParams->begin();
2431
2432 bool RemoveDefaultArguments = false;
2433 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2434 NewParamEnd = NewParams->end();
2435 NewParam != NewParamEnd; ++NewParam) {
2436 // Whether we've seen a duplicate default argument in the same translation
2437 // unit.
2438 bool RedundantDefaultArg = false;
2439 // Whether we've found inconsis inconsitent default arguments in different
2440 // translation unit.
2441 bool InconsistentDefaultArg = false;
2442 // The name of the module which contains the inconsistent default argument.
2443 std::string PrevModuleName;
2444
2445 SourceLocation OldDefaultLoc;
2446 SourceLocation NewDefaultLoc;
2447
2448 // Variable used to diagnose missing default arguments
2449 bool MissingDefaultArg = false;
2450
2451 // Variable used to diagnose non-final parameter packs
2452 bool SawParameterPack = false;
2453
2454 if (TemplateTypeParmDecl *NewTypeParm
2455 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2456 // Check the presence of a default argument here.
2457 if (NewTypeParm->hasDefaultArgument() &&
2459 *this, TPC, NewTypeParm->getLocation(),
2460 NewTypeParm->getDefaultArgument().getSourceRange()))
2461 NewTypeParm->removeDefaultArgument();
2462
2463 // Merge default arguments for template type parameters.
2464 TemplateTypeParmDecl *OldTypeParm
2465 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2466 if (NewTypeParm->isParameterPack()) {
2467 assert(!NewTypeParm->hasDefaultArgument() &&
2468 "Parameter packs can't have a default argument!");
2469 SawParameterPack = true;
2470 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2471 NewTypeParm->hasDefaultArgument() &&
2472 (!SkipBody || !SkipBody->ShouldSkip)) {
2473 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2474 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2475 SawDefaultArgument = true;
2476
2477 if (!OldTypeParm->getOwningModule())
2478 RedundantDefaultArg = true;
2479 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2480 NewTypeParm)) {
2481 InconsistentDefaultArg = true;
2482 PrevModuleName =
2484 }
2485 PreviousDefaultArgLoc = NewDefaultLoc;
2486 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2487 // Merge the default argument from the old declaration to the
2488 // new declaration.
2489 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2490 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2491 } else if (NewTypeParm->hasDefaultArgument()) {
2492 SawDefaultArgument = true;
2493 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2494 } else if (SawDefaultArgument)
2495 MissingDefaultArg = true;
2496 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2497 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2498 // Check for unexpanded parameter packs, except in a template template
2499 // parameter pack, as in those any unexpanded packs should be expanded
2500 // along with the parameter itself.
2502 !NewNonTypeParm->isParameterPack() &&
2503 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2504 NewNonTypeParm->getTypeSourceInfo(),
2506 Invalid = true;
2507 continue;
2508 }
2509
2510 // Check the presence of a default argument here.
2511 if (NewNonTypeParm->hasDefaultArgument() &&
2513 *this, TPC, NewNonTypeParm->getLocation(),
2514 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2515 NewNonTypeParm->removeDefaultArgument();
2516 }
2517
2518 // Merge default arguments for non-type template parameters
2519 NonTypeTemplateParmDecl *OldNonTypeParm
2520 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2521 if (NewNonTypeParm->isParameterPack()) {
2522 assert(!NewNonTypeParm->hasDefaultArgument() &&
2523 "Parameter packs can't have a default argument!");
2524 if (!NewNonTypeParm->isPackExpansion())
2525 SawParameterPack = true;
2526 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2527 NewNonTypeParm->hasDefaultArgument() &&
2528 (!SkipBody || !SkipBody->ShouldSkip)) {
2529 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2530 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2531 SawDefaultArgument = true;
2532 if (!OldNonTypeParm->getOwningModule())
2533 RedundantDefaultArg = true;
2534 else if (!getASTContext().isSameDefaultTemplateArgument(
2535 OldNonTypeParm, NewNonTypeParm)) {
2536 InconsistentDefaultArg = true;
2537 PrevModuleName =
2538 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2539 }
2540 PreviousDefaultArgLoc = NewDefaultLoc;
2541 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2542 // Merge the default argument from the old declaration to the
2543 // new declaration.
2544 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2545 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2546 } else if (NewNonTypeParm->hasDefaultArgument()) {
2547 SawDefaultArgument = true;
2548 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2549 } else if (SawDefaultArgument)
2550 MissingDefaultArg = true;
2551 } else {
2552 TemplateTemplateParmDecl *NewTemplateParm
2553 = cast<TemplateTemplateParmDecl>(*NewParam);
2554
2555 // Check for unexpanded parameter packs, recursively.
2556 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2557 Invalid = true;
2558 continue;
2559 }
2560
2561 // Check the presence of a default argument here.
2562 if (NewTemplateParm->hasDefaultArgument() &&
2564 NewTemplateParm->getLocation(),
2565 NewTemplateParm->getDefaultArgument().getSourceRange()))
2566 NewTemplateParm->removeDefaultArgument();
2567
2568 // Merge default arguments for template template parameters
2569 TemplateTemplateParmDecl *OldTemplateParm
2570 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2571 if (NewTemplateParm->isParameterPack()) {
2572 assert(!NewTemplateParm->hasDefaultArgument() &&
2573 "Parameter packs can't have a default argument!");
2574 if (!NewTemplateParm->isPackExpansion())
2575 SawParameterPack = true;
2576 } else if (OldTemplateParm &&
2577 hasVisibleDefaultArgument(OldTemplateParm) &&
2578 NewTemplateParm->hasDefaultArgument() &&
2579 (!SkipBody || !SkipBody->ShouldSkip)) {
2580 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2581 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2582 SawDefaultArgument = true;
2583 if (!OldTemplateParm->getOwningModule())
2584 RedundantDefaultArg = true;
2585 else if (!getASTContext().isSameDefaultTemplateArgument(
2586 OldTemplateParm, NewTemplateParm)) {
2587 InconsistentDefaultArg = true;
2588 PrevModuleName =
2589 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2590 }
2591 PreviousDefaultArgLoc = NewDefaultLoc;
2592 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2593 // Merge the default argument from the old declaration to the
2594 // new declaration.
2595 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2596 PreviousDefaultArgLoc
2597 = OldTemplateParm->getDefaultArgument().getLocation();
2598 } else if (NewTemplateParm->hasDefaultArgument()) {
2599 SawDefaultArgument = true;
2600 PreviousDefaultArgLoc
2601 = NewTemplateParm->getDefaultArgument().getLocation();
2602 } else if (SawDefaultArgument)
2603 MissingDefaultArg = true;
2604 }
2605
2606 // C++11 [temp.param]p11:
2607 // If a template parameter of a primary class template or alias template
2608 // is a template parameter pack, it shall be the last template parameter.
2609 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2610 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2611 Diag((*NewParam)->getLocation(),
2612 diag::err_template_param_pack_must_be_last_template_parameter);
2613 Invalid = true;
2614 }
2615
2616 // [basic.def.odr]/13:
2617 // There can be more than one definition of a
2618 // ...
2619 // default template argument
2620 // ...
2621 // in a program provided that each definition appears in a different
2622 // translation unit and the definitions satisfy the [same-meaning
2623 // criteria of the ODR].
2624 //
2625 // Simply, the design of modules allows the definition of template default
2626 // argument to be repeated across translation unit. Note that the ODR is
2627 // checked elsewhere. But it is still not allowed to repeat template default
2628 // argument in the same translation unit.
2629 if (RedundantDefaultArg) {
2630 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2631 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2632 Invalid = true;
2633 } else if (InconsistentDefaultArg) {
2634 // We could only diagnose about the case that the OldParam is imported.
2635 // The case NewParam is imported should be handled in ASTReader.
2636 Diag(NewDefaultLoc,
2637 diag::err_template_param_default_arg_inconsistent_redefinition);
2638 Diag(OldDefaultLoc,
2639 diag::note_template_param_prev_default_arg_in_other_module)
2640 << PrevModuleName;
2641 Invalid = true;
2642 } else if (MissingDefaultArg &&
2643 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2644 TPC == TPC_FriendClassTemplate)) {
2645 // C++ 23[temp.param]p14:
2646 // If a template-parameter of a class template, variable template, or
2647 // alias template has a default template argument, each subsequent
2648 // template-parameter shall either have a default template argument
2649 // supplied or be a template parameter pack.
2650 Diag((*NewParam)->getLocation(),
2651 diag::err_template_param_default_arg_missing);
2652 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2653 Invalid = true;
2654 RemoveDefaultArguments = true;
2655 }
2656
2657 // If we have an old template parameter list that we're merging
2658 // in, move on to the next parameter.
2659 if (OldParams)
2660 ++OldParam;
2661 }
2662
2663 // We were missing some default arguments at the end of the list, so remove
2664 // all of the default arguments.
2665 if (RemoveDefaultArguments) {
2666 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2667 NewParamEnd = NewParams->end();
2668 NewParam != NewParamEnd; ++NewParam) {
2669 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2670 TTP->removeDefaultArgument();
2671 else if (NonTypeTemplateParmDecl *NTTP
2672 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2673 NTTP->removeDefaultArgument();
2674 else
2675 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2676 }
2677 }
2678
2679 return Invalid;
2680}
2681
2682namespace {
2683
2684/// A class which looks for a use of a certain level of template
2685/// parameter.
2686struct DependencyChecker : DynamicRecursiveASTVisitor {
2687 unsigned Depth;
2688
2689 // Whether we're looking for a use of a template parameter that makes the
2690 // overall construct type-dependent / a dependent type. This is strictly
2691 // best-effort for now; we may fail to match at all for a dependent type
2692 // in some cases if this is set.
2693 bool IgnoreNonTypeDependent;
2694
2695 bool Match;
2696 SourceLocation MatchLoc;
2697
2698 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2699 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2700 Match(false) {}
2701
2702 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2703 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2704 NamedDecl *ND = Params->getParam(0);
2705 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2706 Depth = PD->getDepth();
2707 } else if (NonTypeTemplateParmDecl *PD =
2708 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2709 Depth = PD->getDepth();
2710 } else {
2711 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2712 }
2713 }
2714
2715 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2716 if (ParmDepth >= Depth) {
2717 Match = true;
2718 MatchLoc = Loc;
2719 return true;
2720 }
2721 return false;
2722 }
2723
2724 bool TraverseStmt(Stmt *S) override {
2725 // Prune out non-type-dependent expressions if requested. This can
2726 // sometimes result in us failing to find a template parameter reference
2727 // (if a value-dependent expression creates a dependent type), but this
2728 // mode is best-effort only.
2729 if (auto *E = dyn_cast_or_null<Expr>(S))
2730 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2731 return true;
2733 }
2734
2735 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2736 if (IgnoreNonTypeDependent && !TL.isNull() &&
2737 !TL.getType()->isDependentType())
2738 return true;
2739 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2740 }
2741
2742 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2743 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2744 }
2745
2746 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2747 // For a best-effort search, keep looking until we find a location.
2748 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2749 }
2750
2751 bool TraverseTemplateName(TemplateName N) override {
2752 if (TemplateTemplateParmDecl *PD =
2753 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2754 if (Matches(PD->getDepth()))
2755 return false;
2757 }
2758
2759 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2760 if (NonTypeTemplateParmDecl *PD =
2761 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2762 if (Matches(PD->getDepth(), E->getExprLoc()))
2763 return false;
2764 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2765 }
2766
2767 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2768 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2769 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2770 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2771 return false;
2772 }
2773 for (auto &TLoc : ULE->template_arguments())
2775 }
2776 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2777 }
2778
2779 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2780 return TraverseType(T->getReplacementType());
2781 }
2782
2783 bool VisitSubstTemplateTypeParmPackType(
2784 SubstTemplateTypeParmPackType *T) override {
2785 return TraverseTemplateArgument(T->getArgumentPack());
2786 }
2787
2788 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2789 bool TraverseQualifier) override {
2790 // An InjectedClassNameType will never have a dependent template name,
2791 // so no need to traverse it.
2792 return TraverseTemplateArguments(
2793 T->getTemplateArgs(T->getDecl()->getASTContext()));
2794 }
2795};
2796} // end anonymous namespace
2797
2798/// Determines whether a given type depends on the given parameter
2799/// list.
2800static bool
2802 if (!Params->size())
2803 return false;
2804
2805 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2806 Checker.TraverseType(T);
2807 return Checker.Match;
2808}
2809
2810// Find the source range corresponding to the named type in the given
2811// nested-name-specifier, if any.
2813 QualType T,
2814 const CXXScopeSpec &SS) {
2816 for (;;) {
2819 break;
2820 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2821 return NNSLoc.castAsTypeLoc().getSourceRange();
2822 // FIXME: This will always be empty.
2823 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2824 }
2825
2826 return SourceRange();
2827}
2828
2830 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2831 TemplateIdAnnotation *TemplateId,
2832 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2833 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2834 IsMemberSpecialization = false;
2835 Invalid = false;
2836
2837 // The sequence of nested types to which we will match up the template
2838 // parameter lists. We first build this list by starting with the type named
2839 // by the nested-name-specifier and walking out until we run out of types.
2840 SmallVector<QualType, 4> NestedTypes;
2841 QualType T;
2842 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2843 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2844 if (CXXRecordDecl *Record =
2845 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2846 T = Context.getCanonicalTagType(Record);
2847 else
2848 T = QualType(Qualifier.getAsType(), 0);
2849 }
2850
2851 // If we found an explicit specialization that prevents us from needing
2852 // 'template<>' headers, this will be set to the location of that
2853 // explicit specialization.
2854 SourceLocation ExplicitSpecLoc;
2855
2856 while (!T.isNull()) {
2857 NestedTypes.push_back(T);
2858
2859 // Retrieve the parent of a record type.
2860 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2861 // If this type is an explicit specialization, we're done.
2863 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2865 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2866 ExplicitSpecLoc = Spec->getLocation();
2867 break;
2868 }
2869 } else if (Record->getTemplateSpecializationKind()
2871 ExplicitSpecLoc = Record->getLocation();
2872 break;
2873 }
2874
2875 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2876 T = Context.getTypeDeclType(Parent);
2877 else
2878 T = QualType();
2879 continue;
2880 }
2881
2882 if (const TemplateSpecializationType *TST
2883 = T->getAs<TemplateSpecializationType>()) {
2884 TemplateName Name = TST->getTemplateName();
2885 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2886 // Look one step prior in a dependent template specialization type.
2887 if (NestedNameSpecifier NNS = DTS->getQualifier();
2889 T = QualType(NNS.getAsType(), 0);
2890 else
2891 T = QualType();
2892 continue;
2893 }
2894 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2895 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2896 T = Context.getTypeDeclType(Parent);
2897 else
2898 T = QualType();
2899 continue;
2900 }
2901 }
2902
2903 // Look one step prior in a dependent name type.
2904 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2905 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2907 T = QualType(NNS.getAsType(), 0);
2908 else
2909 T = QualType();
2910 continue;
2911 }
2912
2913 // Retrieve the parent of an enumeration type.
2914 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2915 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2916 // check here.
2917 EnumDecl *Enum = EnumT->getDecl();
2918
2919 // Get to the parent type.
2920 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2921 T = Context.getCanonicalTypeDeclType(Parent);
2922 else
2923 T = QualType();
2924 continue;
2925 }
2926
2927 T = QualType();
2928 }
2929 // Reverse the nested types list, since we want to traverse from the outermost
2930 // to the innermost while checking template-parameter-lists.
2931 std::reverse(NestedTypes.begin(), NestedTypes.end());
2932
2933 // C++0x [temp.expl.spec]p17:
2934 // A member or a member template may be nested within many
2935 // enclosing class templates. In an explicit specialization for
2936 // such a member, the member declaration shall be preceded by a
2937 // template<> for each enclosing class template that is
2938 // explicitly specialized.
2939 bool SawNonEmptyTemplateParameterList = false;
2940
2941 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2942 if (SawNonEmptyTemplateParameterList) {
2943 if (!SuppressDiagnostic)
2944 Diag(DeclLoc, diag::err_specialize_member_of_template)
2945 << !Recovery << Range;
2946 Invalid = true;
2947 IsMemberSpecialization = false;
2948 return true;
2949 }
2950
2951 return false;
2952 };
2953
2954 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2955 // Check that we can have an explicit specialization here.
2956 if (CheckExplicitSpecialization(Range, true))
2957 return true;
2958
2959 // We don't have a template header, but we should.
2960 SourceLocation ExpectedTemplateLoc;
2961 if (!ParamLists.empty())
2962 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2963 else
2964 ExpectedTemplateLoc = DeclStartLoc;
2965
2966 if (!SuppressDiagnostic)
2967 Diag(DeclLoc, diag::err_template_spec_needs_header)
2968 << Range
2969 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2970 return false;
2971 };
2972
2973 unsigned ParamIdx = 0;
2974 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2975 ++TypeIdx) {
2976 T = NestedTypes[TypeIdx];
2977
2978 // Whether we expect a 'template<>' header.
2979 bool NeedEmptyTemplateHeader = false;
2980
2981 // Whether we expect a template header with parameters.
2982 bool NeedNonemptyTemplateHeader = false;
2983
2984 // For a dependent type, the set of template parameters that we
2985 // expect to see.
2986 TemplateParameterList *ExpectedTemplateParams = nullptr;
2987
2988 // C++0x [temp.expl.spec]p15:
2989 // A member or a member template may be nested within many enclosing
2990 // class templates. In an explicit specialization for such a member, the
2991 // member declaration shall be preceded by a template<> for each
2992 // enclosing class template that is explicitly specialized.
2993 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2995 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2996 ExpectedTemplateParams = Partial->getTemplateParameters();
2997 NeedNonemptyTemplateHeader = true;
2998 } else if (Record->isDependentType()) {
2999 if (Record->getDescribedClassTemplate()) {
3000 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3001 ->getTemplateParameters();
3002 NeedNonemptyTemplateHeader = true;
3003 }
3004 } else if (ClassTemplateSpecializationDecl *Spec
3005 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3006 // C++0x [temp.expl.spec]p4:
3007 // Members of an explicitly specialized class template are defined
3008 // in the same manner as members of normal classes, and not using
3009 // the template<> syntax.
3010 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3011 NeedEmptyTemplateHeader = true;
3012 else
3013 continue;
3014 } else if (Record->getTemplateSpecializationKind()) {
3015 if (Record->getTemplateSpecializationKind()
3017 TypeIdx == NumTypes - 1)
3018 IsMemberSpecialization = true;
3019
3020 continue;
3021 }
3022 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3023 TemplateName Name = TST->getTemplateName();
3024 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3025 ExpectedTemplateParams = Template->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 } else if (Name.getAsDeducedTemplateName()) {
3028 // FIXME: We actually could/should check the template arguments here
3029 // against the corresponding template parameter list.
3030 NeedNonemptyTemplateHeader = false;
3031 }
3032 }
3033
3034 // C++ [temp.expl.spec]p16:
3035 // In an explicit specialization declaration for a member of a class
3036 // template or a member template that appears in namespace scope, the
3037 // member template and some of its enclosing class templates may remain
3038 // unspecialized, except that the declaration shall not explicitly
3039 // specialize a class member template if its enclosing class templates
3040 // are not explicitly specialized as well.
3041 if (ParamIdx < ParamLists.size()) {
3042 if (ParamLists[ParamIdx]->size() == 0) {
3043 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3044 false))
3045 return nullptr;
3046 } else
3047 SawNonEmptyTemplateParameterList = true;
3048 }
3049
3050 if (NeedEmptyTemplateHeader) {
3051 // If we're on the last of the types, and we need a 'template<>' header
3052 // here, then it's a member specialization.
3053 if (TypeIdx == NumTypes - 1)
3054 IsMemberSpecialization = true;
3055
3056 if (ParamIdx < ParamLists.size()) {
3057 if (ParamLists[ParamIdx]->size() > 0) {
3058 // The header has template parameters when it shouldn't. Complain.
3059 if (!SuppressDiagnostic)
3060 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3061 diag::err_template_param_list_matches_nontemplate)
3062 << T
3063 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3064 ParamLists[ParamIdx]->getRAngleLoc())
3066 Invalid = true;
3067 return nullptr;
3068 }
3069
3070 // Consume this template header.
3071 ++ParamIdx;
3072 continue;
3073 }
3074
3075 if (!IsFriend)
3076 if (DiagnoseMissingExplicitSpecialization(
3078 return nullptr;
3079
3080 continue;
3081 }
3082
3083 if (NeedNonemptyTemplateHeader) {
3084 // In friend declarations we can have template-ids which don't
3085 // depend on the corresponding template parameter lists. But
3086 // assume that empty parameter lists are supposed to match this
3087 // template-id.
3088 if (IsFriend && T->isDependentType()) {
3089 if (ParamIdx < ParamLists.size() &&
3090 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3091 ExpectedTemplateParams = nullptr;
3092 else
3093 continue;
3094 }
3095
3096 if (ParamIdx < ParamLists.size()) {
3097 // Check the template parameter list, if we can.
3098 if (ExpectedTemplateParams &&
3100 ExpectedTemplateParams,
3101 !SuppressDiagnostic, TPL_TemplateMatch))
3102 Invalid = true;
3103
3104 if (!Invalid &&
3105 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3107 Invalid = true;
3108
3109 ++ParamIdx;
3110 continue;
3111 }
3112
3113 if (!SuppressDiagnostic)
3114 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3115 << T
3117 Invalid = true;
3118 continue;
3119 }
3120 }
3121
3122 // If there were at least as many template-ids as there were template
3123 // parameter lists, then there are no template parameter lists remaining for
3124 // the declaration itself.
3125 if (ParamIdx >= ParamLists.size()) {
3126 if (TemplateId && !IsFriend) {
3127 // We don't have a template header for the declaration itself, but we
3128 // should.
3129 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3130 TemplateId->RAngleLoc));
3131
3132 // Fabricate an empty template parameter list for the invented header.
3134 SourceLocation(), {},
3135 SourceLocation(), nullptr);
3136 }
3137
3138 return nullptr;
3139 }
3140
3141 // If there were too many template parameter lists, complain about that now.
3142 if (ParamIdx < ParamLists.size() - 1) {
3143 bool HasAnyExplicitSpecHeader = false;
3144 bool AllExplicitSpecHeaders = true;
3145 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3146 if (ParamLists[I]->size() == 0)
3147 HasAnyExplicitSpecHeader = true;
3148 else
3149 AllExplicitSpecHeaders = false;
3150 }
3151
3152 if (!SuppressDiagnostic)
3153 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3154 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3155 : diag::err_template_spec_extra_headers)
3156 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3157 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3158
3159 // If there was a specialization somewhere, such that 'template<>' is
3160 // not required, and there were any 'template<>' headers, note where the
3161 // specialization occurred.
3162 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3163 !SuppressDiagnostic)
3164 Diag(ExplicitSpecLoc,
3165 diag::note_explicit_template_spec_does_not_need_header)
3166 << NestedTypes.back();
3167
3168 // We have a template parameter list with no corresponding scope, which
3169 // means that the resulting template declaration can't be instantiated
3170 // properly (we'll end up with dependent nodes when we shouldn't).
3171 if (!AllExplicitSpecHeaders)
3172 Invalid = true;
3173 }
3174
3175 // C++ [temp.expl.spec]p16:
3176 // In an explicit specialization declaration for a member of a class
3177 // template or a member template that ap- pears in namespace scope, the
3178 // member template and some of its enclosing class templates may remain
3179 // unspecialized, except that the declaration shall not explicitly
3180 // specialize a class member template if its en- closing class templates
3181 // are not explicitly specialized as well.
3182 if (ParamLists.back()->size() == 0 &&
3183 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3184 false))
3185 return nullptr;
3186
3187 // Return the last template parameter list, which corresponds to the
3188 // entity being declared.
3189 return ParamLists.back();
3190}
3191
3193 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3194 Diag(Template->getLocation(), diag::note_template_declared_here)
3196 ? 0
3198 ? 1
3200 ? 2
3202 << Template->getDeclName();
3203 return;
3204 }
3205
3207 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3208 IEnd = OST->end();
3209 I != IEnd; ++I)
3210 Diag((*I)->getLocation(), diag::note_template_declared_here)
3211 << 0 << (*I)->getDeclName();
3212
3213 return;
3214 }
3215}
3216
3218 TemplateName BaseTemplate,
3219 SourceLocation TemplateLoc,
3221 auto lookUpCommonType = [&](TemplateArgument T1,
3222 TemplateArgument T2) -> QualType {
3223 // Don't bother looking for other specializations if both types are
3224 // builtins - users aren't allowed to specialize for them
3225 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3226 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3227 {T1, T2});
3228
3232 Args.addArgument(TemplateArgumentLoc(
3233 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3234
3235 EnterExpressionEvaluationContext UnevaluatedContext(
3237 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3239
3240 QualType BaseTemplateInst = S.CheckTemplateIdType(
3241 Keyword, BaseTemplate, TemplateLoc, Args,
3242 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3243
3244 if (SFINAE.hasErrorOccurred())
3245 return QualType();
3246
3247 return BaseTemplateInst;
3248 };
3249
3250 // Note A: For the common_type trait applied to a template parameter pack T of
3251 // types, the member type shall be either defined or not present as follows:
3252 switch (Ts.size()) {
3253
3254 // If sizeof...(T) is zero, there shall be no member type.
3255 case 0:
3256 return QualType();
3257
3258 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3259 // pack T. The member typedef-name type shall denote the same type, if any, as
3260 // common_type_t<T0, T0>; otherwise there shall be no member type.
3261 case 1:
3262 return lookUpCommonType(Ts[0], Ts[0]);
3263
3264 // If sizeof...(T) is two, let the first and second types constituting T be
3265 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3266 // as decay_t<T1> and decay_t<T2>, respectively.
3267 case 2: {
3268 QualType T1 = Ts[0].getAsType();
3269 QualType T2 = Ts[1].getAsType();
3270 QualType D1 = S.BuiltinDecay(T1, {});
3271 QualType D2 = S.BuiltinDecay(T2, {});
3272
3273 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3274 // the same type, if any, as common_type_t<D1, D2>.
3275 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3276 return lookUpCommonType(D1, D2);
3277
3278 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3279 // denotes a valid type, let C denote that type.
3280 {
3281 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3282 EnterExpressionEvaluationContext UnevaluatedContext(
3284 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3286
3287 // false
3289 VK_PRValue);
3290 ExprResult Cond = &CondExpr;
3291
3292 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3293 if (ConstRefQual) {
3294 D1.addConst();
3295 D2.addConst();
3296 }
3297
3298 // declval<D1>()
3299 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3300 ExprResult LHS = &LHSExpr;
3301
3302 // declval<D2>()
3303 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3304 ExprResult RHS = &RHSExpr;
3305
3308
3309 // decltype(false ? declval<D1>() : declval<D2>())
3310 QualType Result =
3311 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3312
3313 if (Result.isNull() || SFINAE.hasErrorOccurred())
3314 return QualType();
3315
3316 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3317 return S.BuiltinDecay(Result, TemplateLoc);
3318 };
3319
3320 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3321 return Res;
3322
3323 // Let:
3324 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3325 // COND-RES(X, Y) be
3326 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3327
3328 // C++20 only
3329 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3330 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3331 if (!S.Context.getLangOpts().CPlusPlus20)
3332 return QualType();
3333 return CheckConditionalOperands(true);
3334 }
3335 }
3336
3337 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3338 // denote the first, second, and (pack of) remaining types constituting T. Let
3339 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3340 // a type C, the member typedef-name type shall denote the same type, if any,
3341 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3342 default: {
3343 QualType Result = Ts.front().getAsType();
3344 for (auto T : llvm::drop_begin(Ts)) {
3345 Result = lookUpCommonType(Result, T.getAsType());
3346 if (Result.isNull())
3347 return QualType();
3348 }
3349 return Result;
3350 }
3351 }
3352}
3353
3354static bool isInVkNamespace(const RecordType *RT) {
3355 DeclContext *DC = RT->getDecl()->getDeclContext();
3356 if (!DC)
3357 return false;
3358
3359 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3360 if (!ND)
3361 return false;
3362
3363 return ND->getQualifiedNameAsString() == "hlsl::vk";
3364}
3365
3366static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3367 QualType OperandArg,
3368 SourceLocation Loc) {
3369 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3370 bool Literal = false;
3371 SourceLocation LiteralLoc;
3372 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3373 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3374 assert(SpecDecl);
3375
3376 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3377 QualType ConstantType = LiteralArgs[0].getAsType();
3378 RT = ConstantType->getAsCanonical<RecordType>();
3379 Literal = true;
3380 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3381 }
3382
3383 if (RT && isInVkNamespace(RT) &&
3384 RT->getDecl()->getName() == "integral_constant") {
3385 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3386 assert(SpecDecl);
3387
3388 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3389
3390 QualType ConstantType = ConstantArgs[0].getAsType();
3391 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3392
3393 if (Literal)
3394 return SpirvOperand::createLiteral(Value);
3395 return SpirvOperand::createConstant(ConstantType, Value);
3396 } else if (Literal) {
3397 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3398 return SpirvOperand();
3399 }
3400 }
3401 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3402 diag::err_call_incomplete_argument))
3403 return SpirvOperand();
3404 return SpirvOperand::createType(OperandArg);
3405}
3406
3409 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3410 TemplateArgumentListInfo &TemplateArgs) {
3411 ASTContext &Context = SemaRef.getASTContext();
3412
3413 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3414 "Builtin template arguments do not match its parameters");
3415
3416 switch (BTD->getBuiltinTemplateKind()) {
3417 case BTK__make_integer_seq: {
3418 // Specializations of __make_integer_seq<S, T, N> are treated like
3419 // S<T, 0, ..., N-1>.
3420
3421 QualType OrigType = Converted[1].getAsType();
3422 // C++14 [inteseq.intseq]p1:
3423 // T shall be an integer type.
3424 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3425 SemaRef.Diag(TemplateArgs[1].getLocation(),
3426 diag::err_integer_sequence_integral_element_type);
3427 return QualType();
3428 }
3429
3430 TemplateArgument NumArgsArg = Converted[2];
3431 if (NumArgsArg.isDependent())
3432 return QualType();
3433
3434 TemplateArgumentListInfo SyntheticTemplateArgs;
3435 // The type argument, wrapped in substitution sugar, gets reused as the
3436 // first template argument in the synthetic template argument list.
3437 SyntheticTemplateArgs.addArgument(
3440 OrigType, TemplateArgs[1].getLocation())));
3441
3442 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3443 // Expand N into 0 ... N-1.
3444 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3445 I < NumArgs; ++I) {
3446 TemplateArgument TA(Context, I, OrigType);
3447 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3448 TA, OrigType, TemplateArgs[2].getLocation()));
3449 }
3450 } else {
3451 // C++14 [inteseq.make]p1:
3452 // If N is negative the program is ill-formed.
3453 SemaRef.Diag(TemplateArgs[2].getLocation(),
3454 diag::err_integer_sequence_negative_length);
3455 return QualType();
3456 }
3457
3458 // The first template argument will be reused as the template decl that
3459 // our synthetic template arguments will be applied to.
3460 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3461 TemplateLoc, SyntheticTemplateArgs,
3462 /*Scope=*/nullptr,
3463 /*ForNestedNameSpecifier=*/false);
3464 }
3465
3466 case BTK__type_pack_element: {
3467 // Specializations of
3468 // __type_pack_element<Index, T_1, ..., T_N>
3469 // are treated like T_Index.
3470 assert(Converted.size() == 2 &&
3471 "__type_pack_element should be given an index and a parameter pack");
3472
3473 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3474 if (IndexArg.isDependent() || Ts.isDependent())
3475 return QualType();
3476
3477 llvm::APSInt Index = IndexArg.getAsIntegral();
3478 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3479 "type std::size_t, and hence be non-negative");
3480 // If the Index is out of bounds, the program is ill-formed.
3481 if (Index >= Ts.pack_size()) {
3482 SemaRef.Diag(TemplateArgs[0].getLocation(),
3483 diag::err_type_pack_element_out_of_bounds);
3484 return QualType();
3485 }
3486
3487 // We simply return the type at index `Index`.
3488 int64_t N = Index.getExtValue();
3489 return Ts.getPackAsArray()[N].getAsType();
3490 }
3491
3492 case BTK__builtin_common_type: {
3493 assert(Converted.size() == 4);
3494 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3495 return QualType();
3496
3497 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3498 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3499 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3500 TemplateLoc, Ts);
3501 !CT.isNull()) {
3505 CT, TemplateArgs[1].getLocation())));
3506 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3507 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3508 TAs, /*Scope=*/nullptr,
3509 /*ForNestedNameSpecifier=*/false);
3510 }
3511 QualType HasNoTypeMember = Converted[2].getAsType();
3512 return HasNoTypeMember;
3513 }
3514
3515 case BTK__hlsl_spirv_type: {
3516 assert(Converted.size() == 4);
3517
3518 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3519 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3520 }
3521
3522 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3523 return QualType();
3524
3525 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3526 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3527 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3528
3529 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3530
3532
3533 for (auto &OperandTA : OperandArgs) {
3534 QualType OperandArg = OperandTA.getAsType();
3535 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3536 TemplateArgs[3].getLocation());
3537 if (!Operand.isValid())
3538 return QualType();
3539 Operands.push_back(Operand);
3540 }
3541
3542 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3543 }
3544 case BTK__builtin_dedup_pack: {
3545 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3546 "a parameter pack");
3547 TemplateArgument Ts = Converted[0];
3548 // Delay the computation until we can compute the final result. We choose
3549 // not to remove the duplicates upfront before substitution to keep the code
3550 // simple.
3551 if (Ts.isDependent())
3552 return QualType();
3553 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3555 llvm::SmallDenseSet<QualType> Seen;
3556 // Synthesize a new template argument list, removing duplicates.
3557 for (auto T : Ts.getPackAsArray()) {
3558 assert(T.getKind() == clang::TemplateArgument::Type);
3559 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3560 continue;
3561 OutArgs.push_back(T);
3562 }
3563 return Context.getSubstBuiltinTemplatePack(
3564 TemplateArgument::CreatePackCopy(Context, OutArgs));
3565 }
3566 }
3567 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3568}
3569
3570/// Determine whether this alias template is "enable_if_t".
3571/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3573 return AliasTemplate->getName() == "enable_if_t" ||
3574 AliasTemplate->getName() == "__enable_if_t";
3575}
3576
3577/// Collect all of the separable terms in the given condition, which
3578/// might be a conjunction.
3579///
3580/// FIXME: The right answer is to convert the logical expression into
3581/// disjunctive normal form, so we can find the first failed term
3582/// within each possible clause.
3583static void collectConjunctionTerms(Expr *Clause,
3584 SmallVectorImpl<Expr *> &Terms) {
3585 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3586 if (BinOp->getOpcode() == BO_LAnd) {
3587 collectConjunctionTerms(BinOp->getLHS(), Terms);
3588 collectConjunctionTerms(BinOp->getRHS(), Terms);
3589 return;
3590 }
3591 }
3592
3593 Terms.push_back(Clause);
3594}
3595
3596// The ranges-v3 library uses an odd pattern of a top-level "||" with
3597// a left-hand side that is value-dependent but never true. Identify
3598// the idiom and ignore that term.
3600 // Top-level '||'.
3601 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3602 if (!BinOp) return Cond;
3603
3604 if (BinOp->getOpcode() != BO_LOr) return Cond;
3605
3606 // With an inner '==' that has a literal on the right-hand side.
3607 Expr *LHS = BinOp->getLHS();
3608 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3609 if (!InnerBinOp) return Cond;
3610
3611 if (InnerBinOp->getOpcode() != BO_EQ ||
3612 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3613 return Cond;
3614
3615 // If the inner binary operation came from a macro expansion named
3616 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3617 // of the '||', which is the real, user-provided condition.
3618 SourceLocation Loc = InnerBinOp->getExprLoc();
3619 if (!Loc.isMacroID()) return Cond;
3620
3621 StringRef MacroName = PP.getImmediateMacroName(Loc);
3622 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3623 return BinOp->getRHS();
3624
3625 return Cond;
3626}
3627
3628namespace {
3629
3630// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3631// within failing boolean expression, such as substituting template parameters
3632// for actual types.
3633class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3634public:
3635 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3636 : Policy(P) {}
3637
3638 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3639 const auto *DR = dyn_cast<DeclRefExpr>(E);
3640 if (DR && DR->getQualifier()) {
3641 // If this is a qualified name, expand the template arguments in nested
3642 // qualifiers.
3643 DR->getQualifier().print(OS, Policy, true);
3644 // Then print the decl itself.
3645 const ValueDecl *VD = DR->getDecl();
3646 OS << VD->getName();
3647 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3648 // This is a template variable, print the expanded template arguments.
3649 printTemplateArgumentList(
3650 OS, IV->getTemplateArgs().asArray(), Policy,
3651 IV->getSpecializedTemplate()->getTemplateParameters());
3652 }
3653 return true;
3654 }
3655 return false;
3656 }
3657
3658private:
3659 const PrintingPolicy Policy;
3660};
3661
3662} // end anonymous namespace
3663
3664std::pair<Expr *, std::string>
3667
3668 // Separate out all of the terms in a conjunction.
3671
3672 // Determine which term failed.
3673 Expr *FailedCond = nullptr;
3674 for (Expr *Term : Terms) {
3675 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3676
3677 // Literals are uninteresting.
3678 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3679 isa<IntegerLiteral>(TermAsWritten))
3680 continue;
3681
3682 // The initialization of the parameter from the argument is
3683 // a constant-evaluated context.
3686
3687 bool Succeeded;
3688 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3689 !Succeeded) {
3690 FailedCond = TermAsWritten;
3691 break;
3692 }
3693 }
3694 if (!FailedCond)
3695 FailedCond = Cond->IgnoreParenImpCasts();
3696
3697 std::string Description;
3698 {
3699 llvm::raw_string_ostream Out(Description);
3701 Policy.PrintAsCanonical = true;
3702 FailedBooleanConditionPrinterHelper Helper(Policy);
3703 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3704 }
3705 return { FailedCond, Description };
3706}
3707
3708static TemplateName
3710 const AssumedTemplateStorage *ATN,
3711 SourceLocation NameLoc) {
3712 // We assumed this undeclared identifier to be an (ADL-only) function
3713 // template name, but it was used in a context where a type was required.
3714 // Try to typo-correct it now.
3715 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3716 struct CandidateCallback : CorrectionCandidateCallback {
3717 bool ValidateCandidate(const TypoCorrection &TC) override {
3718 return TC.getCorrectionDecl() &&
3720 }
3721 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3722 return std::make_unique<CandidateCallback>(*this);
3723 }
3724 } FilterCCC;
3725
3726 TypoCorrection Corrected =
3727 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3728 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3729 if (Corrected && Corrected.getFoundDecl()) {
3730 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3731 << ATN->getDeclName());
3733 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3735 }
3736
3737 return TemplateName();
3738}
3739
3741 TemplateName Name,
3742 SourceLocation TemplateLoc,
3743 TemplateArgumentListInfo &TemplateArgs,
3744 Scope *Scope, bool ForNestedNameSpecifier) {
3745 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3746
3747 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3748 if (!Template) {
3749 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3750 Template = S->getParameterPack();
3751 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3752 if (DTN->getName().getIdentifier())
3753 // When building a template-id where the template-name is dependent,
3754 // assume the template is a type template. Either our assumption is
3755 // correct, or the code is ill-formed and will be diagnosed when the
3756 // dependent name is substituted.
3757 return Context.getTemplateSpecializationType(Keyword, Name,
3758 TemplateArgs.arguments(),
3759 /*CanonicalArgs=*/{});
3760 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3762 *this, Scope, ATN, TemplateLoc);
3763 CorrectedName.isNull()) {
3764 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3765 return QualType();
3766 } else {
3767 Name = CorrectedName;
3768 Template = Name.getAsTemplateDecl();
3769 }
3770 }
3771 }
3772 if (!Template ||
3774 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3775 if (ForNestedNameSpecifier)
3776 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3777 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3778 else
3779 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3781 return QualType();
3782 }
3783
3784 // Check that the template argument list is well-formed for this
3785 // template.
3787 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3788 DefaultArgs, /*PartialTemplateArgs=*/false,
3789 CTAI,
3790 /*UpdateArgsWithConversions=*/true))
3791 return QualType();
3792
3793 QualType CanonType;
3794
3796 // We might have a substituted template template parameter pack. If so,
3797 // build a template specialization type for it.
3799 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3800
3801 // C++0x [dcl.type.elab]p2:
3802 // If the identifier resolves to a typedef-name or the simple-template-id
3803 // resolves to an alias template specialization, the
3804 // elaborated-type-specifier is ill-formed.
3807 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3810 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3811 }
3812
3813 // Find the canonical type for this type alias template specialization.
3814 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3815 if (Pattern->isInvalidDecl())
3816 return QualType();
3817
3818 // Only substitute for the innermost template argument list.
3819 MultiLevelTemplateArgumentList TemplateArgLists;
3821 /*Final=*/true);
3822 TemplateArgLists.addOuterRetainedLevels(
3823 AliasTemplate->getTemplateParameters()->getDepth());
3824
3826
3827 // Diagnose uses of this alias.
3828 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3829
3830 // FIXME: The TemplateArgs passed here are not used for the context note,
3831 // nor they should, because this note will be pointing to the specialization
3832 // anyway. These arguments are needed for a hack for instantiating lambdas
3833 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3834 // arguments will be used for collating the template arguments needed to
3835 // instantiate the lambda.
3836 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3837 /*Entity=*/AliasTemplate,
3838 /*TemplateArgs=*/CTAI.SugaredConverted);
3839 if (Inst.isInvalid())
3840 return QualType();
3841
3842 std::optional<ContextRAII> SavedContext;
3843 if (!AliasTemplate->getDeclContext()->isFileContext())
3844 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3845
3846 CanonType =
3847 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3848 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3849 if (CanonType.isNull()) {
3850 // If this was enable_if and we failed to find the nested type
3851 // within enable_if in a SFINAE context, dig out the specific
3852 // enable_if condition that failed and present that instead.
3854 if (SFINAETrap *Trap = getSFINAEContext();
3855 TemplateDeductionInfo *DeductionInfo =
3856 Trap ? Trap->getDeductionInfo() : nullptr) {
3857 if (DeductionInfo->hasSFINAEDiagnostic() &&
3858 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3859 diag::err_typename_nested_not_found_enable_if &&
3860 TemplateArgs[0].getArgument().getKind() ==
3862 Expr *FailedCond;
3863 std::string FailedDescription;
3864 std::tie(FailedCond, FailedDescription) =
3865 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3866
3867 // Remove the old SFINAE diagnostic.
3868 PartialDiagnosticAt OldDiag =
3870 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3871
3872 // Add a new SFINAE diagnostic specifying which condition
3873 // failed.
3874 DeductionInfo->addSFINAEDiagnostic(
3875 OldDiag.first,
3876 PDiag(diag::err_typename_nested_not_found_requirement)
3877 << FailedDescription << FailedCond->getSourceRange());
3878 }
3879 }
3880 }
3881
3882 return QualType();
3883 }
3884 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3885 CanonType = checkBuiltinTemplateIdType(
3886 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3887 } else if (Name.isDependent() ||
3888 TemplateSpecializationType::anyDependentTemplateArguments(
3889 TemplateArgs, CTAI.CanonicalConverted)) {
3890 // This class template specialization is a dependent
3891 // type. Therefore, its canonical type is another class template
3892 // specialization type that contains all of the converted
3893 // arguments in canonical form. This ensures that, e.g., A<T> and
3894 // A<T, T> have identical types when A is declared as:
3895 //
3896 // template<typename T, typename U = T> struct A;
3897 CanonType = Context.getCanonicalTemplateSpecializationType(
3899 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3900 CTAI.CanonicalConverted);
3901 assert(CanonType->isCanonicalUnqualified());
3902
3903 // This might work out to be a current instantiation, in which
3904 // case the canonical type needs to be the InjectedClassNameType.
3905 //
3906 // TODO: in theory this could be a simple hashtable lookup; most
3907 // changes to CurContext don't change the set of current
3908 // instantiations.
3910 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3911 // If we get out to a namespace, we're done.
3912 if (Ctx->isFileContext()) break;
3913
3914 // If this isn't a record, keep looking.
3915 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3916 if (!Record) continue;
3917
3918 // Look for one of the two cases with InjectedClassNameTypes
3919 // and check whether it's the same template.
3921 !Record->getDescribedClassTemplate())
3922 continue;
3923
3924 // Fetch the injected class name type and check whether its
3925 // injected type is equal to the type we just built.
3926 CanQualType ICNT = Context.getCanonicalTagType(Record);
3927 CanQualType Injected =
3928 Record->getCanonicalTemplateSpecializationType(Context);
3929
3930 if (CanonType != Injected)
3931 continue;
3932
3933 // If so, the canonical type of this TST is the injected
3934 // class name type of the record we just found.
3935 CanonType = ICNT;
3936 break;
3937 }
3938 }
3939 } else if (ClassTemplateDecl *ClassTemplate =
3940 dyn_cast<ClassTemplateDecl>(Template)) {
3941 // Find the class template specialization declaration that
3942 // corresponds to these arguments.
3943 void *InsertPos = nullptr;
3945 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3946 if (!Decl) {
3947 // This is the first time we have referenced this class template
3948 // specialization. Create the canonical declaration and add it to
3949 // the set of specializations.
3951 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3952 ClassTemplate->getDeclContext(),
3953 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3954 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3955 CTAI.StrictPackMatch, nullptr);
3956 ClassTemplate->AddSpecialization(Decl, InsertPos);
3957 if (ClassTemplate->isOutOfLine())
3958 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3959 }
3960
3961 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3962 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3963 NonSFINAEContext _(*this);
3964 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3965 if (!Inst.isInvalid()) {
3967 CTAI.CanonicalConverted,
3968 /*Final=*/false);
3969 InstantiateAttrsForDecl(TemplateArgLists,
3970 ClassTemplate->getTemplatedDecl(), Decl);
3971 }
3972 }
3973
3974 // Diagnose uses of this specialization.
3975 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3976
3977 CanonType = Context.getCanonicalTagType(Decl);
3978 assert(isa<RecordType>(CanonType) &&
3979 "type of non-dependent specialization is not a RecordType");
3980 } else {
3981 llvm_unreachable("Unhandled template kind");
3982 }
3983
3984 // Build the fully-sugared type for this class template
3985 // specialization, which refers back to the class template
3986 // specialization we created or found.
3987 return Context.getTemplateSpecializationType(
3988 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
3989 CanonType);
3990}
3991
3993 TemplateNameKind &TNK,
3994 SourceLocation NameLoc,
3995 IdentifierInfo *&II) {
3996 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3997
3998 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
3999 assert(ATN && "not an assumed template name");
4000 II = ATN->getDeclName().getAsIdentifierInfo();
4001
4002 if (TemplateName Name =
4003 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4004 !Name.isNull()) {
4005 // Resolved to a type template name.
4006 ParsedName = TemplateTy::make(Name);
4007 TNK = TNK_Type_template;
4008 }
4009}
4010
4012 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4013 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4014 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4015 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4016 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4017 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4018 ImplicitTypenameContext AllowImplicitTypename) {
4019 if (SS.isInvalid())
4020 return true;
4021
4022 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4023 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4024
4025 // C++ [temp.res]p3:
4026 // A qualified-id that refers to a type and in which the
4027 // nested-name-specifier depends on a template-parameter (14.6.2)
4028 // shall be prefixed by the keyword typename to indicate that the
4029 // qualified-id denotes a type, forming an
4030 // elaborated-type-specifier (7.1.5.3).
4031 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4032 // C++2a relaxes some of those restrictions in [temp.res]p5.
4033 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4034 SS.getScopeRep(), TemplateII);
4036 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4037 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4038 << NNS;
4039 if (!getLangOpts().CPlusPlus20)
4040 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4041 } else
4042 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4043
4044 // FIXME: This is not quite correct recovery as we don't transform SS
4045 // into the corresponding dependent form (and we don't diagnose missing
4046 // 'template' keywords within SS as a result).
4047 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4048 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4049 TemplateArgsIn, RAngleLoc);
4050 }
4051
4052 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4053 // it's not actually allowed to be used as a type in most cases. Because
4054 // we annotate it before we know whether it's valid, we have to check for
4055 // this case here.
4056 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4057 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4058 Diag(TemplateIILoc,
4059 TemplateKWLoc.isInvalid()
4060 ? diag::err_out_of_line_qualified_id_type_names_constructor
4061 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4062 << TemplateII << 0 /*injected-class-name used as template name*/
4063 << 1 /*if any keyword was present, it was 'template'*/;
4064 }
4065 }
4066
4067 // Translate the parser's template argument list in our AST format.
4068 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4069 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4070
4072 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4073 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4074 if (SpecTy.isNull())
4075 return true;
4076
4077 // Build type-source information.
4078 TypeLocBuilder TLB;
4079 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4080 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4081 TemplateIILoc, TemplateArgs);
4082 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4083}
4084
4086 TypeSpecifierType TagSpec,
4087 SourceLocation TagLoc,
4088 CXXScopeSpec &SS,
4089 SourceLocation TemplateKWLoc,
4090 TemplateTy TemplateD,
4091 SourceLocation TemplateLoc,
4092 SourceLocation LAngleLoc,
4093 ASTTemplateArgsPtr TemplateArgsIn,
4094 SourceLocation RAngleLoc) {
4095 if (SS.isInvalid())
4096 return TypeResult(true);
4097
4098 // Translate the parser's template argument list in our AST format.
4099 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4100 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4101
4102 // Determine the tag kind
4106
4108 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4109 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4110 if (Result.isNull())
4111 return TypeResult(true);
4112
4113 // Check the tag kind
4114 if (const RecordType *RT = Result->getAs<RecordType>()) {
4115 RecordDecl *D = RT->getDecl();
4116
4117 IdentifierInfo *Id = D->getIdentifier();
4118 assert(Id && "templated class must have an identifier");
4119
4121 TagLoc, Id)) {
4122 Diag(TagLoc, diag::err_use_with_wrong_tag)
4123 << Result
4125 Diag(D->getLocation(), diag::note_previous_use);
4126 }
4127 }
4128
4129 // Provide source-location information for the template specialization.
4130 TypeLocBuilder TLB;
4132 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4133 TemplateArgs);
4135}
4136
4137static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4138 NamedDecl *PrevDecl,
4139 SourceLocation Loc,
4141
4143
4145 unsigned Depth,
4146 unsigned Index) {
4147 switch (Arg.getKind()) {
4155 return false;
4156
4158 QualType Type = Arg.getAsType();
4159 const TemplateTypeParmType *TPT =
4160 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4161 return TPT && !Type.hasQualifiers() &&
4162 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4163 }
4164
4166 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4167 if (!DRE || !DRE->getDecl())
4168 return false;
4169 const NonTypeTemplateParmDecl *NTTP =
4170 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4171 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4172 }
4173
4175 const TemplateTemplateParmDecl *TTP =
4176 dyn_cast_or_null<TemplateTemplateParmDecl>(
4178 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4179 }
4180 llvm_unreachable("unexpected kind of template argument");
4181}
4182
4184 TemplateParameterList *SpecParams,
4186 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4187 return false;
4188
4189 unsigned Depth = Params->getDepth();
4190
4191 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4192 TemplateArgument Arg = Args[I];
4193
4194 // If the parameter is a pack expansion, the argument must be a pack
4195 // whose only element is a pack expansion.
4196 if (Params->getParam(I)->isParameterPack()) {
4197 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4198 !Arg.pack_begin()->isPackExpansion())
4199 return false;
4200 Arg = Arg.pack_begin()->getPackExpansionPattern();
4201 }
4202
4203 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4204 return false;
4205
4206 // For NTTPs further specialization is allowed via deduced types, so
4207 // we need to make sure to only reject here if primary template and
4208 // specialization use the same type for the NTTP.
4209 if (auto *SpecNTTP =
4210 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4211 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4212 if (!NTTP || NTTP->getType().getCanonicalType() !=
4213 SpecNTTP->getType().getCanonicalType())
4214 return false;
4215 }
4216 }
4217
4218 return true;
4219}
4220
4221template<typename PartialSpecDecl>
4222static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4223 if (Partial->getDeclContext()->isDependentContext())
4224 return;
4225
4226 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4227 // for non-substitution-failure issues?
4228 TemplateDeductionInfo Info(Partial->getLocation());
4229 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4230 return;
4231
4232 auto *Template = Partial->getSpecializedTemplate();
4233 S.Diag(Partial->getLocation(),
4234 diag::ext_partial_spec_not_more_specialized_than_primary)
4236
4237 if (Info.hasSFINAEDiagnostic()) {
4241 SmallString<128> SFINAEArgString;
4242 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4243 S.Diag(Diag.first,
4244 diag::note_partial_spec_not_more_specialized_than_primary)
4245 << SFINAEArgString;
4246 }
4247
4249 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4250 Template->getAssociatedConstraints(TemplateAC);
4251 Partial->getAssociatedConstraints(PartialAC);
4253 TemplateAC);
4254}
4255
4256static void
4258 const llvm::SmallBitVector &DeducibleParams) {
4259 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4260 if (!DeducibleParams[I]) {
4261 NamedDecl *Param = TemplateParams->getParam(I);
4262 if (Param->getDeclName())
4263 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4264 << Param->getDeclName();
4265 else
4266 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4267 << "(anonymous)";
4268 }
4269 }
4270}
4271
4272
4273template<typename PartialSpecDecl>
4275 PartialSpecDecl *Partial) {
4276 // C++1z [temp.class.spec]p8: (DR1495)
4277 // - The specialization shall be more specialized than the primary
4278 // template (14.5.5.2).
4280
4281 // C++ [temp.class.spec]p8: (DR1315)
4282 // - Each template-parameter shall appear at least once in the
4283 // template-id outside a non-deduced context.
4284 // C++1z [temp.class.spec.match]p3 (P0127R2)
4285 // If the template arguments of a partial specialization cannot be
4286 // deduced because of the structure of its template-parameter-list
4287 // and the template-id, the program is ill-formed.
4288 auto *TemplateParams = Partial->getTemplateParameters();
4289 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4290 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4291 TemplateParams->getDepth(), DeducibleParams);
4292
4293 if (!DeducibleParams.all()) {
4294 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4295 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4297 << (NumNonDeducible > 1)
4298 << SourceRange(Partial->getLocation(),
4299 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4300 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4301 }
4302}
4303
4308
4313
4315 // C++1z [temp.param]p11:
4316 // A template parameter of a deduction guide template that does not have a
4317 // default-argument shall be deducible from the parameter-type-list of the
4318 // deduction guide template.
4319 auto *TemplateParams = TD->getTemplateParameters();
4320 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4321 MarkDeducedTemplateParameters(TD, DeducibleParams);
4322 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4323 // A parameter pack is deducible (to an empty pack).
4324 auto *Param = TemplateParams->getParam(I);
4325 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4326 DeducibleParams[I] = true;
4327 }
4328
4329 if (!DeducibleParams.all()) {
4330 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4331 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4332 << (NumNonDeducible > 1);
4333 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4334 }
4335}
4336
4339 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4341 // D must be variable template id.
4343 "Variable template specialization is declared with a template id.");
4344
4345 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4346 TemplateArgumentListInfo TemplateArgs =
4347 makeTemplateArgumentListInfo(*this, *TemplateId);
4348 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4349 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4350 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4351
4352 TemplateName Name = TemplateId->Template.get();
4353
4354 // The template-id must name a variable template.
4356 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4357 if (!VarTemplate) {
4358 NamedDecl *FnTemplate;
4359 if (auto *OTS = Name.getAsOverloadedTemplate())
4360 FnTemplate = *OTS->begin();
4361 else
4362 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4363 if (FnTemplate)
4364 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4365 << FnTemplate->getDeclName();
4366 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4368 }
4369
4370 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4371 auto Message = DSA->getMessage();
4372 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4373 << VarTemplate << !Message.empty() << Message;
4374 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4375 }
4376
4377 // Check for unexpanded parameter packs in any of the template arguments.
4378 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4379 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4383 return true;
4384
4385 // Check that the template argument list is well-formed for this
4386 // template.
4388 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4389 /*DefaultArgs=*/{},
4390 /*PartialTemplateArgs=*/false, CTAI,
4391 /*UpdateArgsWithConversions=*/true))
4392 return true;
4393
4394 // Find the variable template (partial) specialization declaration that
4395 // corresponds to these arguments.
4398 TemplateArgs.size(),
4399 CTAI.CanonicalConverted))
4400 return true;
4401
4402 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4403 // we also do them during instantiation.
4404 if (!Name.isDependent() &&
4405 !TemplateSpecializationType::anyDependentTemplateArguments(
4406 TemplateArgs, CTAI.CanonicalConverted)) {
4407 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4408 << VarTemplate->getDeclName();
4410 }
4411
4412 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4413 TemplateParams, CTAI.CanonicalConverted) &&
4414 (!Context.getLangOpts().CPlusPlus20 ||
4415 !TemplateParams->hasAssociatedConstraints())) {
4416 // C++ [temp.class.spec]p9b3:
4417 //
4418 // -- The argument list of the specialization shall not be identical
4419 // to the implicit argument list of the primary template.
4420 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4421 << /*variable template*/ 1
4422 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4423 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4424 // FIXME: Recover from this by treating the declaration as a
4425 // redeclaration of the primary template.
4426 return true;
4427 }
4428 }
4429
4430 void *InsertPos = nullptr;
4431 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4432
4434 PrevDecl = VarTemplate->findPartialSpecialization(
4435 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4436 else
4437 PrevDecl =
4438 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4439
4441
4442 // Check whether we can declare a variable template specialization in
4443 // the current scope.
4444 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4445 TemplateNameLoc,
4447 return true;
4448
4449 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4450 // Since the only prior variable template specialization with these
4451 // arguments was referenced but not declared, reuse that
4452 // declaration node as our own, updating its source location and
4453 // the list of outer template parameters to reflect our new declaration.
4454 Specialization = PrevDecl;
4455 Specialization->setLocation(TemplateNameLoc);
4456 PrevDecl = nullptr;
4457 } else if (IsPartialSpecialization) {
4458 // Create a new class template partial specialization declaration node.
4460 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4463 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4464 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4465 SC, CTAI.CanonicalConverted);
4466 Partial->setTemplateArgsAsWritten(TemplateArgs);
4467
4468 if (!PrevPartial)
4469 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4470 Specialization = Partial;
4471
4472 // If we are providing an explicit specialization of a member variable
4473 // template specialization, make a note of that.
4474 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4475 PrevPartial->setMemberSpecialization();
4476
4478 } else {
4479 // Create a new class template specialization declaration node for
4480 // this explicit specialization or friend declaration.
4482 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4483 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4484 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4485
4486 if (!PrevDecl)
4487 VarTemplate->AddSpecialization(Specialization, InsertPos);
4488 }
4489
4490 // C++ [temp.expl.spec]p6:
4491 // If a template, a member template or the member of a class template is
4492 // explicitly specialized then that specialization shall be declared
4493 // before the first use of that specialization that would cause an implicit
4494 // instantiation to take place, in every translation unit in which such a
4495 // use occurs; no diagnostic is required.
4496 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4497 bool Okay = false;
4498 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4499 // Is there any previous explicit specialization declaration?
4501 Okay = true;
4502 break;
4503 }
4504 }
4505
4506 if (!Okay) {
4507 SourceRange Range(TemplateNameLoc, RAngleLoc);
4508 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4509 << Name << Range;
4510
4511 Diag(PrevDecl->getPointOfInstantiation(),
4512 diag::note_instantiation_required_here)
4513 << (PrevDecl->getTemplateSpecializationKind() !=
4515 return true;
4516 }
4517 }
4518
4519 Specialization->setLexicalDeclContext(CurContext);
4520
4521 // Add the specialization into its lexical context, so that it can
4522 // be seen when iterating through the list of declarations in that
4523 // context. However, specializations are not found by name lookup.
4524 CurContext->addDecl(Specialization);
4525
4526 // Note that this is an explicit specialization.
4527 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4528
4529 Previous.clear();
4530 if (PrevDecl)
4531 Previous.addDecl(PrevDecl);
4532 else if (Specialization->isStaticDataMember() &&
4533 Specialization->isOutOfLine())
4534 Specialization->setAccess(VarTemplate->getAccess());
4535
4536 return Specialization;
4537}
4538
4539namespace {
4540/// A partial specialization whose template arguments have matched
4541/// a given template-id.
4542struct PartialSpecMatchResult {
4545};
4546
4547// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4548// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4549static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4550 if (Var->getName() != "format_kind" ||
4551 !Var->getDeclContext()->isStdNamespace())
4552 return false;
4553
4554 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4555 // release in which users can access std::format_kind.
4556 // We can use 20250520 as the final date, see the following commits.
4557 // GCC releases/gcc-15 branch:
4558 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4559 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4560 // GCC master branch:
4561 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4562 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4563 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4564}
4565} // end anonymous namespace
4566
4569 SourceLocation TemplateNameLoc,
4570 const TemplateArgumentListInfo &TemplateArgs,
4571 bool SetWrittenArgs) {
4572 assert(Template && "A variable template id without template?");
4573
4574 // Check that the template argument list is well-formed for this template.
4577 Template, TemplateNameLoc,
4578 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4579 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4580 /*UpdateArgsWithConversions=*/true))
4581 return true;
4582
4583 // Produce a placeholder value if the specialization is dependent.
4584 if (Template->getDeclContext()->isDependentContext() ||
4585 TemplateSpecializationType::anyDependentTemplateArguments(
4586 TemplateArgs, CTAI.CanonicalConverted)) {
4587 if (ParsingInitForAutoVars.empty())
4588 return DeclResult();
4589
4590 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4591 const TemplateArgument &Arg2) {
4592 return Context.isSameTemplateArgument(Arg1, Arg2);
4593 };
4594
4595 if (VarDecl *Var = Template->getTemplatedDecl();
4596 ParsingInitForAutoVars.count(Var) &&
4597 // See comments on this function definition
4598 !IsLibstdcxxStdFormatKind(PP, Var) &&
4599 llvm::equal(
4600 CTAI.CanonicalConverted,
4601 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4602 IsSameTemplateArg)) {
4603 Diag(TemplateNameLoc,
4604 diag::err_auto_variable_cannot_appear_in_own_initializer)
4605 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4606 return true;
4607 }
4608
4610 Template->getPartialSpecializations(PartialSpecs);
4611 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4612 if (ParsingInitForAutoVars.count(Partial) &&
4613 llvm::equal(CTAI.CanonicalConverted,
4614 Partial->getTemplateArgs().asArray(),
4615 IsSameTemplateArg)) {
4616 Diag(TemplateNameLoc,
4617 diag::err_auto_variable_cannot_appear_in_own_initializer)
4618 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4619 << Partial->getType();
4620 return true;
4621 }
4622
4623 return DeclResult();
4624 }
4625
4626 // Find the variable template specialization declaration that
4627 // corresponds to these arguments.
4628 void *InsertPos = nullptr;
4630 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4631 checkSpecializationReachability(TemplateNameLoc, Spec);
4632 if (Spec->getType()->isUndeducedType()) {
4633 if (ParsingInitForAutoVars.count(Spec))
4634 Diag(TemplateNameLoc,
4635 diag::err_auto_variable_cannot_appear_in_own_initializer)
4636 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4637 << Spec->getType();
4638 else
4639 // We are substituting the initializer of this variable template
4640 // specialization.
4641 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4642 << Spec << Spec->getType();
4643
4644 return true;
4645 }
4646 // If we already have a variable template specialization, return it.
4647 return Spec;
4648 }
4649
4650 // This is the first time we have referenced this variable template
4651 // specialization. Create the canonical declaration and add it to
4652 // the set of specializations, based on the closest partial specialization
4653 // that it represents. That is,
4654 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4655 const TemplateArgumentList *PartialSpecArgs = nullptr;
4656 bool AmbiguousPartialSpec = false;
4657 typedef PartialSpecMatchResult MatchResult;
4659 SourceLocation PointOfInstantiation = TemplateNameLoc;
4660 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4661 /*ForTakingAddress=*/false);
4662
4663 // 1. Attempt to find the closest partial specialization that this
4664 // specializes, if any.
4665 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4666 // Perhaps better after unification of DeduceTemplateArguments() and
4667 // getMoreSpecializedPartialSpecialization().
4669 Template->getPartialSpecializations(PartialSpecs);
4670
4671 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4672 // C++ [temp.spec.partial.member]p2:
4673 // If the primary member template is explicitly specialized for a given
4674 // (implicit) specialization of the enclosing class template, the partial
4675 // specializations of the member template are ignored for this
4676 // specialization of the enclosing class template. If a partial
4677 // specialization of the member template is explicitly specialized for a
4678 // given (implicit) specialization of the enclosing class template, the
4679 // primary member template and its other partial specializations are still
4680 // considered for this specialization of the enclosing class template.
4681 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4682 !Partial->getMostRecentDecl()->isMemberSpecialization())
4683 continue;
4684
4685 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4686
4688 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4690 // Store the failed-deduction information for use in diagnostics, later.
4691 // TODO: Actually use the failed-deduction info?
4692 FailedCandidates.addCandidate().set(
4695 (void)Result;
4696 } else {
4697 Matched.push_back(PartialSpecMatchResult());
4698 Matched.back().Partial = Partial;
4699 Matched.back().Args = Info.takeSugared();
4700 }
4701 }
4702
4703 if (Matched.size() >= 1) {
4704 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4705 if (Matched.size() == 1) {
4706 // -- If exactly one matching specialization is found, the
4707 // instantiation is generated from that specialization.
4708 // We don't need to do anything for this.
4709 } else {
4710 // -- If more than one matching specialization is found, the
4711 // partial order rules (14.5.4.2) are used to determine
4712 // whether one of the specializations is more specialized
4713 // than the others. If none of the specializations is more
4714 // specialized than all of the other matching
4715 // specializations, then the use of the variable template is
4716 // ambiguous and the program is ill-formed.
4717 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4718 PEnd = Matched.end();
4719 P != PEnd; ++P) {
4720 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4721 PointOfInstantiation) ==
4722 P->Partial)
4723 Best = P;
4724 }
4725
4726 // Determine if the best partial specialization is more specialized than
4727 // the others.
4728 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4729 PEnd = Matched.end();
4730 P != PEnd; ++P) {
4732 P->Partial, Best->Partial,
4733 PointOfInstantiation) != Best->Partial) {
4734 AmbiguousPartialSpec = true;
4735 break;
4736 }
4737 }
4738 }
4739
4740 // Instantiate using the best variable template partial specialization.
4741 InstantiationPattern = Best->Partial;
4742 PartialSpecArgs = Best->Args;
4743 } else {
4744 // -- If no match is found, the instantiation is generated
4745 // from the primary template.
4746 // InstantiationPattern = Template->getTemplatedDecl();
4747 }
4748
4749 // 2. Create the canonical declaration.
4750 // Note that we do not instantiate a definition until we see an odr-use
4751 // in DoMarkVarDeclReferenced().
4752 // FIXME: LateAttrs et al.?
4754 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4755 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4756 if (!Decl)
4757 return true;
4758 if (SetWrittenArgs)
4759 Decl->setTemplateArgsAsWritten(TemplateArgs);
4760
4761 if (AmbiguousPartialSpec) {
4762 // Partial ordering did not produce a clear winner. Complain.
4764 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4765 << Decl;
4766
4767 // Print the matching partial specializations.
4768 for (MatchResult P : Matched)
4769 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4770 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4771 *P.Args);
4772 return true;
4773 }
4774
4776 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4777 Decl->setInstantiationOf(D, PartialSpecArgs);
4778
4779 checkSpecializationReachability(TemplateNameLoc, Decl);
4780
4781 assert(Decl && "No variable template specialization?");
4782 return Decl;
4783}
4784
4786 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4787 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4788 const TemplateArgumentListInfo *TemplateArgs) {
4789
4790 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4791 *TemplateArgs, /*SetWrittenArgs=*/false);
4792 if (Decl.isInvalid())
4793 return ExprError();
4794
4795 if (!Decl.get())
4796 return ExprResult();
4797
4798 VarDecl *Var = cast<VarDecl>(Decl.get());
4801 NameInfo.getLoc());
4802
4803 // Build an ordinary singleton decl ref.
4804 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4805}
4806
4808 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4810 const TemplateArgumentListInfo *TemplateArgs) {
4811 assert(Template && "A variable template id without template?");
4812
4813 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4814 Template->templateParameterKind() !=
4816 return ExprResult();
4817
4818 // Check that the template argument list is well-formed for this template.
4821 Template, TemplateLoc,
4822 // FIXME: TemplateArgs will not be modified because
4823 // UpdateArgsWithConversions is false, however, we should
4824 // CheckTemplateArgumentList to be const-correct.
4825 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4826 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4827 /*UpdateArgsWithConversions=*/false))
4828 return true;
4829
4831 R.addDecl(Template);
4832
4833 // FIXME: We model references to variable template and concept parameters
4834 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4835 // data, can generally be used in the same places and work the same way.
4836 // However, it might be cleaner to use a dedicated AST node in the long run.
4839 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4840 /*KnownDependent=*/false,
4841 /*KnownInstantiationDependent=*/false);
4842}
4843
4845 SourceLocation Loc) {
4846 Diag(Loc, diag::err_template_missing_args)
4847 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4848 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4849 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4850 }
4851}
4852
4854 bool TemplateKeyword,
4855 TemplateDecl *TD,
4856 SourceLocation Loc) {
4857 TemplateName Name = Context.getQualifiedTemplateName(
4858 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4860}
4861
4863 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4864 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4865 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4866 bool DoCheckConstraintSatisfaction) {
4867 assert(NamedConcept && "A concept template id without a template?");
4868
4869 if (NamedConcept->isInvalidDecl())
4870 return ExprError();
4871
4874 NamedConcept, ConceptNameInfo.getLoc(),
4875 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4876 /*DefaultArgs=*/{},
4877 /*PartialTemplateArgs=*/false, CTAI,
4878 /*UpdateArgsWithConversions=*/false))
4879 return ExprError();
4880
4881 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4882
4883 // There's a bug with CTAI.CanonicalConverted.
4884 // If the template argument contains a DependentDecltypeType that includes a
4885 // TypeAliasType, and the same written type had occurred previously in the
4886 // source, then the DependentDecltypeType would be canonicalized to that
4887 // previous type which would mess up the substitution.
4888 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4890 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4891 CTAI.SugaredConverted);
4892 ConstraintSatisfaction Satisfaction;
4893 bool AreArgsDependent =
4894 TemplateSpecializationType::anyDependentTemplateArguments(
4895 *TemplateArgs, CTAI.SugaredConverted);
4896 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4897 /*Final=*/false);
4899 Context,
4901 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4903
4904 bool Error = false;
4905 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4906 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4907 DoCheckConstraintSatisfaction) {
4908
4910
4913
4915 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4916 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4917 TemplateArgs->getRAngleLoc()),
4918 Satisfaction, CL);
4919 Satisfaction.ContainsErrors = Error;
4920 }
4921
4922 if (Error)
4923 return ExprError();
4924
4926 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4927}
4928
4930 SourceLocation TemplateKWLoc,
4931 LookupResult &R,
4932 bool RequiresADL,
4933 const TemplateArgumentListInfo *TemplateArgs) {
4934 // FIXME: Can we do any checking at this point? I guess we could check the
4935 // template arguments that we have against the template name, if the template
4936 // name refers to a single template. That's not a terribly common case,
4937 // though.
4938 // foo<int> could identify a single function unambiguously
4939 // This approach does NOT work, since f<int>(1);
4940 // gets resolved prior to resorting to overload resolution
4941 // i.e., template<class T> void f(double);
4942 // vs template<class T, class U> void f(U);
4943
4944 // These should be filtered out by our callers.
4945 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4946
4947 // Non-function templates require a template argument list.
4948 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4949 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4951 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4952 return ExprError();
4953 }
4954 }
4955 bool KnownDependent = false;
4956 // In C++1y, check variable template ids.
4957 if (R.getAsSingle<VarTemplateDecl>()) {
4959 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4960 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4961 if (Res.isInvalid() || Res.isUsable())
4962 return Res;
4963 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4964 KnownDependent = true;
4965 }
4966
4967 // We don't want lookup warnings at this point.
4968 R.suppressDiagnostics();
4969
4970 if (R.getAsSingle<ConceptDecl>()) {
4971 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4972 R.getRepresentativeDecl(),
4973 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4974 }
4975
4976 // Check variable template ids (C++17) and concept template parameters
4977 // (C++26).
4979 if (R.getAsSingle<TemplateTemplateParmDecl>())
4981 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
4982 TemplateKWLoc, TemplateArgs);
4983
4984 // Function templates
4986 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
4987 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4988 R.begin(), R.end(), KnownDependent,
4989 /*KnownInstantiationDependent=*/false);
4990 // Model the templates with UnresolvedTemplateTy. The expression should then
4991 // either be transformed in an instantiation or be diagnosed in
4992 // CheckPlaceholderExpr.
4993 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4994 !R.getFoundDecl()->getAsFunction())
4995 ULE->setType(Context.UnresolvedTemplateTy);
4996
4997 return ULE;
4998}
4999
5001 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5002 const DeclarationNameInfo &NameInfo,
5003 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5004 assert(TemplateArgs || TemplateKWLoc.isValid());
5005
5006 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5007 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5008 /*EnteringContext=*/false, TemplateKWLoc))
5009 return ExprError();
5010
5011 if (R.isAmbiguous())
5012 return ExprError();
5013
5014 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5015 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5016
5017 if (R.empty()) {
5019 Diag(NameInfo.getLoc(), diag::err_no_member)
5020 << NameInfo.getName() << DC << SS.getRange();
5021 return ExprError();
5022 }
5023
5024 // If necessary, build an implicit class member access.
5025 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5026 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5027 /*S=*/nullptr);
5028
5029 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5030}
5031
5033 CXXScopeSpec &SS,
5034 SourceLocation TemplateKWLoc,
5035 const UnqualifiedId &Name,
5036 ParsedType ObjectType,
5037 bool EnteringContext,
5039 bool AllowInjectedClassName) {
5040 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5041 Diag(TemplateKWLoc,
5043 diag::warn_cxx98_compat_template_outside_of_template :
5044 diag::ext_template_outside_of_template)
5045 << FixItHint::CreateRemoval(TemplateKWLoc);
5046
5047 if (SS.isInvalid())
5048 return TNK_Non_template;
5049
5050 // Figure out where isTemplateName is going to look.
5051 DeclContext *LookupCtx = nullptr;
5052 if (SS.isNotEmpty())
5053 LookupCtx = computeDeclContext(SS, EnteringContext);
5054 else if (ObjectType)
5055 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5056
5057 // C++0x [temp.names]p5:
5058 // If a name prefixed by the keyword template is not the name of
5059 // a template, the program is ill-formed. [Note: the keyword
5060 // template may not be applied to non-template members of class
5061 // templates. -end note ] [ Note: as is the case with the
5062 // typename prefix, the template prefix is allowed in cases
5063 // where it is not strictly necessary; i.e., when the
5064 // nested-name-specifier or the expression on the left of the ->
5065 // or . is not dependent on a template-parameter, or the use
5066 // does not appear in the scope of a template. -end note]
5067 //
5068 // Note: C++03 was more strict here, because it banned the use of
5069 // the "template" keyword prior to a template-name that was not a
5070 // dependent name. C++ DR468 relaxed this requirement (the
5071 // "template" keyword is now permitted). We follow the C++0x
5072 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5073 bool MemberOfUnknownSpecialization;
5074 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5075 ObjectType, EnteringContext, Result,
5076 MemberOfUnknownSpecialization);
5077 if (TNK != TNK_Non_template) {
5078 // We resolved this to a (non-dependent) template name. Return it.
5079 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5080 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5082 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5083 // C++14 [class.qual]p2:
5084 // In a lookup in which function names are not ignored and the
5085 // nested-name-specifier nominates a class C, if the name specified
5086 // [...] is the injected-class-name of C, [...] the name is instead
5087 // considered to name the constructor
5088 //
5089 // We don't get here if naming the constructor would be valid, so we
5090 // just reject immediately and recover by treating the
5091 // injected-class-name as naming the template.
5092 Diag(Name.getBeginLoc(),
5093 diag::ext_out_of_line_qualified_id_type_names_constructor)
5094 << Name.Identifier
5095 << 0 /*injected-class-name used as template name*/
5096 << TemplateKWLoc.isValid();
5097 }
5098 return TNK;
5099 }
5100
5101 if (!MemberOfUnknownSpecialization) {
5102 // Didn't find a template name, and the lookup wasn't dependent.
5103 // Do the lookup again to determine if this is a "nothing found" case or
5104 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5105 // need to do this.
5107 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5109 // Tell LookupTemplateName that we require a template so that it diagnoses
5110 // cases where it finds a non-template.
5111 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5112 ? RequiredTemplateKind(TemplateKWLoc)
5114 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5115 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5116 !R.isAmbiguous()) {
5117 if (LookupCtx)
5118 Diag(Name.getBeginLoc(), diag::err_no_member)
5119 << DNI.getName() << LookupCtx << SS.getRange();
5120 else
5121 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5122 << DNI.getName() << SS.getRange();
5123 }
5124 return TNK_Non_template;
5125 }
5126
5127 NestedNameSpecifier Qualifier = SS.getScopeRep();
5128
5129 switch (Name.getKind()) {
5131 Result = TemplateTy::make(Context.getDependentTemplateName(
5132 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5134
5136 Result = TemplateTy::make(Context.getDependentTemplateName(
5137 {Qualifier, Name.OperatorFunctionId.Operator,
5138 TemplateKWLoc.isValid()}));
5139 return TNK_Function_template;
5140
5142 // This is a kind of template name, but can never occur in a dependent
5143 // scope (literal operators can only be declared at namespace scope).
5144 break;
5145
5146 default:
5147 break;
5148 }
5149
5150 // This name cannot possibly name a dependent template. Diagnose this now
5151 // rather than building a dependent template name that can never be valid.
5152 Diag(Name.getBeginLoc(),
5153 diag::err_template_kw_refers_to_dependent_non_template)
5155 << TemplateKWLoc.isValid() << TemplateKWLoc;
5156 return TNK_Non_template;
5157}
5158
5161 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5162 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5163 const TemplateArgument &Arg = AL.getArgument();
5165 TypeSourceInfo *TSI = nullptr;
5166
5167 // Check template type parameter.
5168 switch(Arg.getKind()) {
5170 // C++ [temp.arg.type]p1:
5171 // A template-argument for a template-parameter which is a
5172 // type shall be a type-id.
5173 ArgType = Arg.getAsType();
5174 TSI = AL.getTypeSourceInfo();
5175 break;
5178 // We have a template type parameter but the template argument
5179 // is a template without any arguments.
5180 SourceRange SR = AL.getSourceRange();
5183 return true;
5184 }
5186 // We have a template type parameter but the template argument is an
5187 // expression; see if maybe it is missing the "typename" keyword.
5188 CXXScopeSpec SS;
5189 DeclarationNameInfo NameInfo;
5190
5191 if (DependentScopeDeclRefExpr *ArgExpr =
5192 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5193 SS.Adopt(ArgExpr->getQualifierLoc());
5194 NameInfo = ArgExpr->getNameInfo();
5195 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5196 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5197 if (ArgExpr->isImplicitAccess()) {
5198 SS.Adopt(ArgExpr->getQualifierLoc());
5199 NameInfo = ArgExpr->getMemberNameInfo();
5200 }
5201 }
5202
5203 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5204 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5205 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5206
5207 if (Result.getAsSingle<TypeDecl>() ||
5208 Result.wasNotFoundInCurrentInstantiation()) {
5209 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5210 // Suggest that the user add 'typename' before the NNS.
5212 Diag(Loc, getLangOpts().MSVCCompat
5213 ? diag::ext_ms_template_type_arg_missing_typename
5214 : diag::err_template_arg_must_be_type_suggest)
5215 << FixItHint::CreateInsertion(Loc, "typename ");
5217
5218 // Recover by synthesizing a type using the location information that we
5219 // already have.
5220 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5221 SS.getScopeRep(), II);
5222 TypeLocBuilder TLB;
5224 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5226 TL.setNameLoc(NameInfo.getLoc());
5227 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5228
5229 // Overwrite our input TemplateArgumentLoc so that we can recover
5230 // properly.
5233
5234 break;
5235 }
5236 }
5237 // fallthrough
5238 [[fallthrough]];
5239 }
5240 default: {
5241 // We allow instantiating a template with template argument packs when
5242 // building deduction guides or mapping constraint template parameters.
5243 if (Arg.getKind() == TemplateArgument::Pack &&
5244 (CodeSynthesisContexts.back().Kind ==
5247 SugaredConverted.push_back(Arg);
5248 CanonicalConverted.push_back(Arg);
5249 return false;
5250 }
5251 // We have a template type parameter but the template argument
5252 // is not a type.
5253 SourceRange SR = AL.getSourceRange();
5254 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5256
5257 return true;
5258 }
5259 }
5260
5261 if (CheckTemplateArgument(TSI))
5262 return true;
5263
5264 // Objective-C ARC:
5265 // If an explicitly-specified template argument type is a lifetime type
5266 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5267 if (getLangOpts().ObjCAutoRefCount &&
5268 ArgType->isObjCLifetimeType() &&
5269 !ArgType.getObjCLifetime()) {
5270 Qualifiers Qs;
5272 ArgType = Context.getQualifiedType(ArgType, Qs);
5273 }
5274
5275 SugaredConverted.push_back(TemplateArgument(ArgType));
5276 CanonicalConverted.push_back(
5277 TemplateArgument(Context.getCanonicalType(ArgType)));
5278 return false;
5279}
5280
5281/// Substitute template arguments into the default template argument for
5282/// the given template type parameter.
5283///
5284/// \param SemaRef the semantic analysis object for which we are performing
5285/// the substitution.
5286///
5287/// \param Template the template that we are synthesizing template arguments
5288/// for.
5289///
5290/// \param TemplateLoc the location of the template name that started the
5291/// template-id we are checking.
5292///
5293/// \param RAngleLoc the location of the right angle bracket ('>') that
5294/// terminates the template-id.
5295///
5296/// \param Param the template template parameter whose default we are
5297/// substituting into.
5298///
5299/// \param Converted the list of template arguments provided for template
5300/// parameters that precede \p Param in the template parameter list.
5301///
5302/// \param Output the resulting substituted template argument.
5303///
5304/// \returns true if an error occurred.
5306 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5307 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5308 ArrayRef<TemplateArgument> SugaredConverted,
5309 ArrayRef<TemplateArgument> CanonicalConverted,
5310 TemplateArgumentLoc &Output) {
5311 Output = Param->getDefaultArgument();
5312
5313 // If the argument type is dependent, instantiate it now based
5314 // on the previously-computed template arguments.
5315 if (Output.getArgument().isInstantiationDependent()) {
5316 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5317 SugaredConverted,
5318 SourceRange(TemplateLoc, RAngleLoc));
5319 if (Inst.isInvalid())
5320 return true;
5321
5322 // Only substitute for the innermost template argument list.
5323 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5324 /*Final=*/true);
5325 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5326 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5327
5328 bool ForLambdaCallOperator = false;
5329 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5330 ForLambdaCallOperator = Rec->isLambda();
5331 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5332 !ForLambdaCallOperator);
5333
5334 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5335 Param->getDefaultArgumentLoc(),
5336 Param->getDeclName()))
5337 return true;
5338 }
5339
5340 return false;
5341}
5342
5343/// Substitute template arguments into the default template argument for
5344/// the given non-type template parameter.
5345///
5346/// \param SemaRef the semantic analysis object for which we are performing
5347/// the substitution.
5348///
5349/// \param Template the template that we are synthesizing template arguments
5350/// for.
5351///
5352/// \param TemplateLoc the location of the template name that started the
5353/// template-id we are checking.
5354///
5355/// \param RAngleLoc the location of the right angle bracket ('>') that
5356/// terminates the template-id.
5357///
5358/// \param Param the non-type template parameter whose default we are
5359/// substituting into.
5360///
5361/// \param Converted the list of template arguments provided for template
5362/// parameters that precede \p Param in the template parameter list.
5363///
5364/// \returns the substituted template argument, or NULL if an error occurred.
5366 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5367 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5368 ArrayRef<TemplateArgument> SugaredConverted,
5369 ArrayRef<TemplateArgument> CanonicalConverted,
5370 TemplateArgumentLoc &Output) {
5371 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5372 SugaredConverted,
5373 SourceRange(TemplateLoc, RAngleLoc));
5374 if (Inst.isInvalid())
5375 return true;
5376
5377 // Only substitute for the innermost template argument list.
5378 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5379 /*Final=*/true);
5380 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5381 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5382
5383 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5384 EnterExpressionEvaluationContext ConstantEvaluated(
5386 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5387 TemplateArgLists, Output);
5388}
5389
5390/// Substitute template arguments into the default template argument for
5391/// the given template template parameter.
5392///
5393/// \param SemaRef the semantic analysis object for which we are performing
5394/// the substitution.
5395///
5396/// \param Template the template that we are synthesizing template arguments
5397/// for.
5398///
5399/// \param TemplateLoc the location of the template name that started the
5400/// template-id we are checking.
5401///
5402/// \param RAngleLoc the location of the right angle bracket ('>') that
5403/// terminates the template-id.
5404///
5405/// \param Param the template template parameter whose default we are
5406/// substituting into.
5407///
5408/// \param Converted the list of template arguments provided for template
5409/// parameters that precede \p Param in the template parameter list.
5410///
5411/// \param QualifierLoc Will be set to the nested-name-specifier (with
5412/// source-location information) that precedes the template name.
5413///
5414/// \returns the substituted template argument, or NULL if an error occurred.
5416 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5417 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5419 ArrayRef<TemplateArgument> SugaredConverted,
5420 ArrayRef<TemplateArgument> CanonicalConverted,
5421 NestedNameSpecifierLoc &QualifierLoc) {
5423 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5424 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5425 if (Inst.isInvalid())
5426 return TemplateName();
5427
5428 // Only substitute for the innermost template argument list.
5429 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5430 /*Final=*/true);
5431 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5432 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5433
5434 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5435
5436 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5437 QualifierLoc = A.getTemplateQualifierLoc();
5438 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5440 A.getTemplateNameLoc(), TemplateArgLists);
5441}
5442
5444 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5445 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5446 ArrayRef<TemplateArgument> SugaredConverted,
5447 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5448 HasDefaultArg = false;
5449
5450 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5451 if (!hasReachableDefaultArgument(TypeParm))
5452 return TemplateArgumentLoc();
5453
5454 HasDefaultArg = true;
5455 TemplateArgumentLoc Output;
5456 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5457 RAngleLoc, TypeParm, SugaredConverted,
5458 CanonicalConverted, Output))
5459 return TemplateArgumentLoc();
5460 return Output;
5461 }
5462
5463 if (NonTypeTemplateParmDecl *NonTypeParm
5464 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5465 if (!hasReachableDefaultArgument(NonTypeParm))
5466 return TemplateArgumentLoc();
5467
5468 HasDefaultArg = true;
5469 TemplateArgumentLoc Output;
5470 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5471 RAngleLoc, NonTypeParm, SugaredConverted,
5472 CanonicalConverted, Output))
5473 return TemplateArgumentLoc();
5474 return Output;
5475 }
5476
5477 TemplateTemplateParmDecl *TempTempParm
5479 if (!hasReachableDefaultArgument(TempTempParm))
5480 return TemplateArgumentLoc();
5481
5482 HasDefaultArg = true;
5483 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5484 NestedNameSpecifierLoc QualifierLoc;
5486 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5487 SugaredConverted, CanonicalConverted, QualifierLoc);
5488 if (TName.isNull())
5489 return TemplateArgumentLoc();
5490
5491 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5492 QualifierLoc, A.getTemplateNameLoc());
5493}
5494
5495/// Convert a template-argument that we parsed as a type into a template, if
5496/// possible. C++ permits injected-class-names to perform dual service as
5497/// template template arguments and as template type arguments.
5500 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5501 if (!TagLoc)
5502 return TemplateArgumentLoc();
5503
5504 // If this type was written as an injected-class-name, it can be used as a
5505 // template template argument.
5506 // If this type was written as an injected-class-name, it may have been
5507 // converted to a RecordType during instantiation. If the RecordType is
5508 // *not* wrapped in a TemplateSpecializationType and denotes a class
5509 // template specialization, it must have come from an injected-class-name.
5510
5511 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5512 if (Name.isNull())
5513 return TemplateArgumentLoc();
5514
5515 return TemplateArgumentLoc(Context, Name,
5516 /*TemplateKWLoc=*/SourceLocation(),
5517 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5518}
5519
5522 SourceLocation TemplateLoc,
5523 SourceLocation RAngleLoc,
5524 unsigned ArgumentPackIndex,
5527 // Check template type parameters.
5528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5529 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5530 CTAI.CanonicalConverted);
5531
5532 const TemplateArgument &Arg = ArgLoc.getArgument();
5533 // Check non-type template parameters.
5534 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5535 // Do substitution on the type of the non-type template parameter
5536 // with the template arguments we've seen thus far. But if the
5537 // template has a dependent context then we cannot substitute yet.
5538 QualType NTTPType = NTTP->getType();
5539 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5540 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5541
5542 if (NTTPType->isInstantiationDependentType()) {
5543 // Do substitution on the type of the non-type template parameter.
5544 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5545 CTAI.SugaredConverted,
5546 SourceRange(TemplateLoc, RAngleLoc));
5547 if (Inst.isInvalid())
5548 return true;
5549
5551 /*Final=*/true);
5552 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5553 // If the parameter is a pack expansion, expand this slice of the pack.
5554 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5555 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5556 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5557 NTTP->getDeclName());
5558 } else {
5559 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5560 NTTP->getDeclName());
5561 }
5562
5563 // If that worked, check the non-type template parameter type
5564 // for validity.
5565 if (!NTTPType.isNull())
5566 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5567 NTTP->getLocation());
5568 if (NTTPType.isNull())
5569 return true;
5570 }
5571
5572 auto checkExpr = [&](Expr *E) -> Expr * {
5573 TemplateArgument SugaredResult, CanonicalResult;
5575 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5576 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5577 // If the current template argument causes an error, give up now.
5578 if (Res.isInvalid())
5579 return nullptr;
5580 CTAI.SugaredConverted.push_back(SugaredResult);
5581 CTAI.CanonicalConverted.push_back(CanonicalResult);
5582 return Res.get();
5583 };
5584
5585 switch (Arg.getKind()) {
5587 llvm_unreachable("Should never see a NULL template argument here");
5588
5590 Expr *E = Arg.getAsExpr();
5591 Expr *R = checkExpr(E);
5592 if (!R)
5593 return true;
5594 // If the resulting expression is new, then use it in place of the
5595 // old expression in the template argument.
5596 if (R != E) {
5597 TemplateArgument TA(R, /*IsCanonical=*/false);
5598 ArgLoc = TemplateArgumentLoc(TA, R);
5599 }
5600 break;
5601 }
5602
5603 // As for the converted NTTP kinds, they still might need another
5604 // conversion, as the new corresponding parameter might be different.
5605 // Ideally, we would always perform substitution starting with sugared types
5606 // and never need these, as we would still have expressions. Since these are
5607 // needed so rarely, it's probably a better tradeoff to just convert them
5608 // back to expressions.
5613 // FIXME: StructuralValue is untested here.
5614 ExprResult R =
5616 assert(R.isUsable());
5617 if (!checkExpr(R.get()))
5618 return true;
5619 break;
5620 }
5621
5624 // We were given a template template argument. It may not be ill-formed;
5625 // see below.
5628 // We have a template argument such as \c T::template X, which we
5629 // parsed as a template template argument. However, since we now
5630 // know that we need a non-type template argument, convert this
5631 // template name into an expression.
5632
5633 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5634 ArgLoc.getTemplateNameLoc());
5635
5636 CXXScopeSpec SS;
5637 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5638 // FIXME: the template-template arg was a DependentTemplateName,
5639 // so it was provided with a template keyword. However, its source
5640 // location is not stored in the template argument structure.
5641 SourceLocation TemplateKWLoc;
5643 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5644 nullptr);
5645
5646 // If we parsed the template argument as a pack expansion, create a
5647 // pack expansion expression.
5650 if (E.isInvalid())
5651 return true;
5652 }
5653
5654 TemplateArgument SugaredResult, CanonicalResult;
5656 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5657 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5658 if (E.isInvalid())
5659 return true;
5660
5661 CTAI.SugaredConverted.push_back(SugaredResult);
5662 CTAI.CanonicalConverted.push_back(CanonicalResult);
5663 break;
5664 }
5665
5666 // We have a template argument that actually does refer to a class
5667 // template, alias template, or template template parameter, and
5668 // therefore cannot be a non-type template argument.
5669 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5670 << ArgLoc.getSourceRange();
5672
5673 return true;
5674
5676 // We have a non-type template parameter but the template
5677 // argument is a type.
5678
5679 // C++ [temp.arg]p2:
5680 // In a template-argument, an ambiguity between a type-id and
5681 // an expression is resolved to a type-id, regardless of the
5682 // form of the corresponding template-parameter.
5683 //
5684 // We warn specifically about this case, since it can be rather
5685 // confusing for users.
5686 QualType T = Arg.getAsType();
5687 SourceRange SR = ArgLoc.getSourceRange();
5688 if (T->isFunctionType())
5689 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5690 else
5691 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5693 return true;
5694 }
5695
5697 llvm_unreachable("Caller must expand template argument packs");
5698 }
5699
5700 return false;
5701 }
5702
5703
5704 // Check template template parameters.
5706
5707 TemplateParameterList *Params = TempParm->getTemplateParameters();
5708 if (TempParm->isExpandedParameterPack())
5709 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5710
5711 // Substitute into the template parameter list of the template
5712 // template parameter, since previously-supplied template arguments
5713 // may appear within the template template parameter.
5714 //
5715 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5716 {
5717 // Set up a template instantiation context.
5719 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5720 CTAI.SugaredConverted,
5721 SourceRange(TemplateLoc, RAngleLoc));
5722 if (Inst.isInvalid())
5723 return true;
5724
5725 Params = SubstTemplateParams(
5726 Params, CurContext,
5728 /*Final=*/true),
5729 /*EvaluateConstraints=*/false);
5730 if (!Params)
5731 return true;
5732 }
5733
5734 // C++1z [temp.local]p1: (DR1004)
5735 // When [the injected-class-name] is used [...] as a template-argument for
5736 // a template template-parameter [...] it refers to the class template
5737 // itself.
5738 if (Arg.getKind() == TemplateArgument::Type) {
5740 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5741 if (!ConvertedArg.getArgument().isNull())
5742 ArgLoc = ConvertedArg;
5743 }
5744
5745 switch (Arg.getKind()) {
5747 llvm_unreachable("Should never see a NULL template argument here");
5748
5751 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5752 CTAI.PartialOrdering,
5753 &CTAI.StrictPackMatch))
5754 return true;
5755
5756 CTAI.SugaredConverted.push_back(Arg);
5757 CTAI.CanonicalConverted.push_back(
5758 Context.getCanonicalTemplateArgument(Arg));
5759 break;
5760
5763 auto Kind = 0;
5764 switch (TempParm->templateParameterKind()) {
5766 Kind = 1;
5767 break;
5769 Kind = 2;
5770 break;
5771 default:
5772 break;
5773 }
5774
5775 // We have a template template parameter but the template
5776 // argument does not refer to a template.
5777 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5778 << Kind << getLangOpts().CPlusPlus11;
5779 return true;
5780 }
5781
5786 llvm_unreachable("non-type argument with template template parameter");
5787
5789 llvm_unreachable("Caller must expand template argument packs");
5790 }
5791
5792 return false;
5793}
5794
5795/// Diagnose a missing template argument.
5796template<typename TemplateParmDecl>
5798 TemplateDecl *TD,
5799 const TemplateParmDecl *D,
5801 // Dig out the most recent declaration of the template parameter; there may be
5802 // declarations of the template that are more recent than TD.
5804 ->getTemplateParameters()
5805 ->getParam(D->getIndex()));
5806
5807 // If there's a default argument that's not reachable, diagnose that we're
5808 // missing a module import.
5810 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5812 D->getDefaultArgumentLoc(), Modules,
5814 /*Recover*/true);
5815 return true;
5816 }
5817
5818 // FIXME: If there's a more recent default argument that *is* visible,
5819 // diagnose that it was declared too late.
5820
5822
5823 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5824 << /*not enough args*/0
5826 << TD;
5827 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5828 return true;
5829}
5830
5831/// Check that the given template argument list is well-formed
5832/// for specializing the given template.
5834 TemplateDecl *Template, SourceLocation TemplateLoc,
5835 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5836 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5837 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5839 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5840 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5842}
5843
5844/// Check that the given template argument list is well-formed
5845/// for specializing the given template.
5848 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5849 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5850 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5852
5854 *ConstraintsNotSatisfied = false;
5855
5856 // Make a copy of the template arguments for processing. Only make the
5857 // changes at the end when successful in matching the arguments to the
5858 // template.
5859 TemplateArgumentListInfo NewArgs = TemplateArgs;
5860
5861 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5862
5863 // C++23 [temp.arg.general]p1:
5864 // [...] The type and form of each template-argument specified in
5865 // a template-id shall match the type and form specified for the
5866 // corresponding parameter declared by the template in its
5867 // template-parameter-list.
5868 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5869 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5870 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5871 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5872 LocalInstantiationScope InstScope(*this, true);
5873 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5874 ParamEnd = Params->end(),
5875 Param = ParamBegin;
5876 Param != ParamEnd;
5877 /* increment in loop */) {
5878 if (size_t ParamIdx = Param - ParamBegin;
5879 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5880 // All written arguments should have been consumed by this point.
5881 assert(ArgIdx == NumArgs && "bad default argument deduction");
5882 if (ParamIdx == DefaultArgs.StartPos) {
5883 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5884 // Default arguments from a DeducedTemplateName are already converted.
5885 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5886 CTAI.SugaredConverted.push_back(DefArg);
5887 CTAI.CanonicalConverted.push_back(
5888 Context.getCanonicalTemplateArgument(DefArg));
5889 ++Param;
5890 }
5891 continue;
5892 }
5893 }
5894
5895 // If we have an expanded parameter pack, make sure we don't have too
5896 // many arguments.
5897 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5898 if (*Expansions == SugaredArgumentPack.size()) {
5899 // We're done with this parameter pack. Pack up its arguments and add
5900 // them to the list.
5901 CTAI.SugaredConverted.push_back(
5902 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5903 SugaredArgumentPack.clear();
5904
5905 CTAI.CanonicalConverted.push_back(
5906 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5907 CanonicalArgumentPack.clear();
5908
5909 // This argument is assigned to the next parameter.
5910 ++Param;
5911 continue;
5912 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5913 // Not enough arguments for this parameter pack.
5914 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5915 << /*not enough args*/0
5917 << Template;
5919 return true;
5920 }
5921 }
5922
5923 // Check for builtins producing template packs in this context, we do not
5924 // support them yet.
5925 if (const NonTypeTemplateParmDecl *NTTP =
5926 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5927 NTTP && NTTP->isPackExpansion()) {
5928 auto TL = NTTP->getTypeSourceInfo()
5929 ->getTypeLoc()
5932 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5933 for (const auto &UPP : Unexpanded) {
5934 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5935 if (!TST)
5936 continue;
5937 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5938 // Expanding a built-in pack in this context is not yet supported.
5939 Diag(TL.getEllipsisLoc(),
5940 diag::err_unsupported_builtin_template_pack_expansion)
5941 << TST->getTemplateName();
5942 return true;
5943 }
5944 }
5945
5946 if (ArgIdx < NumArgs) {
5947 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5948 bool NonPackParameter =
5949 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5950 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5951
5952 if (ArgIsExpansion && CTAI.MatchingTTP) {
5953 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5954 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5955 ++Param) {
5956 TemplateArgument &Arg = Args[Param - First];
5957 Arg = ArgLoc.getArgument();
5958 if (!(*Param)->isTemplateParameterPack() ||
5959 getExpandedPackSize(*Param))
5960 Arg = Arg.getPackExpansionPattern();
5961 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5962 SaveAndRestore _1(CTAI.PartialOrdering, false);
5963 SaveAndRestore _2(CTAI.MatchingTTP, true);
5964 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5965 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5967 return true;
5968 Arg = NewArgLoc.getArgument();
5969 CTAI.CanonicalConverted.back().setIsDefaulted(
5970 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5971 CTAI.CanonicalConverted,
5972 Params->getDepth()));
5973 }
5974 ArgLoc = TemplateArgumentLoc(
5977 } else {
5978 SaveAndRestore _1(CTAI.PartialOrdering, false);
5979 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5980 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5982 return true;
5983 CTAI.CanonicalConverted.back().setIsDefaulted(
5984 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5985 *Param, CTAI.CanonicalConverted,
5986 Params->getDepth()));
5987 if (ArgIsExpansion && NonPackParameter) {
5988 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5989 // alias template, builtin template, or concept, and it's not part of
5990 // a parameter pack. This can't be canonicalized, so reject it now.
5992 Template)) {
5993 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
5995 : 0;
5996 Diag(ArgLoc.getLocation(),
5997 diag::err_template_expansion_into_fixed_list)
5998 << DiagSelect << ArgLoc.getSourceRange();
6000 return true;
6001 }
6002 }
6003 }
6004
6005 // We're now done with this argument.
6006 ++ArgIdx;
6007
6008 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6009 // Directly convert the remaining arguments, because we don't know what
6010 // parameters they'll match up with.
6011
6012 if (!SugaredArgumentPack.empty()) {
6013 // If we were part way through filling in an expanded parameter pack,
6014 // fall back to just producing individual arguments.
6015 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6016 SugaredArgumentPack.begin(),
6017 SugaredArgumentPack.end());
6018 SugaredArgumentPack.clear();
6019
6020 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6021 CanonicalArgumentPack.begin(),
6022 CanonicalArgumentPack.end());
6023 CanonicalArgumentPack.clear();
6024 }
6025
6026 while (ArgIdx < NumArgs) {
6027 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6028 CTAI.SugaredConverted.push_back(Arg);
6029 CTAI.CanonicalConverted.push_back(
6030 Context.getCanonicalTemplateArgument(Arg));
6031 ++ArgIdx;
6032 }
6033
6034 return false;
6035 }
6036
6037 if ((*Param)->isTemplateParameterPack()) {
6038 // The template parameter was a template parameter pack, so take the
6039 // deduced argument and place it on the argument pack. Note that we
6040 // stay on the same template parameter so that we can deduce more
6041 // arguments.
6042 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6043 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6044 } else {
6045 // Move to the next template parameter.
6046 ++Param;
6047 }
6048 continue;
6049 }
6050
6051 // If we're checking a partial template argument list, we're done.
6052 if (PartialTemplateArgs) {
6053 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6054 CTAI.SugaredConverted.push_back(
6055 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6056 CTAI.CanonicalConverted.push_back(
6057 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6058 }
6059 return false;
6060 }
6061
6062 // If we have a template parameter pack with no more corresponding
6063 // arguments, just break out now and we'll fill in the argument pack below.
6064 if ((*Param)->isTemplateParameterPack()) {
6065 assert(!getExpandedPackSize(*Param) &&
6066 "Should have dealt with this already");
6067
6068 // A non-expanded parameter pack before the end of the parameter list
6069 // only occurs for an ill-formed template parameter list, unless we've
6070 // got a partial argument list for a function template, so just bail out.
6071 if (Param + 1 != ParamEnd) {
6072 assert(
6073 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6074 "Concept templates must have parameter packs at the end.");
6075 return true;
6076 }
6077
6078 CTAI.SugaredConverted.push_back(
6079 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6080 SugaredArgumentPack.clear();
6081
6082 CTAI.CanonicalConverted.push_back(
6083 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6084 CanonicalArgumentPack.clear();
6085
6086 ++Param;
6087 continue;
6088 }
6089
6090 // Check whether we have a default argument.
6091 bool HasDefaultArg;
6092
6093 // Retrieve the default template argument from the template
6094 // parameter. For each kind of template parameter, we substitute the
6095 // template arguments provided thus far and any "outer" template arguments
6096 // (when the template parameter was part of a nested template) into
6097 // the default argument.
6099 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6100 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6101
6102 if (Arg.getArgument().isNull()) {
6103 if (!HasDefaultArg) {
6104 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6105 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6106 NewArgs);
6107 if (NonTypeTemplateParmDecl *NTTP =
6108 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6109 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6110 NewArgs);
6111 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6113 NewArgs);
6114 }
6115 return true;
6116 }
6117
6118 // Introduce an instantiation record that describes where we are using
6119 // the default template argument. We're not actually instantiating a
6120 // template here, we just create this object to put a note into the
6121 // context stack.
6122 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6123 CTAI.SugaredConverted,
6124 SourceRange(TemplateLoc, RAngleLoc));
6125 if (Inst.isInvalid())
6126 return true;
6127
6128 SaveAndRestore _1(CTAI.PartialOrdering, false);
6129 SaveAndRestore _2(CTAI.MatchingTTP, false);
6130 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6131 // Check the default template argument.
6132 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6133 CTAI, CTAK_Specified))
6134 return true;
6135
6136 CTAI.SugaredConverted.back().setIsDefaulted(true);
6137 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6138
6139 // Core issue 150 (assumed resolution): if this is a template template
6140 // parameter, keep track of the default template arguments from the
6141 // template definition.
6142 if (isTemplateTemplateParameter)
6143 NewArgs.addArgument(Arg);
6144
6145 // Move to the next template parameter and argument.
6146 ++Param;
6147 ++ArgIdx;
6148 }
6149
6150 // If we're performing a partial argument substitution, allow any trailing
6151 // pack expansions; they might be empty. This can happen even if
6152 // PartialTemplateArgs is false (the list of arguments is complete but
6153 // still dependent).
6154 if (CTAI.MatchingTTP ||
6156 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6157 while (ArgIdx < NumArgs &&
6158 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6159 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6160 CTAI.SugaredConverted.push_back(Arg);
6161 CTAI.CanonicalConverted.push_back(
6162 Context.getCanonicalTemplateArgument(Arg));
6163 }
6164 }
6165
6166 // If we have any leftover arguments, then there were too many arguments.
6167 // Complain and fail.
6168 if (ArgIdx < NumArgs) {
6169 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6170 << /*too many args*/1
6172 << Template
6173 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6175 return true;
6176 }
6177
6178 // No problems found with the new argument list, propagate changes back
6179 // to caller.
6180 if (UpdateArgsWithConversions)
6181 TemplateArgs = std::move(NewArgs);
6182
6183 if (!PartialTemplateArgs) {
6184 // Setup the context/ThisScope for the case where we are needing to
6185 // re-instantiate constraints outside of normal instantiation.
6186 DeclContext *NewContext = Template->getDeclContext();
6187
6188 // If this template is in a template, make sure we extract the templated
6189 // decl.
6190 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6191 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6192 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6193
6194 Qualifiers ThisQuals;
6195 if (const auto *Method =
6196 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6197 ThisQuals = Method->getMethodQualifiers();
6198
6199 ContextRAII Context(*this, NewContext);
6200 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6201
6203 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6204 /*RelativeToPrimary=*/true,
6205 /*Pattern=*/nullptr,
6206 /*ForConceptInstantiation=*/true);
6207 if (!isa<ConceptDecl>(Template) &&
6209 Template, MLTAL,
6210 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6213 return true;
6214 }
6215 }
6216
6217 return false;
6218}
6219
6220namespace {
6221 class UnnamedLocalNoLinkageFinder
6222 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6223 {
6224 Sema &S;
6225 SourceRange SR;
6226
6228
6229 public:
6230 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6231
6232 bool Visit(QualType T) {
6233 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6234 }
6235
6236#define TYPE(Class, Parent) \
6237 bool Visit##Class##Type(const Class##Type *);
6238#define ABSTRACT_TYPE(Class, Parent) \
6239 bool Visit##Class##Type(const Class##Type *) { return false; }
6240#define NON_CANONICAL_TYPE(Class, Parent) \
6241 bool Visit##Class##Type(const Class##Type *) { return false; }
6242#include "clang/AST/TypeNodes.inc"
6243
6244 bool VisitTagDecl(const TagDecl *Tag);
6245 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6246 };
6247} // end anonymous namespace
6248
6249bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6250 return false;
6251}
6252
6253bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6254 return Visit(T->getElementType());
6255}
6256
6257bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6258 return Visit(T->getPointeeType());
6259}
6260
6261bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6262 const BlockPointerType* T) {
6263 return Visit(T->getPointeeType());
6264}
6265
6266bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6267 const LValueReferenceType* T) {
6268 return Visit(T->getPointeeType());
6269}
6270
6271bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6272 const RValueReferenceType* T) {
6273 return Visit(T->getPointeeType());
6274}
6275
6276bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6277 const MemberPointerType *T) {
6278 if (Visit(T->getPointeeType()))
6279 return true;
6280 if (auto *RD = T->getMostRecentCXXRecordDecl())
6281 return VisitTagDecl(RD);
6282 return VisitNestedNameSpecifier(T->getQualifier());
6283}
6284
6285bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6286 const ConstantArrayType* T) {
6287 return Visit(T->getElementType());
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6291 const IncompleteArrayType* T) {
6292 return Visit(T->getElementType());
6293}
6294
6295bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6296 const VariableArrayType* T) {
6297 return Visit(T->getElementType());
6298}
6299
6300bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6301 const DependentSizedArrayType* T) {
6302 return Visit(T->getElementType());
6303}
6304
6305bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6306 const DependentSizedExtVectorType* T) {
6307 return Visit(T->getElementType());
6308}
6309
6310bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6311 const DependentSizedMatrixType *T) {
6312 return Visit(T->getElementType());
6313}
6314
6315bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6316 const DependentAddressSpaceType *T) {
6317 return Visit(T->getPointeeType());
6318}
6319
6320bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6321 return Visit(T->getElementType());
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6325 const DependentVectorType *T) {
6326 return Visit(T->getElementType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6330 return Visit(T->getElementType());
6331}
6332
6333bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6334 const ConstantMatrixType *T) {
6335 return Visit(T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6339 const FunctionProtoType* T) {
6340 for (const auto &A : T->param_types()) {
6341 if (Visit(A))
6342 return true;
6343 }
6344
6345 return Visit(T->getReturnType());
6346}
6347
6348bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6349 const FunctionNoProtoType* T) {
6350 return Visit(T->getReturnType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6354 const UnresolvedUsingType*) {
6355 return false;
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6359 return false;
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6363 return Visit(T->getUnmodifiedType());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6367 return false;
6368}
6369
6370bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6371 const PackIndexingType *) {
6372 return false;
6373}
6374
6375bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6376 const UnaryTransformType*) {
6377 return false;
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6381 return Visit(T->getDeducedType());
6382}
6383
6384bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6385 const DeducedTemplateSpecializationType *T) {
6386 return Visit(T->getDeducedType());
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6390 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6394 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6395}
6396
6397bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6398 const TemplateTypeParmType*) {
6399 return false;
6400}
6401
6402bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6403 const SubstTemplateTypeParmPackType *) {
6404 return false;
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6408 const SubstBuiltinTemplatePackType *) {
6409 return false;
6410}
6411
6412bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6413 const TemplateSpecializationType*) {
6414 return false;
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6418 const InjectedClassNameType* T) {
6419 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6420}
6421
6422bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6423 const DependentNameType* T) {
6424 return VisitNestedNameSpecifier(T->getQualifier());
6425}
6426
6427bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6428 const PackExpansionType* T) {
6429 return Visit(T->getPattern());
6430}
6431
6432bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6433 return false;
6434}
6435
6436bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6437 const ObjCInterfaceType *) {
6438 return false;
6439}
6440
6441bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6442 const ObjCObjectPointerType *) {
6443 return false;
6444}
6445
6446bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6447 return Visit(T->getValueType());
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6451 const OverflowBehaviorType *T) {
6452 return Visit(T->getUnderlyingType());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6456 return false;
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6460 return false;
6461}
6462
6463bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6464 const ArrayParameterType *T) {
6465 return VisitConstantArrayType(T);
6466}
6467
6468bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6469 const DependentBitIntType *T) {
6470 return false;
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6474 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6475 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6476 ? diag::warn_cxx98_compat_template_arg_local_type
6477 : diag::ext_template_arg_local_type)
6478 << S.Context.getCanonicalTagType(Tag) << SR;
6479 return true;
6480 }
6481
6482 if (!Tag->hasNameForLinkage()) {
6483 S.Diag(SR.getBegin(),
6484 S.getLangOpts().CPlusPlus11 ?
6485 diag::warn_cxx98_compat_template_arg_unnamed_type :
6486 diag::ext_template_arg_unnamed_type) << SR;
6487 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6488 return true;
6489 }
6490
6491 return false;
6492}
6493
6494bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6495 NestedNameSpecifier NNS) {
6496 switch (NNS.getKind()) {
6501 return false;
6503 return Visit(QualType(NNS.getAsType(), 0));
6504 }
6505 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6509 const HLSLAttributedResourceType *T) {
6510 if (T->hasContainedType() && Visit(T->getContainedType()))
6511 return true;
6512 return Visit(T->getWrappedType());
6513}
6514
6515bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6516 const HLSLInlineSpirvType *T) {
6517 for (auto &Operand : T->getOperands())
6518 if (Operand.isConstant() && Operand.isLiteral())
6519 if (Visit(Operand.getResultType()))
6520 return true;
6521 return false;
6522}
6523
6525 assert(ArgInfo && "invalid TypeSourceInfo");
6526 QualType Arg = ArgInfo->getType();
6527 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6528 QualType CanonArg = Context.getCanonicalType(Arg);
6529
6530 if (CanonArg->isVariablyModifiedType()) {
6531 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6532 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6533 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6534 }
6535
6536 // C++03 [temp.arg.type]p2:
6537 // A local type, a type with no linkage, an unnamed type or a type
6538 // compounded from any of these types shall not be used as a
6539 // template-argument for a template type-parameter.
6540 //
6541 // C++11 allows these, and even in C++03 we allow them as an extension with
6542 // a warning.
6543 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6544 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6545 (void)Finder.Visit(CanonArg);
6546 }
6547
6548 return false;
6549}
6550
6556
6557/// Determine whether the given template argument is a null pointer
6558/// value of the appropriate type.
6561 QualType ParamType, Expr *Arg,
6562 Decl *Entity = nullptr) {
6563 if (Arg->isValueDependent() || Arg->isTypeDependent())
6564 return NPV_NotNullPointer;
6565
6566 // dllimport'd entities aren't constant but are available inside of template
6567 // arguments.
6568 if (Entity && Entity->hasAttr<DLLImportAttr>())
6569 return NPV_NotNullPointer;
6570
6571 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6572 llvm_unreachable(
6573 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6574
6575 if (!S.getLangOpts().CPlusPlus11)
6576 return NPV_NotNullPointer;
6577
6578 // Determine whether we have a constant expression.
6580 if (ArgRV.isInvalid())
6581 return NPV_Error;
6582 Arg = ArgRV.get();
6583
6584 Expr::EvalResult EvalResult;
6586 EvalResult.Diag = &Notes;
6587 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6588 EvalResult.HasSideEffects) {
6589 SourceLocation DiagLoc = Arg->getExprLoc();
6590
6591 // If our only note is the usual "invalid subexpression" note, just point
6592 // the caret at its location rather than producing an essentially
6593 // redundant note.
6594 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6595 diag::note_invalid_subexpr_in_const_expr) {
6596 DiagLoc = Notes[0].first;
6597 Notes.clear();
6598 }
6599
6600 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6601 << Arg->getType() << Arg->getSourceRange();
6602 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6603 S.Diag(Notes[I].first, Notes[I].second);
6604
6606 return NPV_Error;
6607 }
6608
6609 // C++11 [temp.arg.nontype]p1:
6610 // - an address constant expression of type std::nullptr_t
6611 if (Arg->getType()->isNullPtrType())
6612 return NPV_NullPointer;
6613
6614 // - a constant expression that evaluates to a null pointer value (4.10); or
6615 // - a constant expression that evaluates to a null member pointer value
6616 // (4.11); or
6617 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6618 (EvalResult.Val.isMemberPointer() &&
6619 !EvalResult.Val.getMemberPointerDecl())) {
6620 // If our expression has an appropriate type, we've succeeded.
6621 bool ObjCLifetimeConversion;
6622 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6623 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6624 ObjCLifetimeConversion))
6625 return NPV_NullPointer;
6626
6627 // The types didn't match, but we know we got a null pointer; complain,
6628 // then recover as if the types were correct.
6629 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6630 << Arg->getType() << ParamType << Arg->getSourceRange();
6632 return NPV_NullPointer;
6633 }
6634
6635 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6636 // We found a pointer that isn't null, but doesn't refer to an object.
6637 // We could just return NPV_NotNullPointer, but we can print a better
6638 // message with the information we have here.
6639 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6640 << EvalResult.Val.getAsString(S.Context, ParamType);
6642 return NPV_Error;
6643 }
6644
6645 // If we don't have a null pointer value, but we do have a NULL pointer
6646 // constant, suggest a cast to the appropriate type.
6648 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6649 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6650 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6652 ")");
6654 return NPV_NullPointer;
6655 }
6656
6657 // FIXME: If we ever want to support general, address-constant expressions
6658 // as non-type template arguments, we should return the ExprResult here to
6659 // be interpreted by the caller.
6660 return NPV_NotNullPointer;
6661}
6662
6663/// Checks whether the given template argument is compatible with its
6664/// template parameter.
6665static bool
6667 QualType ParamType, Expr *ArgIn,
6668 Expr *Arg, QualType ArgType) {
6669 bool ObjCLifetimeConversion;
6670 if (ParamType->isPointerType() &&
6671 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6672 S.IsQualificationConversion(ArgType, ParamType, false,
6673 ObjCLifetimeConversion)) {
6674 // For pointer-to-object types, qualification conversions are
6675 // permitted.
6676 } else {
6677 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6678 if (!ParamRef->getPointeeType()->isFunctionType()) {
6679 // C++ [temp.arg.nontype]p5b3:
6680 // For a non-type template-parameter of type reference to
6681 // object, no conversions apply. The type referred to by the
6682 // reference may be more cv-qualified than the (otherwise
6683 // identical) type of the template- argument. The
6684 // template-parameter is bound directly to the
6685 // template-argument, which shall be an lvalue.
6686
6687 // FIXME: Other qualifiers?
6688 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6689 unsigned ArgQuals = ArgType.getCVRQualifiers();
6690
6691 if ((ParamQuals | ArgQuals) != ParamQuals) {
6692 S.Diag(Arg->getBeginLoc(),
6693 diag::err_template_arg_ref_bind_ignores_quals)
6694 << ParamType << Arg->getType() << Arg->getSourceRange();
6696 return true;
6697 }
6698 }
6699 }
6700
6701 // At this point, the template argument refers to an object or
6702 // function with external linkage. We now need to check whether the
6703 // argument and parameter types are compatible.
6704 if (!S.Context.hasSameUnqualifiedType(ArgType,
6705 ParamType.getNonReferenceType())) {
6706 // We can't perform this conversion or binding.
6707 if (ParamType->isReferenceType())
6708 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6709 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6710 else
6711 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6712 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6714 return true;
6715 }
6716 }
6717
6718 return false;
6719}
6720
6721/// Checks whether the given template argument is the address
6722/// of an object or function according to C++ [temp.arg.nontype]p1.
6724 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6725 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6726 bool Invalid = false;
6727 Expr *Arg = ArgIn;
6728 QualType ArgType = Arg->getType();
6729
6730 bool AddressTaken = false;
6731 SourceLocation AddrOpLoc;
6732 if (S.getLangOpts().MicrosoftExt) {
6733 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6734 // dereference and address-of operators.
6735 Arg = Arg->IgnoreParenCasts();
6736
6737 bool ExtWarnMSTemplateArg = false;
6738 UnaryOperatorKind FirstOpKind;
6739 SourceLocation FirstOpLoc;
6740 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6741 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6742 if (UnOpKind == UO_Deref)
6743 ExtWarnMSTemplateArg = true;
6744 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6745 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6746 if (!AddrOpLoc.isValid()) {
6747 FirstOpKind = UnOpKind;
6748 FirstOpLoc = UnOp->getOperatorLoc();
6749 }
6750 } else
6751 break;
6752 }
6753 if (FirstOpLoc.isValid()) {
6754 if (ExtWarnMSTemplateArg)
6755 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6756 << ArgIn->getSourceRange();
6757
6758 if (FirstOpKind == UO_AddrOf)
6759 AddressTaken = true;
6760 else if (Arg->getType()->isPointerType()) {
6761 // We cannot let pointers get dereferenced here, that is obviously not a
6762 // constant expression.
6763 assert(FirstOpKind == UO_Deref);
6764 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6765 << Arg->getSourceRange();
6766 }
6767 }
6768 } else {
6769 // See through any implicit casts we added to fix the type.
6770 Arg = Arg->IgnoreImpCasts();
6771
6772 // C++ [temp.arg.nontype]p1:
6773 //
6774 // A template-argument for a non-type, non-template
6775 // template-parameter shall be one of: [...]
6776 //
6777 // -- the address of an object or function with external
6778 // linkage, including function templates and function
6779 // template-ids but excluding non-static class members,
6780 // expressed as & id-expression where the & is optional if
6781 // the name refers to a function or array, or if the
6782 // corresponding template-parameter is a reference; or
6783
6784 // In C++98/03 mode, give an extension warning on any extra parentheses.
6785 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6786 bool ExtraParens = false;
6787 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6788 if (!Invalid && !ExtraParens) {
6789 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6790 << Arg->getSourceRange();
6791 ExtraParens = true;
6792 }
6793
6794 Arg = Parens->getSubExpr();
6795 }
6796
6797 while (SubstNonTypeTemplateParmExpr *subst =
6798 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6799 Arg = subst->getReplacement()->IgnoreImpCasts();
6800
6801 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6802 if (UnOp->getOpcode() == UO_AddrOf) {
6803 Arg = UnOp->getSubExpr();
6804 AddressTaken = true;
6805 AddrOpLoc = UnOp->getOperatorLoc();
6806 }
6807 }
6808
6809 while (SubstNonTypeTemplateParmExpr *subst =
6810 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6811 Arg = subst->getReplacement()->IgnoreImpCasts();
6812 }
6813
6814 ValueDecl *Entity = nullptr;
6815 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6816 Entity = DRE->getDecl();
6817 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6818 Entity = CUE->getGuidDecl();
6819
6820 // If our parameter has pointer type, check for a null template value.
6821 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6822 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6823 Entity)) {
6824 case NPV_NullPointer:
6825 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6826 SugaredConverted = TemplateArgument(ParamType,
6827 /*isNullPtr=*/true);
6828 CanonicalConverted =
6830 /*isNullPtr=*/true);
6831 return false;
6832
6833 case NPV_Error:
6834 return true;
6835
6836 case NPV_NotNullPointer:
6837 break;
6838 }
6839 }
6840
6841 // Stop checking the precise nature of the argument if it is value dependent,
6842 // it should be checked when instantiated.
6843 if (Arg->isValueDependent()) {
6844 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6845 CanonicalConverted =
6846 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6847 return false;
6848 }
6849
6850 if (!Entity) {
6851 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6852 << Arg->getSourceRange();
6854 return true;
6855 }
6856
6857 // Cannot refer to non-static data members
6858 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6859 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6860 << Entity << Arg->getSourceRange();
6862 return true;
6863 }
6864
6865 // Cannot refer to non-static member functions
6866 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6867 if (!Method->isStatic()) {
6868 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6869 << Method << Arg->getSourceRange();
6871 return true;
6872 }
6873 }
6874
6875 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6876 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6877 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6878
6879 // A non-type template argument must refer to an object or function.
6880 if (!Func && !Var && !Guid) {
6881 // We found something, but we don't know specifically what it is.
6882 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6883 << Arg->getSourceRange();
6884 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6885 return true;
6886 }
6887
6888 // Address / reference template args must have external linkage in C++98.
6889 if (Entity->getFormalLinkage() == Linkage::Internal) {
6890 S.Diag(Arg->getBeginLoc(),
6891 S.getLangOpts().CPlusPlus11
6892 ? diag::warn_cxx98_compat_template_arg_object_internal
6893 : diag::ext_template_arg_object_internal)
6894 << !Func << Entity << Arg->getSourceRange();
6895 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6896 << !Func;
6897 } else if (!Entity->hasLinkage()) {
6898 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6899 << !Func << Entity << Arg->getSourceRange();
6900 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6901 << !Func;
6902 return true;
6903 }
6904
6905 if (Var) {
6906 // A value of reference type is not an object.
6907 if (Var->getType()->isReferenceType()) {
6908 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6909 << Var->getType() << Arg->getSourceRange();
6911 return true;
6912 }
6913
6914 // A template argument must have static storage duration.
6915 if (Var->getTLSKind()) {
6916 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6917 << Arg->getSourceRange();
6918 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6919 return true;
6920 }
6921 }
6922
6923 if (AddressTaken && ParamType->isReferenceType()) {
6924 // If we originally had an address-of operator, but the
6925 // parameter has reference type, complain and (if things look
6926 // like they will work) drop the address-of operator.
6927 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6928 ParamType.getNonReferenceType())) {
6929 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6930 << ParamType;
6932 return true;
6933 }
6934
6935 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6936 << ParamType
6937 << FixItHint::CreateRemoval(AddrOpLoc);
6939
6940 ArgType = Entity->getType();
6941 }
6942
6943 // If the template parameter has pointer type, either we must have taken the
6944 // address or the argument must decay to a pointer.
6945 if (!AddressTaken && ParamType->isPointerType()) {
6946 if (Func) {
6947 // Function-to-pointer decay.
6948 ArgType = S.Context.getPointerType(Func->getType());
6949 } else if (Entity->getType()->isArrayType()) {
6950 // Array-to-pointer decay.
6951 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6952 } else {
6953 // If the template parameter has pointer type but the address of
6954 // this object was not taken, complain and (possibly) recover by
6955 // taking the address of the entity.
6956 ArgType = S.Context.getPointerType(Entity->getType());
6957 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6958 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6959 << ParamType;
6961 return true;
6962 }
6963
6964 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6965 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6966
6968 }
6969 }
6970
6971 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6972 Arg, ArgType))
6973 return true;
6974
6975 // Create the template argument.
6976 SugaredConverted = TemplateArgument(Entity, ParamType);
6977 CanonicalConverted =
6979 S.Context.getCanonicalType(ParamType));
6980 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6981 return false;
6982}
6983
6984/// Checks whether the given template argument is a pointer to
6985/// member constant according to C++ [temp.arg.nontype]p1.
6987 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6988 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6989 bool Invalid = false;
6990
6991 Expr *Arg = ResultArg;
6992 bool ObjCLifetimeConversion;
6993
6994 // C++ [temp.arg.nontype]p1:
6995 //
6996 // A template-argument for a non-type, non-template
6997 // template-parameter shall be one of: [...]
6998 //
6999 // -- a pointer to member expressed as described in 5.3.1.
7000 DeclRefExpr *DRE = nullptr;
7001
7002 // In C++98/03 mode, give an extension warning on any extra parentheses.
7003 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7004 bool ExtraParens = false;
7005 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7006 if (!Invalid && !ExtraParens) {
7007 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7008 << Arg->getSourceRange();
7009 ExtraParens = true;
7010 }
7011
7012 Arg = Parens->getSubExpr();
7013 }
7014
7015 while (SubstNonTypeTemplateParmExpr *subst =
7016 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7017 Arg = subst->getReplacement()->IgnoreImpCasts();
7018
7019 // A pointer-to-member constant written &Class::member.
7020 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7021 if (UnOp->getOpcode() == UO_AddrOf) {
7022 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7023 if (DRE && !DRE->getQualifier())
7024 DRE = nullptr;
7025 }
7026 }
7027 // A constant of pointer-to-member type.
7028 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7029 ValueDecl *VD = DRE->getDecl();
7030 if (VD->getType()->isMemberPointerType()) {
7032 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7033 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7034 CanonicalConverted =
7035 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7036 } else {
7037 SugaredConverted = TemplateArgument(VD, ParamType);
7038 CanonicalConverted =
7040 S.Context.getCanonicalType(ParamType));
7041 }
7042 return Invalid;
7043 }
7044 }
7045
7046 DRE = nullptr;
7047 }
7048
7049 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7050
7051 // Check for a null pointer value.
7052 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7053 Entity)) {
7054 case NPV_Error:
7055 return true;
7056 case NPV_NullPointer:
7057 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7058 SugaredConverted = TemplateArgument(ParamType,
7059 /*isNullPtr*/ true);
7060 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7061 /*isNullPtr*/ true);
7062 return false;
7063 case NPV_NotNullPointer:
7064 break;
7065 }
7066
7067 if (S.IsQualificationConversion(ResultArg->getType(),
7068 ParamType.getNonReferenceType(), false,
7069 ObjCLifetimeConversion)) {
7070 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7071 ResultArg->getValueKind())
7072 .get();
7073 } else if (!S.Context.hasSameUnqualifiedType(
7074 ResultArg->getType(), ParamType.getNonReferenceType())) {
7075 // We can't perform this conversion.
7076 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7077 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7079 return true;
7080 }
7081
7082 if (!DRE)
7083 return S.Diag(Arg->getBeginLoc(),
7084 diag::err_template_arg_not_pointer_to_member_form)
7085 << Arg->getSourceRange();
7086
7087 if (isa<FieldDecl>(DRE->getDecl()) ||
7089 isa<CXXMethodDecl>(DRE->getDecl())) {
7090 assert((isa<FieldDecl>(DRE->getDecl()) ||
7093 ->isImplicitObjectMemberFunction()) &&
7094 "Only non-static member pointers can make it here");
7095
7096 // Okay: this is the address of a non-static member, and therefore
7097 // a member pointer constant.
7098 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7099 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7100 CanonicalConverted =
7101 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7102 } else {
7103 ValueDecl *D = DRE->getDecl();
7104 SugaredConverted = TemplateArgument(D, ParamType);
7105 CanonicalConverted =
7107 S.Context.getCanonicalType(ParamType));
7108 }
7109 return Invalid;
7110 }
7111
7112 // We found something else, but we don't know specifically what it is.
7113 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7114 << Arg->getSourceRange();
7115 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7116 return true;
7117}
7118
7119/// Check a template argument against its corresponding
7120/// non-type template parameter.
7121///
7122/// This routine implements the semantics of C++ [temp.arg.nontype].
7123/// If an error occurred, it returns ExprError(); otherwise, it
7124/// returns the converted template argument. \p ParamType is the
7125/// type of the non-type template parameter after it has been instantiated.
7127 Expr *Arg,
7128 TemplateArgument &SugaredConverted,
7129 TemplateArgument &CanonicalConverted,
7130 bool StrictCheck,
7132 SourceLocation StartLoc = Arg->getBeginLoc();
7133 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7134 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7135 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7136 DeductionArg = NewDeductionArg;
7137 if (ArgPE) {
7138 // Recreate a pack expansion if we unwrapped one.
7139 Arg = new (Context) PackExpansionExpr(
7140 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7141 } else {
7142 Arg = DeductionArg;
7143 }
7144 };
7145
7146 // If the parameter type somehow involves auto, deduce the type now.
7147 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7148 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7149 if (IsDeduced) {
7150 // When checking a deduced template argument, deduce from its type even if
7151 // the type is dependent, in order to check the types of non-type template
7152 // arguments line up properly in partial ordering.
7153 TypeSourceInfo *TSI =
7154 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7156 InitializedEntity Entity =
7159 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7160 Expr *Inits[1] = {DeductionArg};
7161 ParamType =
7163 if (ParamType.isNull())
7164 return ExprError();
7165 } else {
7166 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7167 Param->getTemplateDepth() + 1);
7168 ParamType = QualType();
7170 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7171 /*DependentDeduction=*/true,
7172 // We do not check constraints right now because the
7173 // immediately-declared constraint of the auto type is
7174 // also an associated constraint, and will be checked
7175 // along with the other associated constraints after
7176 // checking the template argument list.
7177 /*IgnoreConstraints=*/true);
7179 ParamType = TSI->getType();
7180 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7182 return ExprError();
7183 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7184 Diag(Arg->getExprLoc(),
7185 diag::err_non_type_template_parm_type_deduction_failure)
7186 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7187 << Arg->getSourceRange();
7189 return ExprError();
7190 }
7191 ParamType = SubstAutoTypeDependent(ParamType);
7192 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7193 }
7194 }
7195 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7196 // an error. The error message normally references the parameter
7197 // declaration, but here we'll pass the argument location because that's
7198 // where the parameter type is deduced.
7199 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7200 if (ParamType.isNull()) {
7202 return ExprError();
7203 }
7204 }
7205
7206 // We should have already dropped all cv-qualifiers by now.
7207 assert(!ParamType.hasQualifiers() &&
7208 "non-type template parameter type cannot be qualified");
7209
7210 // If either the parameter has a dependent type or the argument is
7211 // type-dependent, there's nothing we can check now.
7212 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7213 // Force the argument to the type of the parameter to maintain invariants.
7214 if (!IsDeduced) {
7216 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7217 ParamType->isLValueReferenceType() ? VK_LValue
7218 : ParamType->isRValueReferenceType() ? VK_XValue
7219 : VK_PRValue);
7220 if (E.isInvalid())
7221 return ExprError();
7222 setDeductionArg(E.get());
7223 }
7224 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7225 CanonicalConverted = TemplateArgument(
7226 Context.getCanonicalTemplateArgument(SugaredConverted));
7227 return Arg;
7228 }
7229
7230 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7231 if (CTAK == CTAK_Deduced && !StrictCheck &&
7232 (ParamType->isReferenceType()
7233 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7234 DeductionArg->getType())
7235 : !Context.hasSameUnqualifiedType(ParamType,
7236 DeductionArg->getType()))) {
7237 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7238 // we should actually be checking the type of the template argument in P,
7239 // not the type of the template argument deduced from A, against the
7240 // template parameter type.
7241 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7242 << Arg->getType() << ParamType.getUnqualifiedType();
7244 return ExprError();
7245 }
7246
7247 // If the argument is a pack expansion, we don't know how many times it would
7248 // expand. If we continue checking the argument, this will make the template
7249 // definition ill-formed if it would be ill-formed for any number of
7250 // expansions during instantiation time. When partial ordering or matching
7251 // template template parameters, this is exactly what we want. Otherwise, the
7252 // normal template rules apply: we accept the template if it would be valid
7253 // for any number of expansions (i.e. none).
7254 if (ArgPE && !StrictCheck) {
7255 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7256 CanonicalConverted = TemplateArgument(
7257 Context.getCanonicalTemplateArgument(SugaredConverted));
7258 return Arg;
7259 }
7260
7261 // Avoid making a copy when initializing a template parameter of class type
7262 // from a template parameter object of the same type. This is going beyond
7263 // the standard, but is required for soundness: in
7264 // template<A a> struct X { X *p; X<a> *q; };
7265 // ... we need p and q to have the same type.
7266 //
7267 // Similarly, don't inject a call to a copy constructor when initializing
7268 // from a template parameter of the same type.
7269 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7270 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7271 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7272 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7273 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7274
7275 SugaredConverted = TemplateArgument(TPO, ParamType);
7276 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7277 ParamType.getCanonicalType());
7278 return Arg;
7279 }
7281 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7282 CanonicalConverted =
7283 Context.getCanonicalTemplateArgument(SugaredConverted);
7284 return Arg;
7285 }
7286 }
7287
7288 // The initialization of the parameter from the argument is
7289 // a constant-evaluated context.
7292
7293 bool IsConvertedConstantExpression = true;
7294 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7296 StartLoc, /*DirectInit=*/false, DeductionArg);
7297 Expr *Inits[1] = {DeductionArg};
7298 InitializedEntity Entity =
7300 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7301 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7302 if (Result.isInvalid() || !Result.get())
7303 return ExprError();
7305 if (Result.isInvalid() || !Result.get())
7306 return ExprError();
7307 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7308 /*DiscardedValue=*/false,
7309 /*IsConstexpr=*/true,
7310 /*IsTemplateArgument=*/true)
7311 .get());
7312 IsConvertedConstantExpression = false;
7313 }
7314
7315 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7316 // C++17 [temp.arg.nontype]p1:
7317 // A template-argument for a non-type template parameter shall be
7318 // a converted constant expression of the type of the template-parameter.
7319 APValue Value;
7320 ExprResult ArgResult;
7321 if (IsConvertedConstantExpression) {
7323 DeductionArg, ParamType,
7324 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7325 assert(!ArgResult.isUnset());
7326 if (ArgResult.isInvalid()) {
7328 return ExprError();
7329 }
7330 } else {
7331 ArgResult = DeductionArg;
7332 }
7333
7334 // For a value-dependent argument, CheckConvertedConstantExpression is
7335 // permitted (and expected) to be unable to determine a value.
7336 if (ArgResult.get()->isValueDependent()) {
7337 setDeductionArg(ArgResult.get());
7338 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7339 CanonicalConverted =
7340 Context.getCanonicalTemplateArgument(SugaredConverted);
7341 return Arg;
7342 }
7343
7344 APValue PreNarrowingValue;
7346 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7347 false, PreNarrowingValue);
7348 if (ArgResult.isInvalid())
7349 return ExprError();
7350 setDeductionArg(ArgResult.get());
7351
7352 if (Value.isLValue()) {
7353 APValue::LValueBase Base = Value.getLValueBase();
7354 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7355 // For a non-type template-parameter of pointer or reference type,
7356 // the value of the constant expression shall not refer to
7357 assert(ParamType->isPointerOrReferenceType() ||
7358 ParamType->isNullPtrType());
7359 // -- a temporary object
7360 // -- a string literal
7361 // -- the result of a typeid expression, or
7362 // -- a predefined __func__ variable
7363 if (Base &&
7364 (!VD ||
7366 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7367 << Arg->getSourceRange();
7368 return ExprError();
7369 }
7370
7371 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7372 VD->getType()->isArrayType() &&
7373 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7374 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7375 if (ArgPE) {
7376 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7377 CanonicalConverted =
7378 Context.getCanonicalTemplateArgument(SugaredConverted);
7379 } else {
7380 SugaredConverted = TemplateArgument(VD, ParamType);
7381 CanonicalConverted =
7383 ParamType.getCanonicalType());
7384 }
7385 return Arg;
7386 }
7387
7388 // -- a subobject [until C++20]
7389 if (!getLangOpts().CPlusPlus20) {
7390 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7391 Value.isLValueOnePastTheEnd()) {
7392 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7393 << Value.getAsString(Context, ParamType);
7394 return ExprError();
7395 }
7396 assert((VD || !ParamType->isReferenceType()) &&
7397 "null reference should not be a constant expression");
7398 assert((!VD || !ParamType->isNullPtrType()) &&
7399 "non-null value of type nullptr_t?");
7400 }
7401 }
7402
7403 if (Value.isAddrLabelDiff())
7404 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7405
7406 if (ArgPE) {
7407 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7408 CanonicalConverted =
7409 Context.getCanonicalTemplateArgument(SugaredConverted);
7410 } else {
7411 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7412 CanonicalConverted =
7414 }
7415 return Arg;
7416 }
7417
7418 // These should have all been handled above using the C++17 rules.
7419 assert(!ArgPE && !StrictCheck);
7420
7421 // C++ [temp.arg.nontype]p5:
7422 // The following conversions are performed on each expression used
7423 // as a non-type template-argument. If a non-type
7424 // template-argument cannot be converted to the type of the
7425 // corresponding template-parameter then the program is
7426 // ill-formed.
7427 if (ParamType->isIntegralOrEnumerationType()) {
7428 // C++11:
7429 // -- for a non-type template-parameter of integral or
7430 // enumeration type, conversions permitted in a converted
7431 // constant expression are applied.
7432 //
7433 // C++98:
7434 // -- for a non-type template-parameter of integral or
7435 // enumeration type, integral promotions (4.5) and integral
7436 // conversions (4.7) are applied.
7437
7438 if (getLangOpts().CPlusPlus11) {
7439 // C++ [temp.arg.nontype]p1:
7440 // A template-argument for a non-type, non-template template-parameter
7441 // shall be one of:
7442 //
7443 // -- for a non-type template-parameter of integral or enumeration
7444 // type, a converted constant expression of the type of the
7445 // template-parameter; or
7446 llvm::APSInt Value;
7448 Arg, ParamType, Value, CCEKind::TemplateArg);
7449 if (ArgResult.isInvalid())
7450 return ExprError();
7451 Arg = ArgResult.get();
7452
7453 // We can't check arbitrary value-dependent arguments.
7454 if (Arg->isValueDependent()) {
7455 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7456 CanonicalConverted =
7457 Context.getCanonicalTemplateArgument(SugaredConverted);
7458 return Arg;
7459 }
7460
7461 // Widen the argument value to sizeof(parameter type). This is almost
7462 // always a no-op, except when the parameter type is bool. In
7463 // that case, this may extend the argument from 1 bit to 8 bits.
7464 QualType IntegerType = ParamType;
7465 if (const auto *ED = IntegerType->getAsEnumDecl())
7466 IntegerType = ED->getIntegerType();
7467 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7468 ? Context.getIntWidth(IntegerType)
7469 : Context.getTypeSize(IntegerType));
7470
7471 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7472 CanonicalConverted =
7473 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7474 return Arg;
7475 }
7476
7477 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7478 if (ArgResult.isInvalid())
7479 return ExprError();
7480 Arg = ArgResult.get();
7481
7482 QualType ArgType = Arg->getType();
7483
7484 // C++ [temp.arg.nontype]p1:
7485 // A template-argument for a non-type, non-template
7486 // template-parameter shall be one of:
7487 //
7488 // -- an integral constant-expression of integral or enumeration
7489 // type; or
7490 // -- the name of a non-type template-parameter; or
7491 llvm::APSInt Value;
7492 if (!ArgType->isIntegralOrEnumerationType()) {
7493 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7494 << ArgType << Arg->getSourceRange();
7496 return ExprError();
7497 }
7498 if (!Arg->isValueDependent()) {
7499 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7500 QualType T;
7501
7502 public:
7503 TmplArgICEDiagnoser(QualType T) : T(T) { }
7504
7505 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7506 SourceLocation Loc) override {
7507 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7508 }
7509 } Diagnoser(ArgType);
7510
7511 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7512 if (!Arg)
7513 return ExprError();
7514 }
7515
7516 // From here on out, all we care about is the unqualified form
7517 // of the argument type.
7518 ArgType = ArgType.getUnqualifiedType();
7519
7520 // Try to convert the argument to the parameter's type.
7521 if (Context.hasSameType(ParamType, ArgType)) {
7522 // Okay: no conversion necessary
7523 } else if (ParamType->isBooleanType()) {
7524 // This is an integral-to-boolean conversion.
7525 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7526 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7527 !ParamType->isEnumeralType()) {
7528 // This is an integral promotion or conversion.
7529 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7530 } else {
7531 // We can't perform this conversion.
7532 Diag(StartLoc, diag::err_template_arg_not_convertible)
7533 << Arg->getType() << ParamType << Arg->getSourceRange();
7535 return ExprError();
7536 }
7537
7538 // Add the value of this argument to the list of converted
7539 // arguments. We use the bitwidth and signedness of the template
7540 // parameter.
7541 if (Arg->isValueDependent()) {
7542 // The argument is value-dependent. Create a new
7543 // TemplateArgument with the converted expression.
7544 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7545 CanonicalConverted =
7546 Context.getCanonicalTemplateArgument(SugaredConverted);
7547 return Arg;
7548 }
7549
7550 QualType IntegerType = ParamType;
7551 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7552 IntegerType = ED->getIntegerType();
7553 }
7554
7555 if (ParamType->isBooleanType()) {
7556 // Value must be zero or one.
7557 Value = Value != 0;
7558 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7559 if (Value.getBitWidth() != AllowedBits)
7560 Value = Value.extOrTrunc(AllowedBits);
7561 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7562 } else {
7563 llvm::APSInt OldValue = Value;
7564
7565 // Coerce the template argument's value to the value it will have
7566 // based on the template parameter's type.
7567 unsigned AllowedBits = IntegerType->isBitIntType()
7568 ? Context.getIntWidth(IntegerType)
7569 : Context.getTypeSize(IntegerType);
7570 if (Value.getBitWidth() != AllowedBits)
7571 Value = Value.extOrTrunc(AllowedBits);
7572 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7573
7574 // Complain if an unsigned parameter received a negative value.
7575 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7576 (OldValue.isSigned() && OldValue.isNegative())) {
7577 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7578 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7579 << Arg->getSourceRange();
7581 }
7582
7583 // Complain if we overflowed the template parameter's type.
7584 unsigned RequiredBits;
7585 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7586 RequiredBits = OldValue.getActiveBits();
7587 else if (OldValue.isUnsigned())
7588 RequiredBits = OldValue.getActiveBits() + 1;
7589 else
7590 RequiredBits = OldValue.getSignificantBits();
7591 if (RequiredBits > AllowedBits) {
7592 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7593 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7594 << Arg->getSourceRange();
7596 }
7597 }
7598
7599 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7600 SugaredConverted = TemplateArgument(Context, Value, T);
7601 CanonicalConverted =
7602 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7603 return Arg;
7604 }
7605
7606 QualType ArgType = Arg->getType();
7607 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7608
7609 // Handle pointer-to-function, reference-to-function, and
7610 // pointer-to-member-function all in (roughly) the same way.
7611 if (// -- For a non-type template-parameter of type pointer to
7612 // function, only the function-to-pointer conversion (4.3) is
7613 // applied. If the template-argument represents a set of
7614 // overloaded functions (or a pointer to such), the matching
7615 // function is selected from the set (13.4).
7616 (ParamType->isPointerType() &&
7617 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7618 // -- For a non-type template-parameter of type reference to
7619 // function, no conversions apply. If the template-argument
7620 // represents a set of overloaded functions, the matching
7621 // function is selected from the set (13.4).
7622 (ParamType->isReferenceType() &&
7623 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7624 // -- For a non-type template-parameter of type pointer to
7625 // member function, no conversions apply. If the
7626 // template-argument represents a set of overloaded member
7627 // functions, the matching member function is selected from
7628 // the set (13.4).
7629 (ParamType->isMemberPointerType() &&
7630 ParamType->castAs<MemberPointerType>()->getPointeeType()
7631 ->isFunctionType())) {
7632
7633 if (Arg->getType() == Context.OverloadTy) {
7634 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7635 true,
7636 FoundResult)) {
7637 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7638 return ExprError();
7639
7640 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7641 if (Res.isInvalid())
7642 return ExprError();
7643 Arg = Res.get();
7644 ArgType = Arg->getType();
7645 } else
7646 return ExprError();
7647 }
7648
7649 if (!ParamType->isMemberPointerType()) {
7651 *this, Param, ParamType, Arg, SugaredConverted,
7652 CanonicalConverted))
7653 return ExprError();
7654 return Arg;
7655 }
7656
7658 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7659 return ExprError();
7660 return Arg;
7661 }
7662
7663 if (ParamType->isPointerType()) {
7664 // -- for a non-type template-parameter of type pointer to
7665 // object, qualification conversions (4.4) and the
7666 // array-to-pointer conversion (4.2) are applied.
7667 // C++0x also allows a value of std::nullptr_t.
7668 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7669 "Only object pointers allowed here");
7670
7672 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7673 return ExprError();
7674 return Arg;
7675 }
7676
7677 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7678 // -- For a non-type template-parameter of type reference to
7679 // object, no conversions apply. The type referred to by the
7680 // reference may be more cv-qualified than the (otherwise
7681 // identical) type of the template-argument. The
7682 // template-parameter is bound directly to the
7683 // template-argument, which must be an lvalue.
7684 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7685 "Only object references allowed here");
7686
7687 if (Arg->getType() == Context.OverloadTy) {
7689 ParamRefType->getPointeeType(),
7690 true,
7691 FoundResult)) {
7692 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7693 return ExprError();
7694 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7695 if (Res.isInvalid())
7696 return ExprError();
7697 Arg = Res.get();
7698 ArgType = Arg->getType();
7699 } else
7700 return ExprError();
7701 }
7702
7704 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7705 return ExprError();
7706 return Arg;
7707 }
7708
7709 // Deal with parameters of type std::nullptr_t.
7710 if (ParamType->isNullPtrType()) {
7711 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7712 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7713 CanonicalConverted =
7714 Context.getCanonicalTemplateArgument(SugaredConverted);
7715 return Arg;
7716 }
7717
7718 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7719 case NPV_NotNullPointer:
7720 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7721 << Arg->getType() << ParamType;
7723 return ExprError();
7724
7725 case NPV_Error:
7726 return ExprError();
7727
7728 case NPV_NullPointer:
7729 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7730 SugaredConverted = TemplateArgument(ParamType,
7731 /*isNullPtr=*/true);
7732 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7733 /*isNullPtr=*/true);
7734 return Arg;
7735 }
7736 }
7737
7738 // -- For a non-type template-parameter of type pointer to data
7739 // member, qualification conversions (4.4) are applied.
7740 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7741
7743 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7744 return ExprError();
7745 return Arg;
7746}
7747
7751
7754 const TemplateArgumentLoc &Arg) {
7755 // C++0x [temp.arg.template]p1:
7756 // A template-argument for a template template-parameter shall be
7757 // the name of a class template or an alias template, expressed as an
7758 // id-expression. When the template-argument names a class template, only
7759 // primary class templates are considered when matching the
7760 // template template argument with the corresponding parameter;
7761 // partial specializations are not considered even if their
7762 // parameter lists match that of the template template parameter.
7763 //
7764
7766 unsigned DiagFoundKind = 0;
7767
7768 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7769 switch (TTP->templateParameterKind()) {
7771 DiagFoundKind = 3;
7772 break;
7774 DiagFoundKind = 2;
7775 break;
7776 default:
7777 DiagFoundKind = 1;
7778 break;
7779 }
7780 Kind = TTP->templateParameterKind();
7781 } else if (isa<ConceptDecl>(Template)) {
7783 DiagFoundKind = 3;
7784 } else if (isa<FunctionTemplateDecl>(Template)) {
7786 DiagFoundKind = 0;
7787 } else if (isa<VarTemplateDecl>(Template)) {
7789 DiagFoundKind = 2;
7790 } else if (isa<ClassTemplateDecl>(Template) ||
7794 DiagFoundKind = 1;
7795 } else {
7796 assert(false && "Unexpected Decl");
7797 }
7798
7799 if (Kind == Param->templateParameterKind()) {
7800 return true;
7801 }
7802
7803 unsigned DiagKind = 0;
7804 switch (Param->templateParameterKind()) {
7806 DiagKind = 2;
7807 break;
7809 DiagKind = 1;
7810 break;
7811 default:
7812 DiagKind = 0;
7813 break;
7814 }
7815 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7816 << DiagKind;
7817 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7818 << DiagFoundKind << Template;
7819 return false;
7820}
7821
7822/// Check a template argument against its corresponding
7823/// template template parameter.
7824///
7825/// This routine implements the semantics of C++ [temp.arg.template].
7826/// It returns true if an error occurred, and false otherwise.
7828 TemplateParameterList *Params,
7830 bool PartialOrdering,
7831 bool *StrictPackMatch) {
7833 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7834 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7835 if (!Template) {
7836 // FIXME: Handle AssumedTemplateNames
7837 // Any dependent template name is fine.
7838 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7839 return false;
7840 }
7841
7842 if (Template->isInvalidDecl())
7843 return true;
7844
7846 return true;
7847 }
7848
7849 // C++1z [temp.arg.template]p3: (DR 150)
7850 // A template-argument matches a template template-parameter P when P
7851 // is at least as specialized as the template-argument A.
7853 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7854 PartialOrdering, StrictPackMatch))
7855 return true;
7856 // P2113
7857 // C++20[temp.func.order]p2
7858 // [...] If both deductions succeed, the partial ordering selects the
7859 // more constrained template (if one exists) as determined below.
7860 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7861 Params->getAssociatedConstraints(ParamsAC);
7862 // C++20[temp.arg.template]p3
7863 // [...] In this comparison, if P is unconstrained, the constraints on A
7864 // are not considered.
7865 if (ParamsAC.empty())
7866 return false;
7867
7868 Template->getAssociatedConstraints(TemplateAC);
7869
7870 bool IsParamAtLeastAsConstrained;
7871 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7872 IsParamAtLeastAsConstrained))
7873 return true;
7874 if (!IsParamAtLeastAsConstrained) {
7875 Diag(Arg.getLocation(),
7876 diag::err_template_template_parameter_not_at_least_as_constrained)
7877 << Template << Param << Arg.getSourceRange();
7878 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7879 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7881 TemplateAC);
7882 return true;
7883 }
7884 return false;
7885}
7886
7888 unsigned HereDiagID,
7889 unsigned ExternalDiagID) {
7890 if (Decl.getLocation().isValid())
7891 return S.Diag(Decl.getLocation(), HereDiagID);
7892
7893 SmallString<128> Str;
7894 llvm::raw_svector_ostream Out(Str);
7896 PP.TerseOutput = 1;
7897 Decl.print(Out, PP);
7898 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7899}
7900
7902 std::optional<SourceRange> ParamRange) {
7904 noteLocation(*this, Decl, diag::note_template_decl_here,
7905 diag::note_template_decl_external);
7906 if (ParamRange && ParamRange->isValid()) {
7907 assert(Decl.getLocation().isValid() &&
7908 "Parameter range has location when Decl does not");
7909 DB << *ParamRange;
7910 }
7911}
7912
7914 noteLocation(*this, Decl, diag::note_template_param_here,
7915 diag::note_template_param_external);
7916}
7917
7918/// Given a non-type template argument that refers to a
7919/// declaration and the type of its corresponding non-type template
7920/// parameter, produce an expression that properly refers to that
7921/// declaration.
7923 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7925 // C++ [temp.param]p8:
7926 //
7927 // A non-type template-parameter of type "array of T" or
7928 // "function returning T" is adjusted to be of type "pointer to
7929 // T" or "pointer to function returning T", respectively.
7930 if (ParamType->isArrayType())
7931 ParamType = Context.getArrayDecayedType(ParamType);
7932 else if (ParamType->isFunctionType())
7933 ParamType = Context.getPointerType(ParamType);
7934
7935 // For a NULL non-type template argument, return nullptr casted to the
7936 // parameter's type.
7937 if (Arg.getKind() == TemplateArgument::NullPtr) {
7938 return ImpCastExprToType(
7939 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7940 ParamType,
7941 ParamType->getAs<MemberPointerType>()
7942 ? CK_NullToMemberPointer
7943 : CK_NullToPointer);
7944 }
7945 assert(Arg.getKind() == TemplateArgument::Declaration &&
7946 "Only declaration template arguments permitted here");
7947
7948 ValueDecl *VD = Arg.getAsDecl();
7949
7950 CXXScopeSpec SS;
7951 if (ParamType->isMemberPointerType()) {
7952 // If this is a pointer to member, we need to use a qualified name to
7953 // form a suitable pointer-to-member constant.
7954 assert(VD->getDeclContext()->isRecord() &&
7955 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7957 CanQualType ClassType =
7958 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7959 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7960 SS.MakeTrivial(Context, Qualifier, Loc);
7961 }
7962
7964 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7965 if (RefExpr.isInvalid())
7966 return ExprError();
7967
7968 // For a pointer, the argument declaration is the pointee. Take its address.
7969 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7970 if (ParamType->isPointerType() && !ElemT.isNull() &&
7971 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7972 // Decay an array argument if we want a pointer to its first element.
7973 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7974 if (RefExpr.isInvalid())
7975 return ExprError();
7976 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7977 // For any other pointer, take the address (or form a pointer-to-member).
7978 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7979 if (RefExpr.isInvalid())
7980 return ExprError();
7981 } else if (ParamType->isRecordType()) {
7982 assert(isa<TemplateParamObjectDecl>(VD) &&
7983 "arg for class template param not a template parameter object");
7984 // No conversions apply in this case.
7985 return RefExpr;
7986 } else {
7987 assert(ParamType->isReferenceType() &&
7988 "unexpected type for decl template argument");
7989 if (NonTypeTemplateParmDecl *NTTP =
7990 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7991 QualType TemplateParamType = NTTP->getType();
7992 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7993 if (AT && AT->isDecltypeAuto()) {
7995 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7996 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7997 /*PackIndex=*/std::nullopt,
7998 /*RefParam=*/true, /*Final=*/true);
7999 }
8000 }
8001 }
8002
8003 // At this point we should have the right value category.
8004 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8005 "value kind mismatch for non-type template argument");
8006
8007 // The type of the template parameter can differ from the type of the
8008 // argument in various ways; convert it now if necessary.
8009 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8010 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8011 CastKind CK;
8012 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8013 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
8014 CK = CK_NoOp;
8015 } else if (ParamType->isVoidPointerType() &&
8016 RefExpr.get()->getType()->isPointerType()) {
8017 CK = CK_BitCast;
8018 } else {
8019 // FIXME: Pointers to members can need conversion derived-to-base or
8020 // base-to-derived conversions. We currently don't retain enough
8021 // information to convert properly (we need to track a cast path or
8022 // subobject number in the template argument).
8023 llvm_unreachable(
8024 "unexpected conversion required for non-type template argument");
8025 }
8026 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8027 RefExpr.get()->getValueKind());
8028 }
8029
8030 return RefExpr;
8031}
8032
8033/// Construct a new expression that refers to the given
8034/// integral template argument with the given source-location
8035/// information.
8036///
8037/// This routine takes care of the mapping from an integral template
8038/// argument (which may have any integral type) to the appropriate
8039/// literal value.
8041 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8042 assert(OrigT->isIntegralOrEnumerationType());
8043
8044 // If this is an enum type that we're instantiating, we need to use an integer
8045 // type the same size as the enumerator. We don't want to build an
8046 // IntegerLiteral with enum type. The integer type of an enum type can be of
8047 // any integral type with C++11 enum classes, make sure we create the right
8048 // type of literal for it.
8049 QualType T = OrigT;
8050 if (const auto *ED = OrigT->getAsEnumDecl())
8051 T = ED->getIntegerType();
8052
8053 Expr *E;
8054 if (T->isAnyCharacterType()) {
8056 if (T->isWideCharType())
8058 else if (T->isChar8Type() && S.getLangOpts().Char8)
8060 else if (T->isChar16Type())
8062 else if (T->isChar32Type())
8064 else
8066
8067 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8068 } else if (T->isBooleanType()) {
8069 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8070 } else {
8071 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8072 }
8073
8074 if (OrigT->isEnumeralType()) {
8075 // FIXME: This is a hack. We need a better way to handle substituted
8076 // non-type template parameters.
8077 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8078 nullptr, S.CurFPFeatureOverrides(),
8079 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8080 Loc, Loc);
8081 }
8082
8083 return E;
8084}
8085
8087 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8088 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8089 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8090 ILE->setType(T);
8091 return ILE;
8092 };
8093
8094 switch (Val.getKind()) {
8096 // This cannot occur in a template argument at all.
8097 case APValue::Array:
8098 case APValue::Struct:
8099 case APValue::Union:
8100 // These can only occur within a template parameter object, which is
8101 // represented as a TemplateArgument::Declaration.
8102 llvm_unreachable("unexpected template argument value");
8103
8104 case APValue::Int:
8106 Loc);
8107
8108 case APValue::Float:
8109 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8110 T, Loc);
8111
8114 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8115 Val.getFixedPoint().getScale());
8116
8117 case APValue::ComplexInt: {
8118 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8120 S, ElemT, Val.getComplexIntReal(), Loc),
8122 S, ElemT, Val.getComplexIntImag(), Loc)});
8123 }
8124
8125 case APValue::ComplexFloat: {
8126 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8127 return MakeInitList(
8129 ElemT, Loc),
8131 ElemT, Loc)});
8132 }
8133
8134 case APValue::Vector: {
8135 QualType ElemT = T->castAs<VectorType>()->getElementType();
8137 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8139 S, ElemT, Val.getVectorElt(I), Loc));
8140 return MakeInitList(Elts);
8141 }
8142
8143 case APValue::Matrix:
8144 llvm_unreachable("Matrix template argument expression not yet supported");
8145
8146 case APValue::None:
8148 llvm_unreachable("Unexpected APValue kind.");
8149 case APValue::LValue:
8151 // There isn't necessarily a valid equivalent source-level syntax for
8152 // these; in particular, a naive lowering might violate access control.
8153 // So for now we lower to a ConstantExpr holding the value, wrapped around
8154 // an OpaqueValueExpr.
8155 // FIXME: We should have a better representation for this.
8157 if (T->isReferenceType()) {
8158 T = T->getPointeeType();
8159 VK = VK_LValue;
8160 }
8161 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8162 return ConstantExpr::Create(S.Context, OVE, Val);
8163 }
8164 llvm_unreachable("Unhandled APValue::ValueKind enum");
8165}
8166
8169 SourceLocation Loc) {
8170 switch (Arg.getKind()) {
8176 llvm_unreachable("not a non-type template argument");
8177
8179 return Arg.getAsExpr();
8180
8184 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8185
8188 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8189
8192 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8193 }
8194 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8195}
8196
8197/// Match two template parameters within template parameter lists.
8199 Sema &S, NamedDecl *New,
8200 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8201 const NamedDecl *OldInstFrom, bool Complain,
8203 // Check the actual kind (type, non-type, template).
8204 if (Old->getKind() != New->getKind()) {
8205 if (Complain) {
8206 unsigned NextDiag = diag::err_template_param_different_kind;
8207 if (TemplateArgLoc.isValid()) {
8208 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8209 NextDiag = diag::note_template_param_different_kind;
8210 }
8211 S.Diag(New->getLocation(), NextDiag)
8212 << (Kind != Sema::TPL_TemplateMatch);
8213 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8214 << (Kind != Sema::TPL_TemplateMatch);
8215 }
8216
8217 return false;
8218 }
8219
8220 // Check that both are parameter packs or neither are parameter packs.
8221 // However, if we are matching a template template argument to a
8222 // template template parameter, the template template parameter can have
8223 // a parameter pack where the template template argument does not.
8224 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8225 if (Complain) {
8226 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8227 if (TemplateArgLoc.isValid()) {
8228 S.Diag(TemplateArgLoc,
8229 diag::err_template_arg_template_params_mismatch);
8230 NextDiag = diag::note_template_parameter_pack_non_pack;
8231 }
8232
8233 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8235 : 2;
8236 S.Diag(New->getLocation(), NextDiag)
8237 << ParamKind << New->isParameterPack();
8238 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8239 << ParamKind << Old->isParameterPack();
8240 }
8241
8242 return false;
8243 }
8244 // For non-type template parameters, check the type of the parameter.
8245 if (NonTypeTemplateParmDecl *OldNTTP =
8246 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8248
8249 // If we are matching a template template argument to a template
8250 // template parameter and one of the non-type template parameter types
8251 // is dependent, then we must wait until template instantiation time
8252 // to actually compare the arguments.
8254 (!OldNTTP->getType()->isDependentType() &&
8255 !NewNTTP->getType()->isDependentType())) {
8256 // C++20 [temp.over.link]p6:
8257 // Two [non-type] template-parameters are equivalent [if] they have
8258 // equivalent types ignoring the use of type-constraints for
8259 // placeholder types
8260 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8261 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8262 if (!S.Context.hasSameType(OldType, NewType)) {
8263 if (Complain) {
8264 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8265 if (TemplateArgLoc.isValid()) {
8266 S.Diag(TemplateArgLoc,
8267 diag::err_template_arg_template_params_mismatch);
8268 NextDiag = diag::note_template_nontype_parm_different_type;
8269 }
8270 S.Diag(NewNTTP->getLocation(), NextDiag)
8271 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8272 S.Diag(OldNTTP->getLocation(),
8273 diag::note_template_nontype_parm_prev_declaration)
8274 << OldNTTP->getType();
8275 }
8276 return false;
8277 }
8278 }
8279 }
8280 // For template template parameters, check the template parameter types.
8281 // The template parameter lists of template template
8282 // parameters must agree.
8283 else if (TemplateTemplateParmDecl *OldTTP =
8284 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8286 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8287 return false;
8289 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8290 OldTTP->getTemplateParameters(), Complain,
8293 : Kind),
8294 TemplateArgLoc))
8295 return false;
8296 }
8297
8301 const Expr *NewC = nullptr, *OldC = nullptr;
8302
8304 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8305 NewC = TC->getImmediatelyDeclaredConstraint();
8306 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8307 OldC = TC->getImmediatelyDeclaredConstraint();
8308 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8309 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8310 ->getPlaceholderTypeConstraint())
8311 NewC = E;
8312 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8313 ->getPlaceholderTypeConstraint())
8314 OldC = E;
8315 } else
8316 llvm_unreachable("unexpected template parameter type");
8317
8318 auto Diagnose = [&] {
8319 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8320 diag::err_template_different_type_constraint);
8321 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8322 diag::note_template_prev_declaration) << /*declaration*/0;
8323 };
8324
8325 if (!NewC != !OldC) {
8326 if (Complain)
8327 Diagnose();
8328 return false;
8329 }
8330
8331 if (NewC) {
8332 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8333 NewC)) {
8334 if (Complain)
8335 Diagnose();
8336 return false;
8337 }
8338 }
8339 }
8340
8341 return true;
8342}
8343
8344/// Diagnose a known arity mismatch when comparing template argument
8345/// lists.
8346static
8351 SourceLocation TemplateArgLoc) {
8352 unsigned NextDiag = diag::err_template_param_list_different_arity;
8353 if (TemplateArgLoc.isValid()) {
8354 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8355 NextDiag = diag::note_template_param_list_different_arity;
8356 }
8357 S.Diag(New->getTemplateLoc(), NextDiag)
8358 << (New->size() > Old->size())
8359 << (Kind != Sema::TPL_TemplateMatch)
8360 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8361 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8362 << (Kind != Sema::TPL_TemplateMatch)
8363 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8364}
8365
8368 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8369 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8370 if (Old->size() != New->size()) {
8371 if (Complain)
8373 TemplateArgLoc);
8374
8375 return false;
8376 }
8377
8378 // C++0x [temp.arg.template]p3:
8379 // A template-argument matches a template template-parameter (call it P)
8380 // when each of the template parameters in the template-parameter-list of
8381 // the template-argument's corresponding class template or alias template
8382 // (call it A) matches the corresponding template parameter in the
8383 // template-parameter-list of P. [...]
8384 TemplateParameterList::iterator NewParm = New->begin();
8385 TemplateParameterList::iterator NewParmEnd = New->end();
8386 for (TemplateParameterList::iterator OldParm = Old->begin(),
8387 OldParmEnd = Old->end();
8388 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8389 if (NewParm == NewParmEnd) {
8390 if (Complain)
8392 TemplateArgLoc);
8393 return false;
8394 }
8395 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8396 OldInstFrom, Complain, Kind,
8397 TemplateArgLoc))
8398 return false;
8399 }
8400
8401 // Make sure we exhausted all of the arguments.
8402 if (NewParm != NewParmEnd) {
8403 if (Complain)
8405 TemplateArgLoc);
8406
8407 return false;
8408 }
8409
8410 if (Kind != TPL_TemplateParamsEquivalent) {
8411 const Expr *NewRC = New->getRequiresClause();
8412 const Expr *OldRC = Old->getRequiresClause();
8413
8414 auto Diagnose = [&] {
8415 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8416 diag::err_template_different_requires_clause);
8417 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8418 diag::note_template_prev_declaration) << /*declaration*/0;
8419 };
8420
8421 if (!NewRC != !OldRC) {
8422 if (Complain)
8423 Diagnose();
8424 return false;
8425 }
8426
8427 if (NewRC) {
8428 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8429 NewRC)) {
8430 if (Complain)
8431 Diagnose();
8432 return false;
8433 }
8434 }
8435 }
8436
8437 return true;
8438}
8439
8440bool
8442 if (!S)
8443 return false;
8444
8445 // Find the nearest enclosing declaration scope.
8446 S = S->getDeclParent();
8447
8448 // C++ [temp.pre]p6: [P2096]
8449 // A template, explicit specialization, or partial specialization shall not
8450 // have C linkage.
8451 DeclContext *Ctx = S->getEntity();
8452 if (Ctx && Ctx->isExternCContext()) {
8453 SourceRange Range =
8454 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8455 ? TemplateParams->getParam(0)->getSourceRange()
8456 : TemplateParams->getSourceRange();
8457 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8458 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8459 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8460 return true;
8461 }
8462 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8463
8464 // C++ [temp]p2:
8465 // A template-declaration can appear only as a namespace scope or
8466 // class scope declaration.
8467 // C++ [temp.expl.spec]p3:
8468 // An explicit specialization may be declared in any scope in which the
8469 // corresponding primary template may be defined.
8470 // C++ [temp.class.spec]p6: [P2096]
8471 // A partial specialization may be declared in any scope in which the
8472 // corresponding primary template may be defined.
8473 if (Ctx) {
8474 if (Ctx->isFileContext())
8475 return false;
8476 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8477 // C++ [temp.mem]p2:
8478 // A local class shall not have member templates.
8479 if (RD->isLocalClass())
8480 return Diag(TemplateParams->getTemplateLoc(),
8481 diag::err_template_inside_local_class)
8482 << TemplateParams->getSourceRange();
8483 else
8484 return false;
8485 }
8486 }
8487
8488 return Diag(TemplateParams->getTemplateLoc(),
8489 diag::err_template_outside_namespace_or_class_scope)
8490 << TemplateParams->getSourceRange();
8491}
8492
8493/// Determine what kind of template specialization the given declaration
8494/// is.
8496 if (!D)
8497 return TSK_Undeclared;
8498
8499 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8500 return Record->getTemplateSpecializationKind();
8501 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8502 return Function->getTemplateSpecializationKind();
8503 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8504 return Var->getTemplateSpecializationKind();
8505
8506 return TSK_Undeclared;
8507}
8508
8509/// Check whether a specialization is well-formed in the current
8510/// context.
8511///
8512/// This routine determines whether a template specialization can be declared
8513/// in the current context (C++ [temp.expl.spec]p2).
8514///
8515/// \param S the semantic analysis object for which this check is being
8516/// performed.
8517///
8518/// \param Specialized the entity being specialized or instantiated, which
8519/// may be a kind of template (class template, function template, etc.) or
8520/// a member of a class template (member function, static data member,
8521/// member class).
8522///
8523/// \param PrevDecl the previous declaration of this entity, if any.
8524///
8525/// \param Loc the location of the explicit specialization or instantiation of
8526/// this entity.
8527///
8528/// \param IsPartialSpecialization whether this is a partial specialization of
8529/// a class template.
8530///
8531/// \returns true if there was an error that we cannot recover from, false
8532/// otherwise.
8534 NamedDecl *Specialized,
8535 NamedDecl *PrevDecl,
8536 SourceLocation Loc,
8538 // Keep these "kind" numbers in sync with the %select statements in the
8539 // various diagnostics emitted by this routine.
8540 int EntityKind = 0;
8541 if (isa<ClassTemplateDecl>(Specialized))
8542 EntityKind = IsPartialSpecialization? 1 : 0;
8543 else if (isa<VarTemplateDecl>(Specialized))
8544 EntityKind = IsPartialSpecialization ? 3 : 2;
8545 else if (isa<FunctionTemplateDecl>(Specialized))
8546 EntityKind = 4;
8547 else if (isa<CXXMethodDecl>(Specialized))
8548 EntityKind = 5;
8549 else if (isa<VarDecl>(Specialized))
8550 EntityKind = 6;
8551 else if (isa<RecordDecl>(Specialized))
8552 EntityKind = 7;
8553 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8554 EntityKind = 8;
8555 else {
8556 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8557 << S.getLangOpts().CPlusPlus11;
8558 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8559 return true;
8560 }
8561
8562 // C++ [temp.expl.spec]p2:
8563 // An explicit specialization may be declared in any scope in which
8564 // the corresponding primary template may be defined.
8566 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8567 << Specialized;
8568 return true;
8569 }
8570
8571 // C++ [temp.class.spec]p6:
8572 // A class template partial specialization may be declared in any
8573 // scope in which the primary template may be defined.
8574 DeclContext *SpecializedContext =
8575 Specialized->getDeclContext()->getRedeclContext();
8577
8578 // Make sure that this redeclaration (or definition) occurs in the same
8579 // scope or an enclosing namespace.
8580 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8581 : DC->Equals(SpecializedContext))) {
8582 if (isa<TranslationUnitDecl>(SpecializedContext))
8583 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8584 << EntityKind << Specialized;
8585 else {
8586 auto *ND = cast<NamedDecl>(SpecializedContext);
8587 int Diag = diag::err_template_spec_redecl_out_of_scope;
8588 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8589 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8590 S.Diag(Loc, Diag) << EntityKind << Specialized
8591 << ND << isa<CXXRecordDecl>(ND);
8592 }
8593
8594 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8595
8596 // Don't allow specializing in the wrong class during error recovery.
8597 // Otherwise, things can go horribly wrong.
8598 if (DC->isRecord())
8599 return true;
8600 }
8601
8602 return false;
8603}
8604
8606 if (!E->isTypeDependent())
8607 return SourceLocation();
8608 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8609 Checker.TraverseStmt(E);
8610 if (Checker.MatchLoc.isInvalid())
8611 return E->getSourceRange();
8612 return Checker.MatchLoc;
8613}
8614
8615static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8616 if (!TL.getType()->isDependentType())
8617 return SourceLocation();
8618 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8619 Checker.TraverseTypeLoc(TL);
8620 if (Checker.MatchLoc.isInvalid())
8621 return TL.getSourceRange();
8622 return Checker.MatchLoc;
8623}
8624
8625/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8626/// that checks non-type template partial specialization arguments.
8628 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8629 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8630 bool HasError = false;
8631 for (unsigned I = 0; I != NumArgs; ++I) {
8632 if (Args[I].getKind() == TemplateArgument::Pack) {
8634 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8635 Args[I].pack_size(), IsDefaultArgument))
8636 return true;
8637
8638 continue;
8639 }
8640
8641 if (Args[I].getKind() != TemplateArgument::Expression)
8642 continue;
8643
8644 Expr *ArgExpr = Args[I].getAsExpr();
8645 if (ArgExpr->containsErrors()) {
8646 HasError = true;
8647 continue;
8648 }
8649
8650 // We can have a pack expansion of any of the bullets below.
8651 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8652 ArgExpr = Expansion->getPattern();
8653
8654 // Strip off any implicit casts we added as part of type checking.
8655 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8656 ArgExpr = ICE->getSubExpr();
8657
8658 // C++ [temp.class.spec]p8:
8659 // A non-type argument is non-specialized if it is the name of a
8660 // non-type parameter. All other non-type arguments are
8661 // specialized.
8662 //
8663 // Below, we check the two conditions that only apply to
8664 // specialized non-type arguments, so skip any non-specialized
8665 // arguments.
8666 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8667 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8668 continue;
8669
8670 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8671 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8672 continue;
8673 }
8674
8675 // C++ [temp.class.spec]p9:
8676 // Within the argument list of a class template partial
8677 // specialization, the following restrictions apply:
8678 // -- A partially specialized non-type argument expression
8679 // shall not involve a template parameter of the partial
8680 // specialization except when the argument expression is a
8681 // simple identifier.
8682 // -- The type of a template parameter corresponding to a
8683 // specialized non-type argument shall not be dependent on a
8684 // parameter of the specialization.
8685 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8686 // We implement a compromise between the original rules and DR1315:
8687 // -- A specialized non-type template argument shall not be
8688 // type-dependent and the corresponding template parameter
8689 // shall have a non-dependent type.
8690 SourceRange ParamUseRange =
8691 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8692 if (ParamUseRange.isValid()) {
8693 if (IsDefaultArgument) {
8694 S.Diag(TemplateNameLoc,
8695 diag::err_dependent_non_type_arg_in_partial_spec);
8696 S.Diag(ParamUseRange.getBegin(),
8697 diag::note_dependent_non_type_default_arg_in_partial_spec)
8698 << ParamUseRange;
8699 } else {
8700 S.Diag(ParamUseRange.getBegin(),
8701 diag::err_dependent_non_type_arg_in_partial_spec)
8702 << ParamUseRange;
8703 }
8704 return true;
8705 }
8706
8707 ParamUseRange = findTemplateParameter(
8708 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8709 if (ParamUseRange.isValid()) {
8710 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8711 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8712 << Param->getType();
8714 return true;
8715 }
8716 }
8717
8718 return HasError;
8719}
8720
8722 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8723 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8724 // We have to be conservative when checking a template in a dependent
8725 // context.
8726 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8727 return false;
8728
8729 TemplateParameterList *TemplateParams =
8730 PrimaryTemplate->getTemplateParameters();
8731 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8733 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8734 if (!Param)
8735 continue;
8736
8737 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8738 Param, &TemplateArgs[I],
8739 1, I >= NumExplicit))
8740 return true;
8741 }
8742
8743 return false;
8744}
8745
8747 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8748 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8750 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8751 assert(TUK != TagUseKind::Reference && "References are not specializations");
8752
8753 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8754 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8755 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8756
8757 // Find the class template we're specializing
8758 TemplateName Name = TemplateId.Template.get();
8760 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8761
8762 if (!ClassTemplate) {
8763 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8764 << (Name.getAsTemplateDecl() &&
8766 return true;
8767 }
8768
8769 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8770 auto Message = DSA->getMessage();
8771 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8772 << ClassTemplate << !Message.empty() << Message;
8773 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8774 }
8775
8776 if (S->isTemplateParamScope())
8777 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8778
8779 DeclContext *DC = ClassTemplate->getDeclContext();
8780
8781 bool isMemberSpecialization = false;
8782 bool isPartialSpecialization = false;
8783
8784 if (SS.isSet()) {
8785 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8786 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8787 TemplateNameLoc, &TemplateId,
8788 /*IsMemberSpecialization=*/false))
8789 return true;
8790 }
8791
8792 // Check the validity of the template headers that introduce this
8793 // template.
8794 // FIXME: We probably shouldn't complain about these headers for
8795 // friend declarations.
8796 bool Invalid = false;
8797 TemplateParameterList *TemplateParams =
8799 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8800 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8801 if (Invalid)
8802 return true;
8803
8804 // Check that we can declare a template specialization here.
8805 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8806 return true;
8807
8808 if (TemplateParams && DC->isDependentContext()) {
8809 ContextRAII SavedContext(*this, DC);
8811 return true;
8812 }
8813
8814 if (TemplateParams && TemplateParams->size() > 0) {
8815 isPartialSpecialization = true;
8816
8817 if (TUK == TagUseKind::Friend) {
8818 Diag(KWLoc, diag::err_partial_specialization_friend)
8819 << SourceRange(LAngleLoc, RAngleLoc);
8820 return true;
8821 }
8822
8823 // C++ [temp.class.spec]p10:
8824 // The template parameter list of a specialization shall not
8825 // contain default template argument values.
8826 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8827 Decl *Param = TemplateParams->getParam(I);
8828 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8829 if (TTP->hasDefaultArgument()) {
8830 Diag(TTP->getDefaultArgumentLoc(),
8831 diag::err_default_arg_in_partial_spec);
8832 TTP->removeDefaultArgument();
8833 }
8834 } else if (NonTypeTemplateParmDecl *NTTP
8835 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8836 if (NTTP->hasDefaultArgument()) {
8837 Diag(NTTP->getDefaultArgumentLoc(),
8838 diag::err_default_arg_in_partial_spec)
8839 << NTTP->getDefaultArgument().getSourceRange();
8840 NTTP->removeDefaultArgument();
8841 }
8842 } else {
8844 if (TTP->hasDefaultArgument()) {
8846 diag::err_default_arg_in_partial_spec)
8848 TTP->removeDefaultArgument();
8849 }
8850 }
8851 }
8852 } else if (TemplateParams) {
8853 if (TUK == TagUseKind::Friend)
8854 Diag(KWLoc, diag::err_template_spec_friend)
8856 SourceRange(TemplateParams->getTemplateLoc(),
8857 TemplateParams->getRAngleLoc()))
8858 << SourceRange(LAngleLoc, RAngleLoc);
8859 } else {
8860 assert(TUK == TagUseKind::Friend &&
8861 "should have a 'template<>' for this decl");
8862 }
8863
8864 // Check that the specialization uses the same tag kind as the
8865 // original template.
8867 assert(Kind != TagTypeKind::Enum &&
8868 "Invalid enum tag in class template spec!");
8869 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8870 TUK == TagUseKind::Definition, KWLoc,
8871 ClassTemplate->getIdentifier())) {
8872 Diag(KWLoc, diag::err_use_with_wrong_tag)
8873 << ClassTemplate
8875 ClassTemplate->getTemplatedDecl()->getKindName());
8876 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8877 diag::note_previous_use);
8878 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8879 }
8880
8881 // Translate the parser's template argument list in our AST format.
8882 TemplateArgumentListInfo TemplateArgs =
8883 makeTemplateArgumentListInfo(*this, TemplateId);
8884
8885 // Check for unexpanded parameter packs in any of the template arguments.
8886 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8887 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8888 isPartialSpecialization
8891 return true;
8892
8893 // Check that the template argument list is well-formed for this
8894 // template.
8896 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8897 /*DefaultArgs=*/{},
8898 /*PartialTemplateArgs=*/false, CTAI,
8899 /*UpdateArgsWithConversions=*/true))
8900 return true;
8901
8902 // Find the class template (partial) specialization declaration that
8903 // corresponds to these arguments.
8904 if (isPartialSpecialization) {
8906 TemplateArgs.size(),
8907 CTAI.CanonicalConverted))
8908 return true;
8909
8910 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8911 // also do it during instantiation.
8912 if (!Name.isDependent() &&
8913 !TemplateSpecializationType::anyDependentTemplateArguments(
8914 TemplateArgs, CTAI.CanonicalConverted)) {
8915 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8916 << ClassTemplate->getDeclName();
8917 isPartialSpecialization = false;
8918 Invalid = true;
8919 }
8920 }
8921
8922 void *InsertPos = nullptr;
8923 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8924
8925 if (isPartialSpecialization)
8926 PrevDecl = ClassTemplate->findPartialSpecialization(
8927 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8928 else
8929 PrevDecl =
8930 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8931
8933
8934 // Check whether we can declare a class template specialization in
8935 // the current scope.
8936 if (TUK != TagUseKind::Friend &&
8938 TemplateNameLoc,
8939 isPartialSpecialization))
8940 return true;
8941
8942 if (!isPartialSpecialization) {
8943 // Create a new class template specialization declaration node for
8944 // this explicit specialization or friend declaration.
8946 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8947 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8948 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8950 if (TemplateParameterLists.size() > 0) {
8951 Specialization->setTemplateParameterListsInfo(Context,
8952 TemplateParameterLists);
8953 }
8954
8955 if (!PrevDecl)
8956 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8957 } else {
8959 Context.getCanonicalTemplateSpecializationType(
8961 TemplateName(ClassTemplate->getCanonicalDecl()),
8962 CTAI.CanonicalConverted));
8963 if (Context.hasSameType(
8964 CanonType,
8965 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8966 (!Context.getLangOpts().CPlusPlus20 ||
8967 !TemplateParams->hasAssociatedConstraints())) {
8968 // C++ [temp.class.spec]p9b3:
8969 //
8970 // -- The argument list of the specialization shall not be identical
8971 // to the implicit argument list of the primary template.
8972 //
8973 // This rule has since been removed, because it's redundant given DR1495,
8974 // but we keep it because it produces better diagnostics and recovery.
8975 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8976 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8977 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8978 return CheckClassTemplate(
8979 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8980 TemplateNameLoc, Attr, TemplateParams, AS_none,
8981 /*ModulePrivateLoc=*/SourceLocation(),
8982 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8983 TemplateParameterLists.data());
8984 }
8985
8986 // Create a new class template partial specialization declaration node.
8988 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8991 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8992 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8993 Partial->setTemplateArgsAsWritten(TemplateArgs);
8994 SetNestedNameSpecifier(*this, Partial, SS);
8995 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8997 Context, TemplateParameterLists.drop_back(1));
8998 }
8999
9000 if (!PrevPartial)
9001 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9002 Specialization = Partial;
9003
9004 // If we are providing an explicit specialization of a member class
9005 // template specialization, make a note of that.
9006 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9007 PrevPartial->setMemberSpecialization();
9008
9010 }
9011
9012 // C++ [temp.expl.spec]p6:
9013 // If a template, a member template or the member of a class template is
9014 // explicitly specialized then that specialization shall be declared
9015 // before the first use of that specialization that would cause an implicit
9016 // instantiation to take place, in every translation unit in which such a
9017 // use occurs; no diagnostic is required.
9018 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9019 bool Okay = false;
9020 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9021 // Is there any previous explicit specialization declaration?
9023 Okay = true;
9024 break;
9025 }
9026 }
9027
9028 if (!Okay) {
9029 SourceRange Range(TemplateNameLoc, RAngleLoc);
9030 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9031 << Context.getCanonicalTagType(Specialization) << Range;
9032
9033 Diag(PrevDecl->getPointOfInstantiation(),
9034 diag::note_instantiation_required_here)
9035 << (PrevDecl->getTemplateSpecializationKind()
9037 return true;
9038 }
9039 }
9040
9041 // If this is not a friend, note that this is an explicit specialization.
9042 if (TUK != TagUseKind::Friend)
9043 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9044
9045 // Check that this isn't a redefinition of this specialization.
9046 if (TUK == TagUseKind::Definition) {
9047 RecordDecl *Def = Specialization->getDefinition();
9048 NamedDecl *Hidden = nullptr;
9049 bool HiddenDefVisible = false;
9050 if (Def && SkipBody &&
9051 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9052 SkipBody->ShouldSkip = true;
9053 SkipBody->Previous = Def;
9054 if (!HiddenDefVisible && Hidden)
9056 } else if (Def) {
9057 SourceRange Range(TemplateNameLoc, RAngleLoc);
9058 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9059 Diag(Def->getLocation(), diag::note_previous_definition);
9060 Specialization->setInvalidDecl();
9061 return true;
9062 }
9063 }
9064
9067
9068 // Add alignment attributes if necessary; these attributes are checked when
9069 // the ASTContext lays out the structure.
9070 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9071 if (LangOpts.HLSL)
9072 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9075 }
9076
9077 if (ModulePrivateLoc.isValid())
9078 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9079 << (isPartialSpecialization? 1 : 0)
9080 << FixItHint::CreateRemoval(ModulePrivateLoc);
9081
9082 // C++ [temp.expl.spec]p9:
9083 // A template explicit specialization is in the scope of the
9084 // namespace in which the template was defined.
9085 //
9086 // We actually implement this paragraph where we set the semantic
9087 // context (in the creation of the ClassTemplateSpecializationDecl),
9088 // but we also maintain the lexical context where the actual
9089 // definition occurs.
9090 Specialization->setLexicalDeclContext(CurContext);
9091
9092 // We may be starting the definition of this specialization.
9093 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9094 Specialization->startDefinition();
9095
9096 if (TUK == TagUseKind::Friend) {
9097 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9098 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9099 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9101 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9102 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9103
9104 // Build the fully-sugared type for this class template
9105 // specialization as the user wrote in the specialization
9106 // itself. This means that we'll pretty-print the type retrieved
9107 // from the specialization's declaration the way that the user
9108 // actually wrote the specialization, rather than formatting the
9109 // name based on the "canonical" representation used to store the
9110 // template arguments in the specialization.
9112 TemplateNameLoc,
9113 WrittenTy,
9114 /*FIXME:*/KWLoc);
9115 Friend->setAccess(AS_public);
9116 CurContext->addDecl(Friend);
9117 } else {
9118 // Add the specialization into its lexical context, so that it can
9119 // be seen when iterating through the list of declarations in that
9120 // context. However, specializations are not found by name lookup.
9121 CurContext->addDecl(Specialization);
9122 }
9123
9124 if (SkipBody && SkipBody->ShouldSkip)
9125 return SkipBody->Previous;
9126
9127 Specialization->setInvalidDecl(Invalid);
9129 return Specialization;
9130}
9131
9133 MultiTemplateParamsArg TemplateParameterLists,
9134 Declarator &D) {
9135 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9136 ActOnDocumentableDecl(NewDecl);
9137 return NewDecl;
9138}
9139
9141 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9142 const IdentifierInfo *Name, SourceLocation NameLoc) {
9143 DeclContext *DC = CurContext;
9144
9145 if (!DC->getRedeclContext()->isFileContext()) {
9146 Diag(NameLoc,
9147 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9148 return nullptr;
9149 }
9150
9151 if (TemplateParameterLists.size() > 1) {
9152 Diag(NameLoc, diag::err_concept_extra_headers);
9153 return nullptr;
9154 }
9155
9156 TemplateParameterList *Params = TemplateParameterLists.front();
9157
9158 if (Params->size() == 0) {
9159 Diag(NameLoc, diag::err_concept_no_parameters);
9160 return nullptr;
9161 }
9162
9163 // Ensure that the parameter pack, if present, is the last parameter in the
9164 // template.
9165 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9166 ParamEnd = Params->end();
9167 ParamIt != ParamEnd; ++ParamIt) {
9168 Decl const *Param = *ParamIt;
9169 if (Param->isParameterPack()) {
9170 if (++ParamIt == ParamEnd)
9171 break;
9172 Diag(Param->getLocation(),
9173 diag::err_template_param_pack_must_be_last_template_parameter);
9174 return nullptr;
9175 }
9176 }
9177
9178 ConceptDecl *NewDecl =
9179 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9180
9181 if (NewDecl->hasAssociatedConstraints()) {
9182 // C++2a [temp.concept]p4:
9183 // A concept shall not have associated constraints.
9184 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9185 NewDecl->setInvalidDecl();
9186 }
9187
9188 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9189 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9191 LookupName(Previous, S);
9192 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9193 /*AllowInlineNamespace*/ false);
9194
9195 // We cannot properly handle redeclarations until we parse the constraint
9196 // expression, so only inject the name if we are sure we are not redeclaring a
9197 // symbol
9198 if (Previous.empty())
9199 PushOnScopeChains(NewDecl, S, true);
9200
9201 return NewDecl;
9202}
9203
9205 bool Found = false;
9206 LookupResult::Filter F = R.makeFilter();
9207 while (F.hasNext()) {
9208 NamedDecl *D = F.next();
9209 if (D == C) {
9210 F.erase();
9211 Found = true;
9212 break;
9213 }
9214 }
9215 F.done();
9216 return Found;
9217}
9218
9221 Expr *ConstraintExpr,
9222 const ParsedAttributesView &Attrs) {
9223 assert(!C->hasDefinition() && "Concept already defined");
9224 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9225 C->setInvalidDecl();
9226 return nullptr;
9227 }
9228 C->setDefinition(ConstraintExpr);
9229 ProcessDeclAttributeList(S, C, Attrs);
9230
9231 // Check for conflicting previous declaration.
9232 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9233 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9235 LookupName(Previous, S);
9236 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9237 /*AllowInlineNamespace*/ false);
9238 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9239 bool AddToScope = true;
9240 CheckConceptRedefinition(C, Previous, AddToScope);
9241
9243 if (!WasAlreadyAdded && AddToScope)
9244 PushOnScopeChains(C, S);
9245
9246 return C;
9247}
9248
9250 LookupResult &Previous, bool &AddToScope) {
9251 AddToScope = true;
9252
9253 if (Previous.empty())
9254 return;
9255
9256 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9257 if (!OldConcept) {
9258 auto *Old = Previous.getRepresentativeDecl();
9259 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9260 << NewDecl->getDeclName();
9261 notePreviousDefinition(Old, NewDecl->getLocation());
9262 AddToScope = false;
9263 return;
9264 }
9265 // Check if we can merge with a concept declaration.
9266 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9267 if (!IsSame) {
9268 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9269 << NewDecl->getDeclName();
9270 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9271 AddToScope = false;
9272 return;
9273 }
9274 if (hasReachableDefinition(OldConcept) &&
9275 IsRedefinitionInModule(NewDecl, OldConcept)) {
9276 Diag(NewDecl->getLocation(), diag::err_redefinition)
9277 << NewDecl->getDeclName();
9278 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9279 AddToScope = false;
9280 return;
9281 }
9282 if (!Previous.isSingleResult()) {
9283 // FIXME: we should produce an error in case of ambig and failed lookups.
9284 // Other decls (e.g. namespaces) also have this shortcoming.
9285 return;
9286 }
9287 // We unwrap canonical decl late to check for module visibility.
9288 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9289}
9290
9292 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9293 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9294 Diag(Loc, diag::err_recursive_concept) << CE;
9295 Diag(CE->getLocation(), diag::note_declared_at);
9296 return true;
9297 }
9298 // Concept template parameters don't have a definition and can't
9299 // be defined recursively.
9300 return false;
9301}
9302
9303/// \brief Strips various properties off an implicit instantiation
9304/// that has just been explicitly specialized.
9305static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9306 if (MinGW || (isa<FunctionDecl>(D) &&
9307 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9308 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9309
9310 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9311 FD->setInlineSpecified(false);
9312}
9313
9314/// Compute the diagnostic location for an explicit instantiation
9315// declaration or definition.
9317 NamedDecl* D, SourceLocation PointOfInstantiation) {
9318 // Explicit instantiations following a specialization have no effect and
9319 // hence no PointOfInstantiation. In that case, walk decl backwards
9320 // until a valid name loc is found.
9321 SourceLocation PrevDiagLoc = PointOfInstantiation;
9322 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9323 Prev = Prev->getPreviousDecl()) {
9324 PrevDiagLoc = Prev->getLocation();
9325 }
9326 assert(PrevDiagLoc.isValid() &&
9327 "Explicit instantiation without point of instantiation?");
9328 return PrevDiagLoc;
9329}
9330
9331bool
9334 NamedDecl *PrevDecl,
9336 SourceLocation PrevPointOfInstantiation,
9337 bool &HasNoEffect) {
9338 HasNoEffect = false;
9339
9340 switch (NewTSK) {
9341 case TSK_Undeclared:
9343 assert(
9344 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9345 "previous declaration must be implicit!");
9346 return false;
9347
9349 switch (PrevTSK) {
9350 case TSK_Undeclared:
9352 // Okay, we're just specializing something that is either already
9353 // explicitly specialized or has merely been mentioned without any
9354 // instantiation.
9355 return false;
9356
9358 if (PrevPointOfInstantiation.isInvalid()) {
9359 // The declaration itself has not actually been instantiated, so it is
9360 // still okay to specialize it.
9362 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9363 return false;
9364 }
9365 // Fall through
9366 [[fallthrough]];
9367
9370 assert((PrevTSK == TSK_ImplicitInstantiation ||
9371 PrevPointOfInstantiation.isValid()) &&
9372 "Explicit instantiation without point of instantiation?");
9373
9374 // C++ [temp.expl.spec]p6:
9375 // If a template, a member template or the member of a class template
9376 // is explicitly specialized then that specialization shall be declared
9377 // before the first use of that specialization that would cause an
9378 // implicit instantiation to take place, in every translation unit in
9379 // which such a use occurs; no diagnostic is required.
9380 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9381 // Is there any previous explicit specialization declaration?
9383 return false;
9384 }
9385
9386 Diag(NewLoc, diag::err_specialization_after_instantiation)
9387 << PrevDecl;
9388 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9389 << (PrevTSK != TSK_ImplicitInstantiation);
9390
9391 return true;
9392 }
9393 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9394
9396 switch (PrevTSK) {
9398 // This explicit instantiation declaration is redundant (that's okay).
9399 HasNoEffect = true;
9400 return false;
9401
9402 case TSK_Undeclared:
9404 // We're explicitly instantiating something that may have already been
9405 // implicitly instantiated; that's fine.
9406 return false;
9407
9409 // C++0x [temp.explicit]p4:
9410 // For a given set of template parameters, if an explicit instantiation
9411 // of a template appears after a declaration of an explicit
9412 // specialization for that template, the explicit instantiation has no
9413 // effect.
9414 HasNoEffect = true;
9415 return false;
9416
9418 // C++0x [temp.explicit]p10:
9419 // If an entity is the subject of both an explicit instantiation
9420 // declaration and an explicit instantiation definition in the same
9421 // translation unit, the definition shall follow the declaration.
9422 Diag(NewLoc,
9423 diag::err_explicit_instantiation_declaration_after_definition);
9424
9425 // Explicit instantiations following a specialization have no effect and
9426 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9427 // until a valid name loc is found.
9428 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9429 diag::note_explicit_instantiation_definition_here);
9430 HasNoEffect = true;
9431 return false;
9432 }
9433 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9434
9436 switch (PrevTSK) {
9437 case TSK_Undeclared:
9439 // We're explicitly instantiating something that may have already been
9440 // implicitly instantiated; that's fine.
9441 return false;
9442
9444 // C++ DR 259, C++0x [temp.explicit]p4:
9445 // For a given set of template parameters, if an explicit
9446 // instantiation of a template appears after a declaration of
9447 // an explicit specialization for that template, the explicit
9448 // instantiation has no effect.
9449 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9450 << PrevDecl;
9451 Diag(PrevDecl->getLocation(),
9452 diag::note_previous_template_specialization);
9453 HasNoEffect = true;
9454 return false;
9455
9457 // We're explicitly instantiating a definition for something for which we
9458 // were previously asked to suppress instantiations. That's fine.
9459
9460 // C++0x [temp.explicit]p4:
9461 // For a given set of template parameters, if an explicit instantiation
9462 // of a template appears after a declaration of an explicit
9463 // specialization for that template, the explicit instantiation has no
9464 // effect.
9465 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9466 // Is there any previous explicit specialization declaration?
9468 HasNoEffect = true;
9469 break;
9470 }
9471 }
9472
9473 return false;
9474
9476 // C++0x [temp.spec]p5:
9477 // For a given template and a given set of template-arguments,
9478 // - an explicit instantiation definition shall appear at most once
9479 // in a program,
9480
9481 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9482 Diag(NewLoc, (getLangOpts().MSVCCompat)
9483 ? diag::ext_explicit_instantiation_duplicate
9484 : diag::err_explicit_instantiation_duplicate)
9485 << PrevDecl;
9486 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9487 diag::note_previous_explicit_instantiation);
9488 HasNoEffect = true;
9489 return false;
9490 }
9491 }
9492
9493 llvm_unreachable("Missing specialization/instantiation case?");
9494}
9495
9497 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9499 // Remove anything from Previous that isn't a function template in
9500 // the correct context.
9501 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9502 LookupResult::Filter F = Previous.makeFilter();
9503 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9504 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9505 while (F.hasNext()) {
9506 NamedDecl *D = F.next()->getUnderlyingDecl();
9507 if (!isa<FunctionTemplateDecl>(D)) {
9508 F.erase();
9509 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9510 continue;
9511 }
9512
9513 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9515 F.erase();
9516 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9517 continue;
9518 }
9519 }
9520 F.done();
9521
9522 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9523 if (Previous.empty()) {
9524 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9525 << IsFriend;
9526 for (auto &P : DiscardedCandidates)
9527 Diag(P.second->getLocation(),
9528 diag::note_dependent_function_template_spec_discard_reason)
9529 << P.first << IsFriend;
9530 return true;
9531 }
9532
9534 ExplicitTemplateArgs);
9535 return false;
9536}
9537
9539 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9540 LookupResult &Previous, bool QualifiedFriend) {
9541 // The set of function template specializations that could match this
9542 // explicit function template specialization.
9543 UnresolvedSet<8> Candidates;
9544 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9545 /*ForTakingAddress=*/false);
9546
9547 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9548 ConvertedTemplateArgs;
9549
9550 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9551 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9552 I != E; ++I) {
9553 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9554 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9555 // Only consider templates found within the same semantic lookup scope as
9556 // FD.
9557 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9559 continue;
9560
9561 QualType FT = FD->getType();
9562 // C++11 [dcl.constexpr]p8:
9563 // A constexpr specifier for a non-static member function that is not
9564 // a constructor declares that member function to be const.
9565 //
9566 // When matching a constexpr member function template specialization
9567 // against the primary template, we don't yet know whether the
9568 // specialization has an implicit 'const' (because we don't know whether
9569 // it will be a static member function until we know which template it
9570 // specializes). This rule was removed in C++14.
9571 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9572 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9574 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9575 if (OldMD && OldMD->isConst()) {
9576 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9578 EPI.TypeQuals.addConst();
9579 FT = Context.getFunctionType(FPT->getReturnType(),
9580 FPT->getParamTypes(), EPI);
9581 }
9582 }
9583
9585 if (ExplicitTemplateArgs)
9586 Args = *ExplicitTemplateArgs;
9587
9588 // C++ [temp.expl.spec]p11:
9589 // A trailing template-argument can be left unspecified in the
9590 // template-id naming an explicit function template specialization
9591 // provided it can be deduced from the function argument type.
9592 // Perform template argument deduction to determine whether we may be
9593 // specializing this template.
9594 // FIXME: It is somewhat wasteful to build
9595 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9596 FunctionDecl *Specialization = nullptr;
9598 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9599 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9601 // Template argument deduction failed; record why it failed, so
9602 // that we can provide nifty diagnostics.
9603 FailedCandidates.addCandidate().set(
9604 I.getPair(), FunTmpl->getTemplatedDecl(),
9605 MakeDeductionFailureInfo(Context, TDK, Info));
9606 (void)TDK;
9607 continue;
9608 }
9609
9610 // Target attributes are part of the cuda function signature, so
9611 // the deduced template's cuda target must match that of the
9612 // specialization. Given that C++ template deduction does not
9613 // take target attributes into account, we reject candidates
9614 // here that have a different target.
9615 if (LangOpts.CUDA &&
9616 CUDA().IdentifyTarget(Specialization,
9617 /* IgnoreImplicitHDAttr = */ true) !=
9618 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9619 FailedCandidates.addCandidate().set(
9620 I.getPair(), FunTmpl->getTemplatedDecl(),
9623 continue;
9624 }
9625
9626 // Record this candidate.
9627 if (ExplicitTemplateArgs)
9628 ConvertedTemplateArgs[Specialization] = std::move(Args);
9629 Candidates.addDecl(Specialization, I.getAccess());
9630 }
9631 }
9632
9633 // For a qualified friend declaration (with no explicit marker to indicate
9634 // that a template specialization was intended), note all (template and
9635 // non-template) candidates.
9636 if (QualifiedFriend && Candidates.empty()) {
9637 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9638 << FD->getDeclName() << FDLookupContext;
9639 // FIXME: We should form a single candidate list and diagnose all
9640 // candidates at once, to get proper sorting and limiting.
9641 for (auto *OldND : Previous) {
9642 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9643 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9644 }
9645 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9646 return true;
9647 }
9648
9649 // Find the most specialized function template.
9651 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9652 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9653 PDiag(diag::err_function_template_spec_ambiguous)
9654 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9655 PDiag(diag::note_function_template_spec_matched));
9656
9657 if (Result == Candidates.end())
9658 return true;
9659
9660 // Ignore access information; it doesn't figure into redeclaration checking.
9662
9663 if (const auto *PT = Specialization->getPrimaryTemplate();
9664 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9665 auto Message = DSA->getMessage();
9666 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9667 << PT << !Message.empty() << Message;
9668 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9669 }
9670
9671 // C++23 [except.spec]p13:
9672 // An exception specification is considered to be needed when:
9673 // - [...]
9674 // - the exception specification is compared to that of another declaration
9675 // (e.g., an explicit specialization or an overriding virtual function);
9676 // - [...]
9677 //
9678 // The exception specification of a defaulted function is evaluated as
9679 // described above only when needed; similarly, the noexcept-specifier of a
9680 // specialization of a function template or member function of a class
9681 // template is instantiated only when needed.
9682 //
9683 // The standard doesn't specify what the "comparison with another declaration"
9684 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9685 // not state which properties of an explicit specialization must match the
9686 // primary template.
9687 //
9688 // We assume that an explicit specialization must correspond with (per
9689 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9690 // the declaration produced by substitution into the function template.
9691 //
9692 // Since the determination whether two function declarations correspond does
9693 // not consider exception specification, we only need to instantiate it once
9694 // we determine the primary template when comparing types per
9695 // [basic.link]p11.1.
9696 auto *SpecializationFPT =
9697 Specialization->getType()->castAs<FunctionProtoType>();
9698 // If the function has a dependent exception specification, resolve it after
9699 // we have selected the primary template so we can check whether it matches.
9700 if (getLangOpts().CPlusPlus17 &&
9701 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9702 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9703 return true;
9704
9706 = Specialization->getTemplateSpecializationInfo();
9707 assert(SpecInfo && "Function template specialization info missing?");
9708
9709 // Note: do not overwrite location info if previous template
9710 // specialization kind was explicit.
9712 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9713 Specialization->setLocation(FD->getLocation());
9714 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9715 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9716 // function can differ from the template declaration with respect to
9717 // the constexpr specifier.
9718 // FIXME: We need an update record for this AST mutation.
9719 // FIXME: What if there are multiple such prior declarations (for instance,
9720 // from different modules)?
9721 Specialization->setConstexprKind(FD->getConstexprKind());
9722 }
9723
9724 // FIXME: Check if the prior specialization has a point of instantiation.
9725 // If so, we have run afoul of .
9726
9727 // If this is a friend declaration, then we're not really declaring
9728 // an explicit specialization.
9729 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9730
9731 // Check the scope of this explicit specialization.
9732 if (!isFriend &&
9734 Specialization->getPrimaryTemplate(),
9736 false))
9737 return true;
9738
9739 // C++ [temp.expl.spec]p6:
9740 // If a template, a member template or the member of a class template is
9741 // explicitly specialized then that specialization shall be declared
9742 // before the first use of that specialization that would cause an implicit
9743 // instantiation to take place, in every translation unit in which such a
9744 // use occurs; no diagnostic is required.
9745 bool HasNoEffect = false;
9746 if (!isFriend &&
9751 SpecInfo->getPointOfInstantiation(),
9752 HasNoEffect))
9753 return true;
9754
9755 // Mark the prior declaration as an explicit specialization, so that later
9756 // clients know that this is an explicit specialization.
9757 // A dependent friend specialization which has a definition should be treated
9758 // as explicit specialization, despite being invalid.
9759 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9760 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9761 // Since explicit specializations do not inherit '=delete' from their
9762 // primary function template - check if the 'specialization' that was
9763 // implicitly generated (during template argument deduction for partial
9764 // ordering) from the most specialized of all the function templates that
9765 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9766 // first check that it was implicitly generated during template argument
9767 // deduction by making sure it wasn't referenced, and then reset the deleted
9768 // flag to not-deleted, so that we can inherit that information from 'FD'.
9769 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9770 !Specialization->getCanonicalDecl()->isReferenced()) {
9771 // FIXME: This assert will not hold in the presence of modules.
9772 assert(
9773 Specialization->getCanonicalDecl() == Specialization &&
9774 "This must be the only existing declaration of this specialization");
9775 // FIXME: We need an update record for this AST mutation.
9776 Specialization->setDeletedAsWritten(false);
9777 }
9778 // FIXME: We need an update record for this AST mutation.
9781 }
9782
9783 // Turn the given function declaration into a function template
9784 // specialization, with the template arguments from the previous
9785 // specialization.
9786 // Take copies of (semantic and syntactic) template argument lists.
9788 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9789 FD->setFunctionTemplateSpecialization(
9790 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9792 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9793
9794 // A function template specialization inherits the target attributes
9795 // of its template. (We require the attributes explicitly in the
9796 // code to match, but a template may have implicit attributes by
9797 // virtue e.g. of being constexpr, and it passes these implicit
9798 // attributes on to its specializations.)
9799 if (LangOpts.CUDA)
9800 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9801
9802 // The "previous declaration" for this function template specialization is
9803 // the prior function template specialization.
9804 Previous.clear();
9805 Previous.addDecl(Specialization);
9806 return false;
9807}
9808
9809bool
9811 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9812 "Only for non-template members");
9813
9814 // Try to find the member we are instantiating.
9815 NamedDecl *FoundInstantiation = nullptr;
9816 NamedDecl *Instantiation = nullptr;
9817 NamedDecl *InstantiatedFrom = nullptr;
9818 MemberSpecializationInfo *MSInfo = nullptr;
9819
9820 if (Previous.empty()) {
9821 // Nowhere to look anyway.
9822 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9823 UnresolvedSet<8> Candidates;
9824 for (NamedDecl *Candidate : Previous) {
9825 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9826 // Ignore any candidates that aren't member functions.
9827 if (!Method)
9828 continue;
9829
9830 QualType Adjusted = Function->getType();
9831 if (!hasExplicitCallingConv(Adjusted))
9832 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9833 // Ignore any candidates with the wrong type.
9834 // This doesn't handle deduced return types, but both function
9835 // declarations should be undeduced at this point.
9836 // FIXME: The exception specification should probably be ignored when
9837 // comparing the types.
9838 if (!Context.hasSameType(Adjusted, Method->getType()))
9839 continue;
9840
9841 // Ignore any candidates with unsatisfied constraints.
9842 if (ConstraintSatisfaction Satisfaction;
9843 Method->getTrailingRequiresClause() &&
9844 (CheckFunctionConstraints(Method, Satisfaction,
9845 /*UsageLoc=*/Member->getLocation(),
9846 /*ForOverloadResolution=*/true) ||
9847 !Satisfaction.IsSatisfied))
9848 continue;
9849
9850 Candidates.addDecl(Candidate);
9851 }
9852
9853 // If we have no viable candidates left after filtering, we are done.
9854 if (Candidates.empty())
9855 return false;
9856
9857 // Find the function that is more constrained than every other function it
9858 // has been compared to.
9859 UnresolvedSetIterator Best = Candidates.begin();
9860 CXXMethodDecl *BestMethod = nullptr;
9861 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9862 I != E; ++I) {
9863 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9864 if (I == Best ||
9865 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9866 Best = I;
9867 BestMethod = Method;
9868 }
9869 }
9870
9871 FoundInstantiation = *Best;
9872 Instantiation = BestMethod;
9873 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9874 MSInfo = BestMethod->getMemberSpecializationInfo();
9875
9876 // Make sure the best candidate is more constrained than all of the others.
9877 bool Ambiguous = false;
9878 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9879 I != E; ++I) {
9880 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9881 if (I != Best &&
9882 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9883 Ambiguous = true;
9884 break;
9885 }
9886 }
9887
9888 if (Ambiguous) {
9889 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9890 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9891 for (NamedDecl *Candidate : Candidates) {
9892 Candidate = Candidate->getUnderlyingDecl();
9893 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9894 << Candidate;
9895 }
9896 return true;
9897 }
9898 } else if (isa<VarDecl>(Member)) {
9899 VarDecl *PrevVar;
9900 if (Previous.isSingleResult() &&
9901 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9902 if (PrevVar->isStaticDataMember()) {
9903 FoundInstantiation = Previous.getRepresentativeDecl();
9904 Instantiation = PrevVar;
9905 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9906 MSInfo = PrevVar->getMemberSpecializationInfo();
9907 }
9908 } else if (isa<RecordDecl>(Member)) {
9909 CXXRecordDecl *PrevRecord;
9910 if (Previous.isSingleResult() &&
9911 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9912 FoundInstantiation = Previous.getRepresentativeDecl();
9913 Instantiation = PrevRecord;
9914 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9915 MSInfo = PrevRecord->getMemberSpecializationInfo();
9916 }
9917 } else if (isa<EnumDecl>(Member)) {
9918 EnumDecl *PrevEnum;
9919 if (Previous.isSingleResult() &&
9920 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9921 FoundInstantiation = Previous.getRepresentativeDecl();
9922 Instantiation = PrevEnum;
9923 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9924 MSInfo = PrevEnum->getMemberSpecializationInfo();
9925 }
9926 }
9927
9928 if (!Instantiation) {
9929 // There is no previous declaration that matches. Since member
9930 // specializations are always out-of-line, the caller will complain about
9931 // this mismatch later.
9932 return false;
9933 }
9934
9935 // A member specialization in a friend declaration isn't really declaring
9936 // an explicit specialization, just identifying a specific (possibly implicit)
9937 // specialization. Don't change the template specialization kind.
9938 //
9939 // FIXME: Is this really valid? Other compilers reject.
9940 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9941 // Preserve instantiation information.
9942 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9943 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9944 cast<CXXMethodDecl>(InstantiatedFrom),
9946 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9947 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9948 cast<CXXRecordDecl>(InstantiatedFrom),
9950 }
9951
9952 Previous.clear();
9953 Previous.addDecl(FoundInstantiation);
9954 return false;
9955 }
9956
9957 // Make sure that this is a specialization of a member.
9958 if (!InstantiatedFrom) {
9959 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9960 << Member;
9961 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9962 return true;
9963 }
9964
9965 // C++ [temp.expl.spec]p6:
9966 // If a template, a member template or the member of a class template is
9967 // explicitly specialized then that specialization shall be declared
9968 // before the first use of that specialization that would cause an implicit
9969 // instantiation to take place, in every translation unit in which such a
9970 // use occurs; no diagnostic is required.
9971 assert(MSInfo && "Member specialization info missing?");
9972
9973 bool HasNoEffect = false;
9976 Instantiation,
9978 MSInfo->getPointOfInstantiation(),
9979 HasNoEffect))
9980 return true;
9981
9982 // Check the scope of this explicit specialization.
9984 InstantiatedFrom,
9985 Instantiation, Member->getLocation(),
9986 false))
9987 return true;
9988
9989 // Note that this member specialization is an "instantiation of" the
9990 // corresponding member of the original template.
9991 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9992 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9993 if (InstantiationFunction->getTemplateSpecializationKind() ==
9995 // Explicit specializations of member functions of class templates do not
9996 // inherit '=delete' from the member function they are specializing.
9997 if (InstantiationFunction->isDeleted()) {
9998 // FIXME: This assert will not hold in the presence of modules.
9999 assert(InstantiationFunction->getCanonicalDecl() ==
10000 InstantiationFunction);
10001 // FIXME: We need an update record for this AST mutation.
10002 InstantiationFunction->setDeletedAsWritten(false);
10003 }
10004 }
10005
10006 MemberFunction->setInstantiationOfMemberFunction(
10008 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10009 MemberVar->setInstantiationOfStaticDataMember(
10010 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10011 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10012 MemberClass->setInstantiationOfMemberClass(
10014 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10015 MemberEnum->setInstantiationOfMemberEnum(
10016 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10017 } else {
10018 llvm_unreachable("unknown member specialization kind");
10019 }
10020
10021 // Save the caller the trouble of having to figure out which declaration
10022 // this specialization matches.
10023 Previous.clear();
10024 Previous.addDecl(FoundInstantiation);
10025 return false;
10026}
10027
10028/// Complete the explicit specialization of a member of a class template by
10029/// updating the instantiated member to be marked as an explicit specialization.
10030///
10031/// \param OrigD The member declaration instantiated from the template.
10032/// \param Loc The location of the explicit specialization of the member.
10033template<typename DeclT>
10034static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10035 SourceLocation Loc) {
10036 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10037 return;
10038
10039 // FIXME: Inform AST mutation listeners of this AST mutation.
10040 // FIXME: If there are multiple in-class declarations of the member (from
10041 // multiple modules, or a declaration and later definition of a member type),
10042 // should we update all of them?
10043 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10044 OrigD->setLocation(Loc);
10045}
10046
10049 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10050 if (Instantiation == Member)
10051 return;
10052
10053 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10054 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10055 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10056 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10057 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10058 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10059 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10060 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10061 else
10062 llvm_unreachable("unknown member specialization kind");
10063}
10064
10065/// Check the scope of an explicit instantiation.
10066///
10067/// \returns true if a serious error occurs, false otherwise.
10069 SourceLocation InstLoc,
10070 bool WasQualifiedName) {
10072 DeclContext *CurContext = S.CurContext->getRedeclContext();
10073
10074 if (CurContext->isRecord()) {
10075 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10076 << D;
10077 return true;
10078 }
10079
10080 // C++11 [temp.explicit]p3:
10081 // An explicit instantiation shall appear in an enclosing namespace of its
10082 // template. If the name declared in the explicit instantiation is an
10083 // unqualified name, the explicit instantiation shall appear in the
10084 // namespace where its template is declared or, if that namespace is inline
10085 // (7.3.1), any namespace from its enclosing namespace set.
10086 //
10087 // This is DR275, which we do not retroactively apply to C++98/03.
10088 if (WasQualifiedName) {
10089 if (CurContext->Encloses(OrigContext))
10090 return false;
10091 } else {
10092 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10093 return false;
10094 }
10095
10096 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10097 if (WasQualifiedName)
10098 S.Diag(InstLoc,
10099 S.getLangOpts().CPlusPlus11?
10100 diag::err_explicit_instantiation_out_of_scope :
10101 diag::warn_explicit_instantiation_out_of_scope_0x)
10102 << D << NS;
10103 else
10104 S.Diag(InstLoc,
10105 S.getLangOpts().CPlusPlus11?
10106 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10107 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10108 << D << NS;
10109 } else
10110 S.Diag(InstLoc,
10111 S.getLangOpts().CPlusPlus11?
10112 diag::err_explicit_instantiation_must_be_global :
10113 diag::warn_explicit_instantiation_must_be_global_0x)
10114 << D;
10115 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10116 return false;
10117}
10118
10119/// Common checks for whether an explicit instantiation of \p D is valid.
10121 SourceLocation InstLoc,
10122 bool WasQualifiedName,
10124 // C++ [temp.explicit]p13:
10125 // An explicit instantiation declaration shall not name a specialization of
10126 // a template with internal linkage.
10129 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10130 return true;
10131 }
10132
10133 // C++11 [temp.explicit]p3: [DR 275]
10134 // An explicit instantiation shall appear in an enclosing namespace of its
10135 // template.
10136 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10137 return true;
10138
10139 return false;
10140}
10141
10142/// Determine whether the given scope specifier has a template-id in it.
10144 // C++11 [temp.explicit]p3:
10145 // If the explicit instantiation is for a member function, a member class
10146 // or a static data member of a class template specialization, the name of
10147 // the class template specialization in the qualified-id for the member
10148 // name shall be a simple-template-id.
10149 //
10150 // C++98 has the same restriction, just worded differently.
10151 for (NestedNameSpecifier NNS = SS.getScopeRep();
10153 /**/) {
10154 const Type *T = NNS.getAsType();
10156 return true;
10157 NNS = T->getPrefix();
10158 }
10159 return false;
10160}
10161
10162/// Make a dllexport or dllimport attr on a class template specialization take
10163/// effect.
10166 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10167 assert(A && "dllExportImportClassTemplateSpecialization called "
10168 "on Def without dllexport or dllimport");
10169
10170 // We reject explicit instantiations in class scope, so there should
10171 // never be any delayed exported classes to worry about.
10172 assert(S.DelayedDllExportClasses.empty() &&
10173 "delayed exports present at explicit instantiation");
10175
10176 // Propagate attribute to base class templates.
10177 for (auto &B : Def->bases()) {
10178 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10179 B.getType()->getAsCXXRecordDecl()))
10181 }
10182
10184}
10185
10187 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10188 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10189 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10190 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10191 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10192 // Find the class template we're specializing
10193 TemplateName Name = TemplateD.get();
10194 TemplateDecl *TD = Name.getAsTemplateDecl();
10195 // Check that the specialization uses the same tag kind as the
10196 // original template.
10198 assert(Kind != TagTypeKind::Enum &&
10199 "Invalid enum tag in class template explicit instantiation!");
10200
10201 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10202
10203 if (!ClassTemplate) {
10204 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10205 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10206 Diag(TD->getLocation(), diag::note_previous_use);
10207 return true;
10208 }
10209
10210 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10211 Kind, /*isDefinition*/false, KWLoc,
10212 ClassTemplate->getIdentifier())) {
10213 Diag(KWLoc, diag::err_use_with_wrong_tag)
10214 << ClassTemplate
10216 ClassTemplate->getTemplatedDecl()->getKindName());
10217 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10218 diag::note_previous_use);
10219 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10220 }
10221
10222 // C++0x [temp.explicit]p2:
10223 // There are two forms of explicit instantiation: an explicit instantiation
10224 // definition and an explicit instantiation declaration. An explicit
10225 // instantiation declaration begins with the extern keyword. [...]
10226 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10229
10231 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10232 // Check for dllexport class template instantiation declarations,
10233 // except for MinGW mode.
10234 for (const ParsedAttr &AL : Attr) {
10235 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10236 Diag(ExternLoc,
10237 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10238 Diag(AL.getLoc(), diag::note_attribute);
10239 break;
10240 }
10241 }
10242
10243 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10244 Diag(ExternLoc,
10245 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10246 Diag(A->getLocation(), diag::note_attribute);
10247 }
10248 }
10249
10250 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10251 // instantiation declarations for most purposes.
10252 bool DLLImportExplicitInstantiationDef = false;
10254 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10255 // Check for dllimport class template instantiation definitions.
10256 bool DLLImport =
10257 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10258 for (const ParsedAttr &AL : Attr) {
10259 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10260 DLLImport = true;
10261 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10262 // dllexport trumps dllimport here.
10263 DLLImport = false;
10264 break;
10265 }
10266 }
10267 if (DLLImport) {
10269 DLLImportExplicitInstantiationDef = true;
10270 }
10271 }
10272
10273 // Translate the parser's template argument list in our AST format.
10274 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10275 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10276
10277 // Check that the template argument list is well-formed for this
10278 // template.
10280 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10281 /*DefaultArgs=*/{}, false, CTAI,
10282 /*UpdateArgsWithConversions=*/true,
10283 /*ConstraintsNotSatisfied=*/nullptr))
10284 return true;
10285
10286 // Find the class template specialization declaration that
10287 // corresponds to these arguments.
10288 void *InsertPos = nullptr;
10290 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10291
10292 TemplateSpecializationKind PrevDecl_TSK
10293 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10294
10295 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10296 Context.getTargetInfo().getTriple().isOSCygMing()) {
10297 // Check for dllexport class template instantiation definitions in MinGW
10298 // mode, if a previous declaration of the instantiation was seen.
10299 for (const ParsedAttr &AL : Attr) {
10300 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10301 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10302 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10303 } else {
10304 Diag(AL.getLoc(),
10305 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10306 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10307 }
10308 break;
10309 }
10310 }
10311 }
10312
10313 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10314 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10315 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10316 return AL.getKind() == ParsedAttr::AT_DLLExport;
10317 })) {
10318 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10319 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10320 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10321 }
10322 }
10323
10324 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10325 SS.isSet(), TSK))
10326 return true;
10327
10329
10330 bool HasNoEffect = false;
10331 if (PrevDecl) {
10332 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10333 PrevDecl, PrevDecl_TSK,
10334 PrevDecl->getPointOfInstantiation(),
10335 HasNoEffect))
10336 return PrevDecl;
10337
10338 // Even though HasNoEffect == true means that this explicit instantiation
10339 // has no effect on semantics, we go on to put its syntax in the AST.
10340
10341 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10342 PrevDecl_TSK == TSK_Undeclared) {
10343 // Since the only prior class template specialization with these
10344 // arguments was referenced but not declared, reuse that
10345 // declaration node as our own, updating the source location
10346 // for the template name to reflect our new declaration.
10347 // (Other source locations will be updated later.)
10348 Specialization = PrevDecl;
10349 Specialization->setLocation(TemplateNameLoc);
10350 PrevDecl = nullptr;
10351 }
10352
10353 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10354 DLLImportExplicitInstantiationDef) {
10355 // The new specialization might add a dllimport attribute.
10356 HasNoEffect = false;
10357 }
10358 }
10359
10360 if (!Specialization) {
10361 // Create a new class template specialization declaration node for
10362 // this explicit specialization.
10364 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10365 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10367
10368 // A MSInheritanceAttr attached to the previous declaration must be
10369 // propagated to the new node prior to instantiation.
10370 if (PrevDecl) {
10371 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10372 auto *Clone = A->clone(getASTContext());
10373 Clone->setInherited(true);
10374 Specialization->addAttr(Clone);
10375 Consumer.AssignInheritanceModel(Specialization);
10376 }
10377 }
10378
10379 if (!HasNoEffect && !PrevDecl) {
10380 // Insert the new specialization.
10381 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10382 }
10383 }
10384
10385 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10386
10387 // Set source locations for keywords.
10388 Specialization->setExternKeywordLoc(ExternLoc);
10389 Specialization->setTemplateKeywordLoc(TemplateLoc);
10390 Specialization->setBraceRange(SourceRange());
10391
10392 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10395
10396 // Add the explicit instantiation into its lexical context. However,
10397 // since explicit instantiations are never found by name lookup, we
10398 // just put it into the declaration context directly.
10399 Specialization->setLexicalDeclContext(CurContext);
10400 CurContext->addDecl(Specialization);
10401
10402 // Syntax is now OK, so return if it has no other effect on semantics.
10403 if (HasNoEffect) {
10404 // Set the template specialization kind.
10405 Specialization->setTemplateSpecializationKind(TSK);
10406 return Specialization;
10407 }
10408
10409 // C++ [temp.explicit]p3:
10410 // A definition of a class template or class member template
10411 // shall be in scope at the point of the explicit instantiation of
10412 // the class template or class member template.
10413 //
10414 // This check comes when we actually try to perform the
10415 // instantiation.
10417 = cast_or_null<ClassTemplateSpecializationDecl>(
10418 Specialization->getDefinition());
10419 if (!Def)
10421 /*Complain=*/true,
10422 CTAI.StrictPackMatch);
10423 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10424 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10425 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10426 }
10427
10428 // Instantiate the members of this class template specialization.
10429 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10430 Specialization->getDefinition());
10431 if (Def) {
10433 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10434 // TSK_ExplicitInstantiationDefinition
10435 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10437 DLLImportExplicitInstantiationDef)) {
10438 // FIXME: Need to notify the ASTMutationListener that we did this.
10440
10441 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10442 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10443 // An explicit instantiation definition can add a dll attribute to a
10444 // template with a previous instantiation declaration. MinGW doesn't
10445 // allow this.
10446 auto *A = cast<InheritableAttr>(
10448 A->setInherited(true);
10449 Def->addAttr(A);
10451 }
10452 }
10453
10454 // Fix a TSK_ImplicitInstantiation followed by a
10455 // TSK_ExplicitInstantiationDefinition
10456 bool NewlyDLLExported =
10457 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10458 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10459 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10460 // An explicit instantiation definition can add a dll attribute to a
10461 // template with a previous implicit instantiation. MinGW doesn't allow
10462 // this. We limit clang to only adding dllexport, to avoid potentially
10463 // strange codegen behavior. For example, if we extend this conditional
10464 // to dllimport, and we have a source file calling a method on an
10465 // implicitly instantiated template class instance and then declaring a
10466 // dllimport explicit instantiation definition for the same template
10467 // class, the codegen for the method call will not respect the dllimport,
10468 // while it will with cl. The Def will already have the DLL attribute,
10469 // since the Def and Specialization will be the same in the case of
10470 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10471 // attribute to the Specialization; we just need to make it take effect.
10472 assert(Def == Specialization &&
10473 "Def and Specialization should match for implicit instantiation");
10475 }
10476
10477 // In MinGW mode, export the template instantiation if the declaration
10478 // was marked dllexport.
10479 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10480 Context.getTargetInfo().getTriple().isOSCygMing() &&
10481 PrevDecl->hasAttr<DLLExportAttr>()) {
10483 }
10484
10485 // Set the template specialization kind. Make sure it is set before
10486 // instantiating the members which will trigger ASTConsumer callbacks.
10487 Specialization->setTemplateSpecializationKind(TSK);
10488 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10489 } else {
10490
10491 // Set the template specialization kind.
10492 Specialization->setTemplateSpecializationKind(TSK);
10493 }
10494
10495 return Specialization;
10496}
10497
10500 SourceLocation TemplateLoc, unsigned TagSpec,
10501 SourceLocation KWLoc, CXXScopeSpec &SS,
10502 IdentifierInfo *Name, SourceLocation NameLoc,
10503 const ParsedAttributesView &Attr) {
10504
10505 bool Owned = false;
10506 bool IsDependent = false;
10507 Decl *TagD =
10508 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10509 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10510 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10511 false, TypeResult(), /*IsTypeSpecifier*/ false,
10512 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10513 .get();
10514 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10515
10516 if (!TagD)
10517 return true;
10518
10519 TagDecl *Tag = cast<TagDecl>(TagD);
10520 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10521
10522 if (Tag->isInvalidDecl())
10523 return true;
10524
10526 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10527 if (!Pattern) {
10528 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10529 << Context.getCanonicalTagType(Record);
10530 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10531 return true;
10532 }
10533
10534 // C++0x [temp.explicit]p2:
10535 // If the explicit instantiation is for a class or member class, the
10536 // elaborated-type-specifier in the declaration shall include a
10537 // simple-template-id.
10538 //
10539 // C++98 has the same restriction, just worded differently.
10541 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10542 << Record << SS.getRange();
10543
10544 // C++0x [temp.explicit]p2:
10545 // There are two forms of explicit instantiation: an explicit instantiation
10546 // definition and an explicit instantiation declaration. An explicit
10547 // instantiation declaration begins with the extern keyword. [...]
10551
10552 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10553
10554 // Verify that it is okay to explicitly instantiate here.
10555 CXXRecordDecl *PrevDecl
10556 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10557 if (!PrevDecl && Record->getDefinition())
10558 PrevDecl = Record;
10559 if (PrevDecl) {
10561 bool HasNoEffect = false;
10562 assert(MSInfo && "No member specialization information?");
10563 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10564 PrevDecl,
10566 MSInfo->getPointOfInstantiation(),
10567 HasNoEffect))
10568 return true;
10569 if (HasNoEffect)
10570 return TagD;
10571 }
10572
10573 CXXRecordDecl *RecordDef
10574 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10575 if (!RecordDef) {
10576 // C++ [temp.explicit]p3:
10577 // A definition of a member class of a class template shall be in scope
10578 // at the point of an explicit instantiation of the member class.
10579 CXXRecordDecl *Def
10580 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10581 if (!Def) {
10582 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10583 << 0 << Record->getDeclName() << Record->getDeclContext();
10584 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10585 << Pattern;
10586 return true;
10587 } else {
10588 if (InstantiateClass(NameLoc, Record, Def,
10590 TSK))
10591 return true;
10592
10593 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10594 if (!RecordDef)
10595 return true;
10596 }
10597 }
10598
10599 // Instantiate all of the members of the class.
10600 InstantiateClassMembers(NameLoc, RecordDef,
10602
10604 MarkVTableUsed(NameLoc, RecordDef, true);
10605
10606 // FIXME: We don't have any representation for explicit instantiations of
10607 // member classes. Such a representation is not needed for compilation, but it
10608 // should be available for clients that want to see all of the declarations in
10609 // the source code.
10610 return TagD;
10611}
10612
10614 SourceLocation ExternLoc,
10615 SourceLocation TemplateLoc,
10616 Declarator &D) {
10617 // Explicit instantiations always require a name.
10618 // TODO: check if/when DNInfo should replace Name.
10620 DeclarationName Name = NameInfo.getName();
10621 if (!Name) {
10622 if (!D.isInvalidType())
10624 diag::err_explicit_instantiation_requires_name)
10626
10627 return true;
10628 }
10629
10630 // Get the innermost enclosing declaration scope.
10631 S = S->getDeclParent();
10632
10633 // Determine the type of the declaration.
10635 QualType R = T->getType();
10636 if (R.isNull())
10637 return true;
10638
10639 // C++ [dcl.stc]p1:
10640 // A storage-class-specifier shall not be specified in [...] an explicit
10641 // instantiation (14.7.2) directive.
10643 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10644 << Name;
10645 return true;
10646 } else if (D.getDeclSpec().getStorageClassSpec()
10648 // Complain about then remove the storage class specifier.
10649 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10651
10653 }
10654
10655 // C++0x [temp.explicit]p1:
10656 // [...] An explicit instantiation of a function template shall not use the
10657 // inline or constexpr specifiers.
10658 // Presumably, this also applies to member functions of class templates as
10659 // well.
10663 diag::err_explicit_instantiation_inline :
10664 diag::warn_explicit_instantiation_inline_0x)
10666 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10667 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10668 // not already specified.
10670 diag::err_explicit_instantiation_constexpr);
10671
10672 // A deduction guide is not on the list of entities that can be explicitly
10673 // instantiated.
10675 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10676 << /*explicit instantiation*/ 0;
10677 return true;
10678 }
10679
10680 // C++0x [temp.explicit]p2:
10681 // There are two forms of explicit instantiation: an explicit instantiation
10682 // definition and an explicit instantiation declaration. An explicit
10683 // instantiation declaration begins with the extern keyword. [...]
10687
10688 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10690 /*ObjectType=*/QualType());
10691
10692 if (!R->isFunctionType()) {
10693 // C++ [temp.explicit]p1:
10694 // A [...] static data member of a class template can be explicitly
10695 // instantiated from the member definition associated with its class
10696 // template.
10697 // C++1y [temp.explicit]p1:
10698 // A [...] variable [...] template specialization can be explicitly
10699 // instantiated from its template.
10700 if (Previous.isAmbiguous())
10701 return true;
10702
10703 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10704 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10705
10706 if (!PrevTemplate) {
10707 if (!Prev || !Prev->isStaticDataMember()) {
10708 // We expect to see a static data member here.
10709 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10710 << Name;
10711 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10712 P != PEnd; ++P)
10713 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10714 return true;
10715 }
10716
10718 // FIXME: Check for explicit specialization?
10720 diag::err_explicit_instantiation_data_member_not_instantiated)
10721 << Prev;
10722 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10723 // FIXME: Can we provide a note showing where this was declared?
10724 return true;
10725 }
10726 } else {
10727 // Explicitly instantiate a variable template.
10728
10729 // C++1y [dcl.spec.auto]p6:
10730 // ... A program that uses auto or decltype(auto) in a context not
10731 // explicitly allowed in this section is ill-formed.
10732 //
10733 // This includes auto-typed variable template instantiations.
10734 if (R->isUndeducedType()) {
10735 Diag(T->getTypeLoc().getBeginLoc(),
10736 diag::err_auto_not_allowed_var_inst);
10737 return true;
10738 }
10739
10741 // C++1y [temp.explicit]p3:
10742 // If the explicit instantiation is for a variable, the unqualified-id
10743 // in the declaration shall be a template-id.
10745 diag::err_explicit_instantiation_without_template_id)
10746 << PrevTemplate;
10747 Diag(PrevTemplate->getLocation(),
10748 diag::note_explicit_instantiation_here);
10749 return true;
10750 }
10751
10752 // Translate the parser's template argument list into our AST format.
10753 TemplateArgumentListInfo TemplateArgs =
10755
10756 DeclResult Res =
10757 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10758 TemplateArgs, /*SetWrittenArgs=*/true);
10759 if (Res.isInvalid())
10760 return true;
10761
10762 if (!Res.isUsable()) {
10763 // We somehow specified dependent template arguments in an explicit
10764 // instantiation. This should probably only happen during error
10765 // recovery.
10766 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10767 return true;
10768 }
10769
10770 // Ignore access control bits, we don't need them for redeclaration
10771 // checking.
10772 Prev = cast<VarDecl>(Res.get());
10773 }
10774
10775 // C++0x [temp.explicit]p2:
10776 // If the explicit instantiation is for a member function, a member class
10777 // or a static data member of a class template specialization, the name of
10778 // the class template specialization in the qualified-id for the member
10779 // name shall be a simple-template-id.
10780 //
10781 // C++98 has the same restriction, just worded differently.
10782 //
10783 // This does not apply to variable template specializations, where the
10784 // template-id is in the unqualified-id instead.
10785 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10787 diag::ext_explicit_instantiation_without_qualified_id)
10788 << Prev << D.getCXXScopeSpec().getRange();
10789
10790 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10791
10792 // Verify that it is okay to explicitly instantiate here.
10795 bool HasNoEffect = false;
10797 PrevTSK, POI, HasNoEffect))
10798 return true;
10799
10800 if (!HasNoEffect) {
10801 // Instantiate static data member or variable template.
10803 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10804 VTSD->setExternKeywordLoc(ExternLoc);
10805 VTSD->setTemplateKeywordLoc(TemplateLoc);
10806 }
10807
10808 // Merge attributes.
10810 if (PrevTemplate)
10811 ProcessAPINotes(Prev);
10812
10815 }
10816
10817 // Check the new variable specialization against the parsed input.
10818 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10819 Diag(T->getTypeLoc().getBeginLoc(),
10820 diag::err_invalid_var_template_spec_type)
10821 << 0 << PrevTemplate << R << Prev->getType();
10822 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10823 << 2 << PrevTemplate->getDeclName();
10824 return true;
10825 }
10826
10827 // FIXME: Create an ExplicitInstantiation node?
10828 return (Decl*) nullptr;
10829 }
10830
10831 // If the declarator is a template-id, translate the parser's template
10832 // argument list into our AST format.
10833 bool HasExplicitTemplateArgs = false;
10834 TemplateArgumentListInfo TemplateArgs;
10836 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10837 HasExplicitTemplateArgs = true;
10838 }
10839
10840 // C++ [temp.explicit]p1:
10841 // A [...] function [...] can be explicitly instantiated from its template.
10842 // A member function [...] of a class template can be explicitly
10843 // instantiated from the member definition associated with its class
10844 // template.
10845 UnresolvedSet<8> TemplateMatches;
10846 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10848 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10849 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10850 P != PEnd; ++P) {
10851 NamedDecl *Prev = *P;
10852 if (!HasExplicitTemplateArgs) {
10853 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10854 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10855 /*AdjustExceptionSpec*/true);
10856 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10857 if (Method->getPrimaryTemplate()) {
10858 TemplateMatches.addDecl(Method, P.getAccess());
10859 } else {
10860 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10861 C.FoundDecl = P.getPair();
10862 C.Function = Method;
10863 C.Viable = true;
10865 if (Method->getTrailingRequiresClause() &&
10867 /*ForOverloadResolution=*/true) ||
10868 !S.IsSatisfied)) {
10869 C.Viable = false;
10871 }
10872 }
10873 }
10874 }
10875 }
10876
10877 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10878 if (!FunTmpl)
10879 continue;
10880
10881 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10882 FunctionDecl *Specialization = nullptr;
10884 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10885 Specialization, Info);
10887 // Keep track of almost-matches.
10888 FailedTemplateCandidates.addCandidate().set(
10889 P.getPair(), FunTmpl->getTemplatedDecl(),
10890 MakeDeductionFailureInfo(Context, TDK, Info));
10891 (void)TDK;
10892 continue;
10893 }
10894
10895 // Target attributes are part of the cuda function signature, so
10896 // the cuda target of the instantiated function must match that of its
10897 // template. Given that C++ template deduction does not take
10898 // target attributes into account, we reject candidates here that
10899 // have a different target.
10900 if (LangOpts.CUDA &&
10901 CUDA().IdentifyTarget(Specialization,
10902 /* IgnoreImplicitHDAttr = */ true) !=
10903 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10904 FailedTemplateCandidates.addCandidate().set(
10905 P.getPair(), FunTmpl->getTemplatedDecl(),
10908 continue;
10909 }
10910
10911 TemplateMatches.addDecl(Specialization, P.getAccess());
10912 }
10913
10914 FunctionDecl *Specialization = nullptr;
10915 if (!NonTemplateMatches.empty()) {
10916 unsigned Msg = 0;
10917 OverloadCandidateDisplayKind DisplayKind;
10919 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10920 Best)) {
10921 case OR_Success:
10922 case OR_Deleted:
10923 Specialization = cast<FunctionDecl>(Best->Function);
10924 break;
10925 case OR_Ambiguous:
10926 Msg = diag::err_explicit_instantiation_ambiguous;
10927 DisplayKind = OCD_AmbiguousCandidates;
10928 break;
10930 Msg = diag::err_explicit_instantiation_no_candidate;
10931 DisplayKind = OCD_AllCandidates;
10932 break;
10933 }
10934 if (Msg) {
10935 PartialDiagnostic Diag = PDiag(Msg) << Name;
10936 NonTemplateMatches.NoteCandidates(
10937 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10938 {});
10939 return true;
10940 }
10941 }
10942
10943 if (!Specialization) {
10944 // Find the most specialized function template specialization.
10946 TemplateMatches.begin(), TemplateMatches.end(),
10947 FailedTemplateCandidates, D.getIdentifierLoc(),
10948 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10949 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10950 PDiag(diag::note_explicit_instantiation_candidate));
10951
10952 if (Result == TemplateMatches.end())
10953 return true;
10954
10955 // Ignore access control bits, we don't need them for redeclaration checking.
10957 }
10958
10959 // C++11 [except.spec]p4
10960 // In an explicit instantiation an exception-specification may be specified,
10961 // but is not required.
10962 // If an exception-specification is specified in an explicit instantiation
10963 // directive, it shall be compatible with the exception-specifications of
10964 // other declarations of that function.
10965 if (auto *FPT = R->getAs<FunctionProtoType>())
10966 if (FPT->hasExceptionSpec()) {
10967 unsigned DiagID =
10968 diag::err_mismatched_exception_spec_explicit_instantiation;
10969 if (getLangOpts().MicrosoftExt)
10970 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10972 PDiag(DiagID) << Specialization->getType(),
10973 PDiag(diag::note_explicit_instantiation_here),
10974 Specialization->getType()->getAs<FunctionProtoType>(),
10975 Specialization->getLocation(), FPT, D.getBeginLoc());
10976 // In Microsoft mode, mismatching exception specifications just cause a
10977 // warning.
10978 if (!getLangOpts().MicrosoftExt && Result)
10979 return true;
10980 }
10981
10982 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10984 diag::err_explicit_instantiation_member_function_not_instantiated)
10986 << (Specialization->getTemplateSpecializationKind() ==
10988 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10989 return true;
10990 }
10991
10992 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10993 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10994 PrevDecl = Specialization;
10995
10996 if (PrevDecl) {
10997 bool HasNoEffect = false;
10999 PrevDecl,
11001 PrevDecl->getPointOfInstantiation(),
11002 HasNoEffect))
11003 return true;
11004
11005 // FIXME: We may still want to build some representation of this
11006 // explicit specialization.
11007 if (HasNoEffect)
11008 return (Decl*) nullptr;
11009 }
11010
11011 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11012 // functions
11013 // valarray<size_t>::valarray(size_t) and
11014 // valarray<size_t>::~valarray()
11015 // that it declared to have internal linkage with the internal_linkage
11016 // attribute. Ignore the explicit instantiation declaration in this case.
11017 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11019 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11020 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11021 RD->isInStdNamespace())
11022 return (Decl*) nullptr;
11023 }
11024
11027
11028 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11029 // instantiation declarations.
11031 Specialization->hasAttr<DLLImportAttr>() &&
11032 Context.getTargetInfo().getCXXABI().isMicrosoft())
11034
11035 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11036
11037 if (Specialization->isDefined()) {
11038 // Let the ASTConsumer know that this function has been explicitly
11039 // instantiated now, and its linkage might have changed.
11040 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11041 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11043
11044 // C++0x [temp.explicit]p2:
11045 // If the explicit instantiation is for a member function, a member class
11046 // or a static data member of a class template specialization, the name of
11047 // the class template specialization in the qualified-id for the member
11048 // name shall be a simple-template-id.
11049 //
11050 // C++98 has the same restriction, just worded differently.
11051 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11052 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11053 D.getCXXScopeSpec().isSet() &&
11056 diag::ext_explicit_instantiation_without_qualified_id)
11058
11060 *this,
11061 FunTmpl ? (NamedDecl *)FunTmpl
11062 : Specialization->getInstantiatedFromMemberFunction(),
11063 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11064
11065 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11066 return (Decl*) nullptr;
11067}
11068
11070 const CXXScopeSpec &SS,
11071 const IdentifierInfo *Name,
11072 SourceLocation TagLoc,
11073 SourceLocation NameLoc) {
11074 // This has to hold, because SS is expected to be defined.
11075 assert(Name && "Expected a name in a dependent tag");
11076
11078 if (!NNS)
11079 return true;
11080
11082
11083 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11084 Diag(NameLoc, diag::err_dependent_tag_decl)
11085 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11086 return true;
11087 }
11088
11089 // Create the resulting type.
11091 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11092
11093 // Create type-source location information for this type.
11094 TypeLocBuilder TLB;
11096 TL.setElaboratedKeywordLoc(TagLoc);
11098 TL.setNameLoc(NameLoc);
11100}
11101
11103 const CXXScopeSpec &SS,
11104 const IdentifierInfo &II,
11105 SourceLocation IdLoc,
11106 ImplicitTypenameContext IsImplicitTypename) {
11107 if (SS.isInvalid())
11108 return true;
11109
11110 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11111 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11112 << FixItHint::CreateRemoval(TypenameLoc);
11113
11115 TypeSourceInfo *TSI = nullptr;
11116 QualType T =
11119 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11120 /*DeducedTSTContext=*/true);
11121 if (T.isNull())
11122 return true;
11123 return CreateParsedType(T, TSI);
11124}
11125
11128 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11129 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11130 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11131 ASTTemplateArgsPtr TemplateArgsIn,
11132 SourceLocation RAngleLoc) {
11133 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11134 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11135 ? diag::compat_cxx11_typename_outside_of_template
11136 : diag::compat_pre_cxx11_typename_outside_of_template)
11137 << FixItHint::CreateRemoval(TypenameLoc);
11138
11139 // Strangely, non-type results are not ignored by this lookup, so the
11140 // program is ill-formed if it finds an injected-class-name.
11141 if (TypenameLoc.isValid()) {
11142 auto *LookupRD =
11143 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11144 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11145 Diag(TemplateIILoc,
11146 diag::ext_out_of_line_qualified_id_type_names_constructor)
11147 << TemplateII << 0 /*injected-class-name used as template name*/
11148 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11149 }
11150 }
11151
11152 // Translate the parser's template argument list in our AST format.
11153 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11154 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11155
11159 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11160 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11161 if (T.isNull())
11162 return true;
11163
11164 // Provide source-location information for the template specialization type.
11165 TypeLocBuilder Builder;
11167 = Builder.push<TemplateSpecializationTypeLoc>(T);
11168 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11169 TemplateIILoc, TemplateArgs);
11170 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11171 return CreateParsedType(T, TSI);
11172}
11173
11174/// Determine whether this failed name lookup should be treated as being
11175/// disabled by a usage of std::enable_if.
11177 SourceRange &CondRange, Expr *&Cond) {
11178 // We must be looking for a ::type...
11179 if (!II.isStr("type"))
11180 return false;
11181
11182 // ... within an explicitly-written template specialization...
11184 return false;
11185
11186 // FIXME: Look through sugar.
11187 auto EnableIfTSTLoc =
11189 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11190 return false;
11191 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11192
11193 // ... which names a complete class template declaration...
11194 const TemplateDecl *EnableIfDecl =
11195 EnableIfTST->getTemplateName().getAsTemplateDecl();
11196 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11197 return false;
11198
11199 // ... called "enable_if".
11200 const IdentifierInfo *EnableIfII =
11201 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11202 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11203 return false;
11204
11205 // Assume the first template argument is the condition.
11206 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11207
11208 // Dig out the condition.
11209 Cond = nullptr;
11210 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11212 return true;
11213
11214 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11215
11216 // Ignore Boolean literals; they add no value.
11217 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11218 Cond = nullptr;
11219
11220 return true;
11221}
11222
11225 SourceLocation KeywordLoc,
11226 NestedNameSpecifierLoc QualifierLoc,
11227 const IdentifierInfo &II,
11228 SourceLocation IILoc,
11229 TypeSourceInfo **TSI,
11230 bool DeducedTSTContext) {
11231 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11232 DeducedTSTContext);
11233 if (T.isNull())
11234 return QualType();
11235
11236 TypeLocBuilder TLB;
11237 if (isa<DependentNameType>(T)) {
11238 auto TL = TLB.push<DependentNameTypeLoc>(T);
11239 TL.setElaboratedKeywordLoc(KeywordLoc);
11240 TL.setQualifierLoc(QualifierLoc);
11241 TL.setNameLoc(IILoc);
11244 TL.setElaboratedKeywordLoc(KeywordLoc);
11245 TL.setQualifierLoc(QualifierLoc);
11246 TL.setNameLoc(IILoc);
11247 } else if (isa<TemplateTypeParmType>(T)) {
11248 // FIXME: There might be a 'typename' keyword here, but we just drop it
11249 // as it can't be represented.
11250 assert(!QualifierLoc);
11251 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11252 } else if (isa<TagType>(T)) {
11253 auto TL = TLB.push<TagTypeLoc>(T);
11254 TL.setElaboratedKeywordLoc(KeywordLoc);
11255 TL.setQualifierLoc(QualifierLoc);
11256 TL.setNameLoc(IILoc);
11257 } else if (isa<TypedefType>(T)) {
11258 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11259 } else {
11260 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11261 }
11262 *TSI = TLB.getTypeSourceInfo(Context, T);
11263 return T;
11264}
11265
11266/// Build the type that describes a C++ typename specifier,
11267/// e.g., "typename T::type".
11270 SourceLocation KeywordLoc,
11271 NestedNameSpecifierLoc QualifierLoc,
11272 const IdentifierInfo &II,
11273 SourceLocation IILoc, bool DeducedTSTContext) {
11274 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11275
11276 CXXScopeSpec SS;
11277 SS.Adopt(QualifierLoc);
11278
11279 DeclContext *Ctx = nullptr;
11280 if (QualifierLoc) {
11281 Ctx = computeDeclContext(SS);
11282 if (!Ctx) {
11283 // If the nested-name-specifier is dependent and couldn't be
11284 // resolved to a type, build a typename type.
11285 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11286 return Context.getDependentNameType(Keyword,
11287 QualifierLoc.getNestedNameSpecifier(),
11288 &II);
11289 }
11290
11291 // If the nested-name-specifier refers to the current instantiation,
11292 // the "typename" keyword itself is superfluous. In C++03, the
11293 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11294 // allows such extraneous "typename" keywords, and we retroactively
11295 // apply this DR to C++03 code with only a warning. In any case we continue.
11296
11297 if (RequireCompleteDeclContext(SS, Ctx))
11298 return QualType();
11299 }
11300
11301 DeclarationName Name(&II);
11302 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11303 if (Ctx)
11304 LookupQualifiedName(Result, Ctx, SS);
11305 else
11306 LookupName(Result, CurScope);
11307 unsigned DiagID = 0;
11308 Decl *Referenced = nullptr;
11309 switch (Result.getResultKind()) {
11311 // If we're looking up 'type' within a template named 'enable_if', produce
11312 // a more specific diagnostic.
11313 SourceRange CondRange;
11314 Expr *Cond = nullptr;
11315 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11316 // If we have a condition, narrow it down to the specific failed
11317 // condition.
11318 if (Cond) {
11319 Expr *FailedCond;
11320 std::string FailedDescription;
11321 std::tie(FailedCond, FailedDescription) =
11323
11324 Diag(FailedCond->getExprLoc(),
11325 diag::err_typename_nested_not_found_requirement)
11326 << FailedDescription
11327 << FailedCond->getSourceRange();
11328 return QualType();
11329 }
11330
11331 Diag(CondRange.getBegin(),
11332 diag::err_typename_nested_not_found_enable_if)
11333 << Ctx << CondRange;
11334 return QualType();
11335 }
11336
11337 DiagID = Ctx ? diag::err_typename_nested_not_found
11338 : diag::err_unknown_typename;
11339 break;
11340 }
11341
11343 // We found a using declaration that is a value. Most likely, the using
11344 // declaration itself is meant to have the 'typename' keyword.
11345 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11346 IILoc);
11347 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11348 << Name << Ctx << FullRange;
11349 if (UnresolvedUsingValueDecl *Using
11350 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11351 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11352 Diag(Loc, diag::note_using_value_decl_missing_typename)
11353 << FixItHint::CreateInsertion(Loc, "typename ");
11354 }
11355 }
11356 // Fall through to create a dependent typename type, from which we can
11357 // recover better.
11358 [[fallthrough]];
11359
11361 // Okay, it's a member of an unknown instantiation.
11362 return Context.getDependentNameType(Keyword,
11363 QualifierLoc.getNestedNameSpecifier(),
11364 &II);
11365
11367 // FXIME: Missing support for UsingShadowDecl on this path?
11368 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11369 // C++ [class.qual]p2:
11370 // In a lookup in which function names are not ignored and the
11371 // nested-name-specifier nominates a class C, if the name specified
11372 // after the nested-name-specifier, when looked up in C, is the
11373 // injected-class-name of C [...] then the name is instead considered
11374 // to name the constructor of class C.
11375 //
11376 // Unlike in an elaborated-type-specifier, function names are not ignored
11377 // in typename-specifier lookup. However, they are ignored in all the
11378 // contexts where we form a typename type with no keyword (that is, in
11379 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11380 //
11381 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11382 // ignore functions, but that appears to be an oversight.
11387 Type, IILoc);
11388 // FIXME: This appears to be the only case where a template type parameter
11389 // can have an elaborated keyword. We should preserve it somehow.
11392 assert(!QualifierLoc);
11394 }
11395 return Context.getTypeDeclType(
11396 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11397 }
11398
11399 // C++ [dcl.type.simple]p2:
11400 // A type-specifier of the form
11401 // typename[opt] nested-name-specifier[opt] template-name
11402 // is a placeholder for a deduced class type [...].
11403 if (getLangOpts().CPlusPlus17) {
11404 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11405 if (!DeducedTSTContext) {
11406 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11407 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11408 Diag(IILoc, diag::err_dependent_deduced_tst)
11410 << QualType(Qualifier.getAsType(), 0);
11411 else
11412 Diag(IILoc, diag::err_deduced_tst)
11415 return QualType();
11416 }
11417 TemplateName Name = Context.getQualifiedTemplateName(
11418 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11419 TemplateName(TD));
11420 return Context.getDeducedTemplateSpecializationType(
11421 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11422 Name);
11423 }
11424 }
11425
11426 DiagID = Ctx ? diag::err_typename_nested_not_type
11427 : diag::err_typename_not_type;
11428 Referenced = Result.getFoundDecl();
11429 break;
11430
11432 DiagID = Ctx ? diag::err_typename_nested_not_type
11433 : diag::err_typename_not_type;
11434 Referenced = *Result.begin();
11435 break;
11436
11438 return QualType();
11439 }
11440
11441 // If we get here, it's because name lookup did not find a
11442 // type. Emit an appropriate diagnostic and return an error.
11443 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11444 IILoc);
11445 if (Ctx)
11446 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11447 else
11448 Diag(IILoc, DiagID) << FullRange << Name;
11449 if (Referenced)
11450 Diag(Referenced->getLocation(),
11451 Ctx ? diag::note_typename_member_refers_here
11452 : diag::note_typename_refers_here)
11453 << Name;
11454 return QualType();
11455}
11456
11457namespace {
11458 // See Sema::RebuildTypeInCurrentInstantiation
11459 class CurrentInstantiationRebuilder
11460 : public TreeTransform<CurrentInstantiationRebuilder> {
11461 SourceLocation Loc;
11462 DeclarationName Entity;
11463
11464 public:
11466
11467 CurrentInstantiationRebuilder(Sema &SemaRef,
11468 SourceLocation Loc,
11469 DeclarationName Entity)
11470 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11471 Loc(Loc), Entity(Entity) { }
11472
11473 /// Determine whether the given type \p T has already been
11474 /// transformed.
11475 ///
11476 /// For the purposes of type reconstruction, a type has already been
11477 /// transformed if it is NULL or if it is not dependent.
11478 bool AlreadyTransformed(QualType T) {
11479 return T.isNull() || !T->isInstantiationDependentType();
11480 }
11481
11482 /// Returns the location of the entity whose type is being
11483 /// rebuilt.
11484 SourceLocation getBaseLocation() { return Loc; }
11485
11486 /// Returns the name of the entity whose type is being rebuilt.
11487 DeclarationName getBaseEntity() { return Entity; }
11488
11489 /// Sets the "base" location and entity when that
11490 /// information is known based on another transformation.
11491 void setBase(SourceLocation Loc, DeclarationName Entity) {
11492 this->Loc = Loc;
11493 this->Entity = Entity;
11494 }
11495
11496 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11497 // Lambdas never need to be transformed.
11498 return E;
11499 }
11500 };
11501} // end anonymous namespace
11502
11504 SourceLocation Loc,
11505 DeclarationName Name) {
11506 if (!T || !T->getType()->isInstantiationDependentType())
11507 return T;
11508
11509 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11510 return Rebuilder.TransformType(T);
11511}
11512
11514 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11515 DeclarationName());
11516 return Rebuilder.TransformExpr(E);
11517}
11518
11520 if (SS.isInvalid())
11521 return true;
11522
11524 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11525 DeclarationName());
11527 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11528 if (!Rebuilt)
11529 return true;
11530
11531 SS.Adopt(Rebuilt);
11532 return false;
11533}
11534
11536 TemplateParameterList *Params) {
11537 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11538 Decl *Param = Params->getParam(I);
11539
11540 // There is nothing to rebuild in a type parameter.
11541 if (isa<TemplateTypeParmDecl>(Param))
11542 continue;
11543
11544 // Rebuild the template parameter list of a template template parameter.
11546 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11548 TTP->getTemplateParameters()))
11549 return true;
11550
11551 continue;
11552 }
11553
11554 // Rebuild the type of a non-type template parameter.
11556 TypeSourceInfo *NewTSI
11558 NTTP->getLocation(),
11559 NTTP->getDeclName());
11560 if (!NewTSI)
11561 return true;
11562
11563 if (NewTSI->getType()->isUndeducedType()) {
11564 // C++17 [temp.dep.expr]p3:
11565 // An id-expression is type-dependent if it contains
11566 // - an identifier associated by name lookup with a non-type
11567 // template-parameter declared with a type that contains a
11568 // placeholder type (7.1.7.4),
11569 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11570 }
11571
11572 if (NewTSI != NTTP->getTypeSourceInfo()) {
11573 NTTP->setTypeSourceInfo(NewTSI);
11574 NTTP->setType(NewTSI->getType());
11575 }
11576 }
11577
11578 return false;
11579}
11580
11581std::string
11583 const TemplateArgumentList &Args) {
11584 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11585}
11586
11587std::string
11589 const TemplateArgument *Args,
11590 unsigned NumArgs) {
11591 SmallString<128> Str;
11592 llvm::raw_svector_ostream Out(Str);
11593
11594 if (!Params || Params->size() == 0 || NumArgs == 0)
11595 return std::string();
11596
11597 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11598 if (I >= NumArgs)
11599 break;
11600
11601 if (I == 0)
11602 Out << "[with ";
11603 else
11604 Out << ", ";
11605
11606 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11607 Out << Id->getName();
11608 } else {
11609 Out << '$' << I;
11610 }
11611
11612 Out << " = ";
11613 Args[I].print(getPrintingPolicy(), Out,
11615 getPrintingPolicy(), Params, I));
11616 }
11617
11618 Out << ']';
11619 return std::string(Out.str());
11620}
11621
11623 CachedTokens &Toks) {
11624 if (!FD)
11625 return;
11626
11627 auto LPT = std::make_unique<LateParsedTemplate>();
11628
11629 // Take tokens to avoid allocations
11630 LPT->Toks.swap(Toks);
11631 LPT->D = FnD;
11632 LPT->FPO = getCurFPFeatures();
11633 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11634
11635 FD->setLateTemplateParsed(true);
11636}
11637
11639 if (!FD)
11640 return;
11641 FD->setLateTemplateParsed(false);
11642}
11643
11645 DeclContext *DC = CurContext;
11646
11647 while (DC) {
11648 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11649 const FunctionDecl *FD = RD->isLocalClass();
11650 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11651 } else if (DC->isTranslationUnit() || DC->isNamespace())
11652 return false;
11653
11654 DC = DC->getParent();
11655 }
11656 return false;
11657}
11658
11659namespace {
11660/// Walk the path from which a declaration was instantiated, and check
11661/// that every explicit specialization along that path is visible. This enforces
11662/// C++ [temp.expl.spec]/6:
11663///
11664/// If a template, a member template or a member of a class template is
11665/// explicitly specialized then that specialization shall be declared before
11666/// the first use of that specialization that would cause an implicit
11667/// instantiation to take place, in every translation unit in which such a
11668/// use occurs; no diagnostic is required.
11669///
11670/// and also C++ [temp.class.spec]/1:
11671///
11672/// A partial specialization shall be declared before the first use of a
11673/// class template specialization that would make use of the partial
11674/// specialization as the result of an implicit or explicit instantiation
11675/// in every translation unit in which such a use occurs; no diagnostic is
11676/// required.
11677class ExplicitSpecializationVisibilityChecker {
11678 Sema &S;
11679 SourceLocation Loc;
11682
11683public:
11684 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11686 : S(S), Loc(Loc), Kind(Kind) {}
11687
11688 void check(NamedDecl *ND) {
11689 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11690 return checkImpl(FD);
11691 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11692 return checkImpl(RD);
11693 if (auto *VD = dyn_cast<VarDecl>(ND))
11694 return checkImpl(VD);
11695 if (auto *ED = dyn_cast<EnumDecl>(ND))
11696 return checkImpl(ED);
11697 }
11698
11699private:
11700 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11701 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11702 : Sema::MissingImportKind::ExplicitSpecialization;
11703 const bool Recover = true;
11704
11705 // If we got a custom set of modules (because only a subset of the
11706 // declarations are interesting), use them, otherwise let
11707 // diagnoseMissingImport intelligently pick some.
11708 if (Modules.empty())
11709 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11710 else
11711 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11712 }
11713
11714 bool CheckMemberSpecialization(const NamedDecl *D) {
11715 return Kind == Sema::AcceptableKind::Visible
11718 }
11719
11720 bool CheckExplicitSpecialization(const NamedDecl *D) {
11721 return Kind == Sema::AcceptableKind::Visible
11724 }
11725
11726 bool CheckDeclaration(const NamedDecl *D) {
11727 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11729 }
11730
11731 // Check a specific declaration. There are three problematic cases:
11732 //
11733 // 1) The declaration is an explicit specialization of a template
11734 // specialization.
11735 // 2) The declaration is an explicit specialization of a member of an
11736 // templated class.
11737 // 3) The declaration is an instantiation of a template, and that template
11738 // is an explicit specialization of a member of a templated class.
11739 //
11740 // We don't need to go any deeper than that, as the instantiation of the
11741 // surrounding class / etc is not triggered by whatever triggered this
11742 // instantiation, and thus should be checked elsewhere.
11743 template<typename SpecDecl>
11744 void checkImpl(SpecDecl *Spec) {
11745 bool IsHiddenExplicitSpecialization = false;
11746 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11747 // Some invalid friend declarations are written as specializations but are
11748 // instantiated implicitly.
11749 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11750 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11751 if (SpecKind == TSK_ExplicitSpecialization) {
11752 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11753 ? !CheckMemberSpecialization(Spec)
11754 : !CheckExplicitSpecialization(Spec);
11755 } else {
11756 checkInstantiated(Spec);
11757 }
11758
11759 if (IsHiddenExplicitSpecialization)
11760 diagnose(Spec->getMostRecentDecl(), false);
11761 }
11762
11763 void checkInstantiated(FunctionDecl *FD) {
11764 if (auto *TD = FD->getPrimaryTemplate())
11765 checkTemplate(TD);
11766 }
11767
11768 void checkInstantiated(CXXRecordDecl *RD) {
11769 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11770 if (!SD)
11771 return;
11772
11773 auto From = SD->getSpecializedTemplateOrPartial();
11774 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11775 checkTemplate(TD);
11776 else if (auto *TD =
11777 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11778 if (!CheckDeclaration(TD))
11779 diagnose(TD, true);
11780 checkTemplate(TD);
11781 }
11782 }
11783
11784 void checkInstantiated(VarDecl *RD) {
11785 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11786 if (!SD)
11787 return;
11788
11789 auto From = SD->getSpecializedTemplateOrPartial();
11790 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11791 checkTemplate(TD);
11792 else if (auto *TD =
11793 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11794 if (!CheckDeclaration(TD))
11795 diagnose(TD, true);
11796 checkTemplate(TD);
11797 }
11798 }
11799
11800 void checkInstantiated(EnumDecl *FD) {}
11801
11802 template<typename TemplDecl>
11803 void checkTemplate(TemplDecl *TD) {
11804 if (TD->isMemberSpecialization()) {
11805 if (!CheckMemberSpecialization(TD))
11806 diagnose(TD->getMostRecentDecl(), false);
11807 }
11808 }
11809};
11810} // end anonymous namespace
11811
11813 if (!getLangOpts().Modules)
11814 return;
11815
11816 ExplicitSpecializationVisibilityChecker(*this, Loc,
11818 .check(Spec);
11819}
11820
11822 NamedDecl *Spec) {
11823 if (!getLangOpts().CPlusPlusModules)
11824 return checkSpecializationVisibility(Loc, Spec);
11825
11826 ExplicitSpecializationVisibilityChecker(*this, Loc,
11828 .check(Spec);
11829}
11830
11833 return N->getLocation();
11834 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11836 return FD->getLocation();
11839 return N->getLocation();
11840 }
11841 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11842 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11843 continue;
11844 return CSC.PointOfInstantiation;
11845 }
11846 return N->getLocation();
11847}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
APSInt & getInt()
Definition APValue.h:508
APSInt & getComplexIntImag()
Definition APValue.h:546
ValueKind getKind() const
Definition APValue.h:479
APFixedPoint & getFixedPoint()
Definition APValue.h:530
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isMemberPointer() const
Definition APValue.h:496
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isNullPointer() const
Definition APValue.cpp:1051
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3942
QualType getElementType() const
Definition TypeBase.h:3784
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8230
Attr - This represents one attribute.
Definition Attr.h:46
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2393
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2411
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2461
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2454
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2429
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2435
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2441
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8283
Pointer to a block type.
Definition TypeBase.h:3592
QualType getPointeeType() const
Definition TypeBase.h:3604
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
BuiltinTemplateKind getBuiltinTemplateKind() const
This class is used for builtin types like 'int'.
Definition TypeBase.h:3214
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition Expr.cpp:2104
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:736
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3871
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:769
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2030
base_class_range bases()
Definition DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2056
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2037
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2071
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:207
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:184
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1069
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
QualType getElementType() const
Definition TypeBase.h:3335
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
bool isNamespace() const
Definition DeclBase.h:2198
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1374
ValueDecl * getDecl()
Definition Expr.h:1341
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
bool isVirtualSpecified() const
Definition DeclSpec.h:653
void ClearStorageClassSpecs()
Definition DeclSpec.h:498
bool isNoreturnSpecified() const
Definition DeclSpec.h:666
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:493
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:558
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:667
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:659
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:485
ParsedAttributes & getAttributes()
Definition DeclSpec.h:878
bool isInlineSpecified() const
Definition DeclSpec.h:642
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:494
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:654
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:841
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:645
bool hasExplicitSpecifier() const
Definition DeclSpec.h:656
bool hasConstexprSpecifier() const
Definition DeclSpec.h:842
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2747
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2087
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
bool hasEllipsis() const
Definition DeclSpec.h:2746
bool isInvalidType() const
Definition DeclSpec.h:2735
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2075
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4111
QualType getPointeeType() const
Definition TypeBase.h:4123
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3511
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4061
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4151
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4523
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4277
QualType getElementType() const
Definition TypeBase.h:4289
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateName(TemplateName Template)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4028
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4300
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5155
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:830
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3070
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4068
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Represents a member of a struct/union/class.
Definition Decl.h:3175
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:997
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1076
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Represents a function declaration or definition.
Definition Decl.h:2015
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2491
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4206
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4515
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4173
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3748
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2555
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4145
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition Decl.cpp:4379
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2377
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4418
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3170
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4166
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4935
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5797
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
QualType getReturnType() const
Definition TypeBase.h:4893
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3959
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5302
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3667
Represents a linkage specification.
Definition DeclCXX.h:3018
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
A global _GUID constant.
Definition DeclCXX.h:4401
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4401
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3735
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5536
QualType getPointeeType() const
Definition TypeBase.h:3721
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:258
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:212
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:266
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1942
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7993
Represents a pointer to an Objective C object.
Definition TypeBase.h:8049
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
bool isVarDeclReference() const
Definition ExprCXX.h:3303
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3319
bool isConceptReference() const
Definition ExprCXX.h:3292
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3338
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4364
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8249
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8520
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3630
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3623
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3685
Represents a struct/union/class.
Definition Decl.h:4342
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4526
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5347
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3623
QualType getPointeeType() const
Definition TypeBase.h:3641
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13746
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8523
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
Whether and why a template name is required in this lookup.
Definition Sema.h:11483
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11491
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12542
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12576
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7792
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13685
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13139
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2628
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9402
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9406
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9414
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9409
ExprResult ActOnConstantExpression(ExprResult Res)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9716
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void NoteAllFoundTemplates(TemplateName Name)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition Sema.h:1473
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4199
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11454
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12052
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12055
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12059
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1308
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:939
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12232
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12250
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12240
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12260
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
AssumedTemplateKind
Definition Sema.h:11504
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11511
@ None
This is not assumed to be a template name.
Definition Sema.h:11506
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11508
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition Sema.h:11440
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14547
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14535
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14544
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14538
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14562
const LangOptions & getLangOpts() const
Definition Sema.h:932
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1307
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1306
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13784
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15555
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ASTConsumer & Consumer
Definition Sema.h:1309
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4697
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *StrictPackMatch)
Check a template argument against its corresponding template template parameter.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6801
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6780
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
bool inParameterMappingSubstitution() const
Definition Sema.h:14061
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11481
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11664
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11674
@ TPC_FriendFunctionTemplate
Definition Sema.h:11672
@ TPC_ClassTemplateMember
Definition Sema.h:11670
@ TPC_FunctionTemplate
Definition Sema.h:11669
@ TPC_FriendClassTemplate
Definition Sema.h:11671
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11673
friend class InitializationSequence
Definition Sema.h:1588
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6351
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6488
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1300
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3519
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11446
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:149
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9725
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12982
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:328
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8734
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13781
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4665
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3732
StringRef getKindName() const
Definition Decl.h:3928
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4907
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5043
TagKind getTagKind() const
Definition Decl.h:3932
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3703
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3528
const Type * getTypeForDecl() const
Definition Decl.h:3553
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3562
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:884
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6268
A container of type source information.
Definition TypeBase.h:8402
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8413
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2533
bool isBooleanType() const
Definition TypeBase.h:9171
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2308
bool isRValueReferenceType() const
Definition TypeBase.h:8700
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:714
bool isArrayType() const
Definition TypeBase.h:8767
bool isPointerType() const
Definition TypeBase.h:8668
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2121
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:473
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8855
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2949
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2840
bool isLValueReferenceType() const
Definition TypeBase.h:8696
bool isBitIntType() const
Definition TypeBase.h:8943
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8791
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2074
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2850
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition Type.cpp:4979
bool isPointerOrReferenceType() const
Definition TypeBase.h:8672
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isVectorType() const
Definition TypeBase.h:8807
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2459
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
QualType getUnderlyingType() const
Definition Decl.h:3632
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4121
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1065
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1245
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1242
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1061
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1085
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3391
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6073
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3943
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3402
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3466
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2180
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1298
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2784
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2919
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2812
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2791
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2910
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4016
Represents a GCC generic vector type.
Definition TypeBase.h:4225
QualType getElementType() const
Definition TypeBase.h:4239
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
const PartialDiagnosticAt & peekSFINAEDiagnostic() const
Peek at the SFINAE diagnostic.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
ImplicitTypenameContext
Definition DeclSpec.h:1904
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1017
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1011
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1013
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Extern
Definition Specifiers.h:251
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5981
@ Enum
The "enum" keyword.
Definition TypeBase.h:5995
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1800
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1250
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5956
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5974
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2246
CharacterLiteralKind
Definition Expr.h:1606
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5442
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3333
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3350
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3315
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12090
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12086
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12079
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12076
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12076
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13190
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13297
A stack object to be created when performing template instantiation.
Definition Sema.h:13384
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13537
NamedDecl * Previous
Definition Sema.h:356
Location information for a TemplateArgument.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1044