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
179Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
180 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
181 bool EnteringContext, TemplateTy &TemplateResult,
182 bool &MemberOfUnknownSpecialization,
183 bool AllowTypoCorrection) {
184 assert(getLangOpts().CPlusPlus && "No template names in C!");
185
186 DeclarationName TName;
187 MemberOfUnknownSpecialization = false;
188
189 switch (Name.getKind()) {
191 TName = DeclarationName(Name.Identifier);
192 break;
193
195 TName = Context.DeclarationNames.getCXXOperatorName(
197 break;
198
200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201 break;
202
203 default:
204 return TNK_Non_template;
205 }
206
207 QualType ObjectType = ObjectTypePtr.get();
208
209 AssumedTemplateKind AssumedTemplate;
210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212 /*RequiredTemplate=*/SourceLocation(),
213 &AssumedTemplate, AllowTypoCorrection))
214 return TNK_Non_template;
215 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238 if (isa<FunctionTemplateDecl>(FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
276 R.suppressDiagnostics();
277 } else {
278 if (!D) {
279 D = getAsTemplateNameDecl(*R.begin());
280 assert(D && "unambiguous result is not a template name");
281 }
282
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (!SS.isInvalid()) {
294 NestedNameSpecifier Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296 Template);
297 }
298
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
303 R.suppressDiagnostics();
304 } else {
308 TemplateKind =
310 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
314 }
315 }
316
318 S->getTemplateParamParent() == nullptr)
319 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
320 // Recover by returning the template, even though we would never be able to
321 // substitute it.
322
323 TemplateResult = TemplateTy::make(Template);
324 return TemplateKind;
325}
326
328 SourceLocation NameLoc, CXXScopeSpec &SS,
329 ParsedTemplateTy *Template /*=nullptr*/) {
330 // We could use redeclaration lookup here, but we don't need to: the
331 // syntactic form of a deduction guide is enough to identify it even
332 // if we can't look up the template name at all.
333 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
334 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
335 /*EnteringContext*/ false))
336 return false;
337
338 if (R.empty()) return false;
339 if (R.isAmbiguous()) {
340 // FIXME: Diagnose an ambiguity if we find at least one template.
341 R.suppressDiagnostics();
342 return false;
343 }
344
345 // We only treat template-names that name type templates as valid deduction
346 // guide names.
347 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
348 if (!TD || !getAsTypeTemplateDecl(TD))
349 return false;
350
351 if (Template) {
352 TemplateName Name = Context.getQualifiedTemplateName(
353 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
354 *Template = TemplateTy::make(Name);
355 }
356 return true;
357}
358
360 SourceLocation IILoc,
361 Scope *S,
362 const CXXScopeSpec *SS,
363 TemplateTy &SuggestedTemplate,
364 TemplateNameKind &SuggestedKind) {
365 // We can't recover unless there's a dependent scope specifier preceding the
366 // template name.
367 // FIXME: Typo correction?
368 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
370 return false;
371
372 // The code is missing a 'template' keyword prior to the dependent template
373 // name.
374 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
375 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
376 Diag(IILoc, diag::err_template_kw_missing)
377 << SuggestedTemplate.get()
378 << FixItHint::CreateInsertion(IILoc, "template ");
379 SuggestedKind = TNK_Dependent_template_name;
380 return true;
381}
382
384 QualType ObjectType, bool EnteringContext,
385 RequiredTemplateKind RequiredTemplate,
387 bool AllowTypoCorrection) {
388 if (ATK)
390
391 if (SS.isInvalid())
392 return true;
393
394 Found.setTemplateNameLookup(true);
395
396 // Determine where to perform name lookup
397 DeclContext *LookupCtx = nullptr;
398 bool IsDependent = false;
399 if (!ObjectType.isNull()) {
400 // This nested-name-specifier occurs in a member access expression, e.g.,
401 // x->B::f, and we are looking into the type of the object.
402 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
403 LookupCtx = computeDeclContext(ObjectType);
404 IsDependent = !LookupCtx && ObjectType->isDependentType();
405 assert((IsDependent || !ObjectType->isIncompleteType() ||
406 !ObjectType->getAs<TagType>() ||
407 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
408 "Caller should have completed object type");
409
410 // Template names cannot appear inside an Objective-C class or object type
411 // or a vector type.
412 //
413 // FIXME: This is wrong. For example:
414 //
415 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
416 // Vec<int> vi;
417 // vi.Vec<int>::~Vec<int>();
418 //
419 // ... should be accepted but we will not treat 'Vec' as a template name
420 // here. The right thing to do would be to check if the name is a valid
421 // vector component name, and look up a template name if not. And similarly
422 // for lookups into Objective-C class and object types, where the same
423 // problem can arise.
424 if (ObjectType->isObjCObjectOrInterfaceType() ||
425 ObjectType->isVectorType()) {
426 Found.clear();
427 return false;
428 }
429 } else if (SS.isNotEmpty()) {
430 // This nested-name-specifier occurs after another nested-name-specifier,
431 // so long into the context associated with the prior nested-name-specifier.
432 LookupCtx = computeDeclContext(SS, EnteringContext);
433 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
434
435 // The declaration context must be complete.
436 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
437 return true;
438 }
439
440 bool ObjectTypeSearchedInScope = false;
441 bool AllowFunctionTemplatesInLookup = true;
442 if (LookupCtx) {
443 // Perform "qualified" name lookup into the declaration context we
444 // computed, which is either the type of the base of a member access
445 // expression or the declaration context associated with a prior
446 // nested-name-specifier.
447 LookupQualifiedName(Found, LookupCtx);
448
449 // FIXME: The C++ standard does not clearly specify what happens in the
450 // case where the object type is dependent, and implementations vary. In
451 // Clang, we treat a name after a . or -> as a template-name if lookup
452 // finds a non-dependent member or member of the current instantiation that
453 // is a type template, or finds no such members and lookup in the context
454 // of the postfix-expression finds a type template. In the latter case, the
455 // name is nonetheless dependent, and we may resolve it to a member of an
456 // unknown specialization when we come to instantiate the template.
457 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
458 }
459
460 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
461 // C++ [basic.lookup.classref]p1:
462 // In a class member access expression (5.2.5), if the . or -> token is
463 // immediately followed by an identifier followed by a <, the
464 // identifier must be looked up to determine whether the < is the
465 // beginning of a template argument list (14.2) or a less-than operator.
466 // The identifier is first looked up in the class of the object
467 // expression. If the identifier is not found, it is then looked up in
468 // the context of the entire postfix-expression and shall name a class
469 // template.
470 if (S)
471 LookupName(Found, S);
472
473 if (!ObjectType.isNull()) {
474 // FIXME: We should filter out all non-type templates here, particularly
475 // variable templates and concepts. But the exclusion of alias templates
476 // and template template parameters is a wording defect.
477 AllowFunctionTemplatesInLookup = false;
478 ObjectTypeSearchedInScope = true;
479 }
480
481 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
482 }
483
484 if (Found.isAmbiguous())
485 return false;
486
487 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
488 !RequiredTemplate.hasTemplateKeyword()) {
489 // C++2a [temp.names]p2:
490 // A name is also considered to refer to a template if it is an
491 // unqualified-id followed by a < and name lookup finds either one or more
492 // functions or finds nothing.
493 //
494 // To keep our behavior consistent, we apply the "finds nothing" part in
495 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
496 // successfully form a call to an undeclared template-id.
497 bool AllFunctions =
498 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
500 });
501 if (AllFunctions || (Found.empty() && !IsDependent)) {
502 // If lookup found any functions, or if this is a name that can only be
503 // used for a function, then strongly assume this is a function
504 // template-id.
505 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
508 Found.clear();
509 return false;
510 }
511 }
512
513 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
514 // If we did not find any names, and this is not a disambiguation, attempt
515 // to correct any typos.
516 DeclarationName Name = Found.getLookupName();
517 Found.clear();
518
519 class TemplateNameLookupValidatorCCC final
521 public:
523
524 bool ValidateCandidate(const TypoCorrection &Candidate) final {
525 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
526 !ND || !isa<TemplateDecl>(ND))
527 return false;
529 }
530
531 std::unique_ptr<CorrectionCandidateCallback> clone() final {
532 return std::make_unique<TemplateNameLookupValidatorCCC>(*this);
533 }
534 };
535
536 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
537 FilterCCC.WantTypeSpecifiers = false;
538 FilterCCC.WantExpressionKeywords = false;
539 FilterCCC.WantRemainingKeywords = false;
540 FilterCCC.WantCXXNamedCasts = true;
541 if (TypoCorrection Corrected = CorrectTypo(
542 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
543 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
544 if (auto *ND = Corrected.getFoundDecl())
545 Found.addDecl(ND);
547 if (Found.isAmbiguous()) {
548 Found.clear();
549 } else if (!Found.empty()) {
550 // Do not erase the typo-corrected result to avoid duplicated
551 // diagnostics.
552 AllowFunctionTemplatesInLookup = true;
553 Found.setLookupName(Corrected.getCorrection());
554 if (LookupCtx) {
555 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
556 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
557 Name.getAsString() == CorrectedStr;
558 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
559 << Name << LookupCtx << DroppedSpecifier
560 << SS.getRange());
561 } else {
562 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
563 }
564
565 if (Corrected.WillReplaceSpecifier()) {
566 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
567 // In order to be valid, a non-empty CXXScopeSpec needs a source
568 // range.
569 SS.MakeTrivial(Context, NNS,
570 NNS ? Found.getNameLoc() : SourceRange());
571 }
572 }
573 }
574 }
575
576 NamedDecl *ExampleLookupResult =
577 Found.empty() ? nullptr : Found.getRepresentativeDecl();
578 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
579 if (Found.empty()) {
580 if (IsDependent) {
581 Found.setNotFoundInCurrentInstantiation();
582 return false;
583 }
584
585 // If a 'template' keyword was used, a lookup that finds only non-template
586 // names is an error.
587 if (ExampleLookupResult && RequiredTemplate) {
588 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
589 << Found.getLookupName() << SS.getRange()
590 << RequiredTemplate.hasTemplateKeyword()
591 << RequiredTemplate.getTemplateKeywordLoc();
592 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
593 diag::note_template_kw_refers_to_non_template)
594 << Found.getLookupName();
595 return true;
596 }
597
598 return false;
599 }
600
601 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
603 // C++03 [basic.lookup.classref]p1:
604 // [...] If the lookup in the class of the object expression finds a
605 // template, the name is also looked up in the context of the entire
606 // postfix-expression and [...]
607 //
608 // Note: C++11 does not perform this second lookup.
609 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
611 FoundOuter.setTemplateNameLookup(true);
612 LookupName(FoundOuter, S);
613 // FIXME: We silently accept an ambiguous lookup here, in violation of
614 // [basic.lookup]/1.
615 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
616
617 NamedDecl *OuterTemplate;
618 if (FoundOuter.empty()) {
619 // - if the name is not found, the name found in the class of the
620 // object expression is used, otherwise
621 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
622 !(OuterTemplate =
623 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
624 // - if the name is found in the context of the entire
625 // postfix-expression and does not name a class template, the name
626 // found in the class of the object expression is used, otherwise
627 FoundOuter.clear();
628 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
629 // - if the name found is a class template, it must refer to the same
630 // entity as the one found in the class of the object expression,
631 // otherwise the program is ill-formed.
632 if (!Found.isSingleResult() ||
633 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
634 OuterTemplate->getCanonicalDecl()) {
635 Diag(Found.getNameLoc(),
636 diag::ext_nested_name_member_ref_lookup_ambiguous)
637 << Found.getLookupName()
638 << ObjectType;
639 Diag(Found.getRepresentativeDecl()->getLocation(),
640 diag::note_ambig_member_ref_object_type)
641 << ObjectType;
642 Diag(FoundOuter.getFoundDecl()->getLocation(),
643 diag::note_ambig_member_ref_scope);
644
645 // Recover by taking the template that we found in the object
646 // expression's type.
647 }
648 }
649 }
650
651 return false;
652}
653
657 if (TemplateName.isInvalid())
658 return;
659
660 DeclarationNameInfo NameInfo;
661 CXXScopeSpec SS;
662 LookupNameKind LookupKind;
663
664 DeclContext *LookupCtx = nullptr;
665 NamedDecl *Found = nullptr;
666 bool MissingTemplateKeyword = false;
667
668 // Figure out what name we looked up.
669 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
670 NameInfo = DRE->getNameInfo();
671 SS.Adopt(DRE->getQualifierLoc());
672 LookupKind = LookupOrdinaryName;
673 Found = DRE->getFoundDecl();
674 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
675 NameInfo = ME->getMemberNameInfo();
676 SS.Adopt(ME->getQualifierLoc());
677 LookupKind = LookupMemberName;
678 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
679 Found = ME->getMemberDecl();
680 } else if (auto *DSDRE =
681 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
682 NameInfo = DSDRE->getNameInfo();
683 SS.Adopt(DSDRE->getQualifierLoc());
684 MissingTemplateKeyword = true;
685 } else if (auto *DSME =
686 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
687 NameInfo = DSME->getMemberNameInfo();
688 SS.Adopt(DSME->getQualifierLoc());
689 MissingTemplateKeyword = true;
690 } else {
691 llvm_unreachable("unexpected kind of potential template name");
692 }
693
694 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
695 // was missing.
696 if (MissingTemplateKeyword) {
697 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
698 << NameInfo.getName() << SourceRange(Less, Greater);
699 return;
700 }
701
702 // Try to correct the name by looking for templates and C++ named casts.
703 struct TemplateCandidateFilter : CorrectionCandidateCallback {
704 Sema &S;
705 TemplateCandidateFilter(Sema &S) : S(S) {
706 WantTypeSpecifiers = false;
707 WantExpressionKeywords = false;
708 WantRemainingKeywords = false;
709 WantCXXNamedCasts = true;
710 };
711 bool ValidateCandidate(const TypoCorrection &Candidate) override {
712 if (auto *ND = Candidate.getCorrectionDecl())
713 return S.getAsTemplateNameDecl(ND);
714 return Candidate.isKeyword();
715 }
716
717 std::unique_ptr<CorrectionCandidateCallback> clone() override {
718 return std::make_unique<TemplateCandidateFilter>(*this);
719 }
720 };
721
722 DeclarationName Name = NameInfo.getName();
723 TemplateCandidateFilter CCC(*this);
724 if (TypoCorrection Corrected =
725 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
726 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
727 auto *ND = Corrected.getFoundDecl();
728 if (ND)
729 ND = getAsTemplateNameDecl(ND);
730 if (ND || Corrected.isKeyword()) {
731 if (LookupCtx) {
732 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
733 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
734 Name.getAsString() == CorrectedStr;
735 diagnoseTypo(Corrected,
736 PDiag(diag::err_non_template_in_member_template_id_suggest)
737 << Name << LookupCtx << DroppedSpecifier
738 << SS.getRange(), false);
739 } else {
740 diagnoseTypo(Corrected,
741 PDiag(diag::err_non_template_in_template_id_suggest)
742 << Name, false);
743 }
744 if (Found)
745 Diag(Found->getLocation(),
746 diag::note_non_template_in_template_id_found);
747 return;
748 }
749 }
750
751 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
752 << Name << SourceRange(Less, Greater);
753 if (Found)
754 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
755}
756
759 SourceLocation TemplateKWLoc,
760 const DeclarationNameInfo &NameInfo,
761 bool isAddressOfOperand,
762 const TemplateArgumentListInfo *TemplateArgs) {
763 if (SS.isEmpty()) {
764 // FIXME: This codepath is only used by dependent unqualified names
765 // (e.g. a dependent conversion-function-id, or operator= once we support
766 // it). It doesn't quite do the right thing, and it will silently fail if
767 // getCurrentThisType() returns null.
768 QualType ThisType = getCurrentThisType();
769 if (ThisType.isNull())
770 return ExprError();
771
773 Context, /*Base=*/nullptr, ThisType,
774 /*IsArrow=*/!Context.getLangOpts().HLSL,
775 /*OperatorLoc=*/SourceLocation(),
776 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
777 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
778 }
779 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
780}
781
784 SourceLocation TemplateKWLoc,
785 const DeclarationNameInfo &NameInfo,
786 const TemplateArgumentListInfo *TemplateArgs) {
787 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
788 if (!SS.isValid())
789 return CreateRecoveryExpr(
790 SS.getBeginLoc(),
791 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
792
794 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
795 TemplateArgs);
796}
797
799Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
800 QualType ParamType, SourceLocation Loc,
802 UnsignedOrNone PackIndex, bool Final) {
803 // The template argument itself might be an expression, in which case we just
804 // return that expression. This happens when substituting into an alias
805 // template.
806 Expr *Replacement;
808 Replacement = Arg.getAsExpr();
809 } else {
810 ExprResult result =
811 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
812 if (result.isInvalid())
813 return ExprError();
814 Replacement = result.get();
815 }
816 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
817 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
818 AssociatedDecl, ParamType, Index, PackIndex, Final);
819}
820
822 NamedDecl *Instantiation,
823 bool InstantiatedFromMember,
824 const NamedDecl *Pattern,
825 const NamedDecl *PatternDef,
827 bool Complain, bool *Unreachable) {
828 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
829 isa<VarDecl>(Instantiation));
830
831 bool IsEntityBeingDefined = false;
832 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
833 IsEntityBeingDefined = TD->isBeingDefined();
834
835 if (PatternDef && !IsEntityBeingDefined) {
836 NamedDecl *SuggestedDef = nullptr;
837 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
838 &SuggestedDef,
839 /*OnlyNeedComplete*/ false)) {
840 if (Unreachable)
841 *Unreachable = true;
842 // If we're allowed to diagnose this and recover, do so.
843 bool Recover = Complain && !isSFINAEContext();
844 if (Complain)
845 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
847 return !Recover;
848 }
849 return false;
850 }
851
852 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
853 return true;
854
855 CanQualType InstantiationTy;
856 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
857 InstantiationTy = Context.getCanonicalTagType(TD);
858 if (PatternDef) {
859 Diag(PointOfInstantiation,
860 diag::err_template_instantiate_within_definition)
861 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
862 << InstantiationTy;
863 // Not much point in noting the template declaration here, since
864 // we're lexically inside it.
865 Instantiation->setInvalidDecl();
866 } else if (InstantiatedFromMember) {
867 if (isa<FunctionDecl>(Instantiation)) {
868 Diag(PointOfInstantiation,
869 diag::err_explicit_instantiation_undefined_member)
870 << /*member function*/ 1 << Instantiation->getDeclName()
871 << Instantiation->getDeclContext();
872 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
873 } else {
874 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
875 Diag(PointOfInstantiation,
876 diag::err_implicit_instantiate_member_undefined)
877 << InstantiationTy;
878 Diag(Pattern->getLocation(), diag::note_member_declared_at);
879 }
880 } else {
881 if (isa<FunctionDecl>(Instantiation)) {
882 Diag(PointOfInstantiation,
883 diag::err_explicit_instantiation_undefined_func_template)
884 << Pattern;
885 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
886 } else if (isa<TagDecl>(Instantiation)) {
887 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
888 << (TSK != TSK_ImplicitInstantiation)
889 << InstantiationTy;
890 NoteTemplateLocation(*Pattern);
891 } else {
892 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
893 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
894 Diag(PointOfInstantiation,
895 diag::err_explicit_instantiation_undefined_var_template)
896 << Instantiation;
897 Instantiation->setInvalidDecl();
898 } else
899 Diag(PointOfInstantiation,
900 diag::err_explicit_instantiation_undefined_member)
901 << /*static data member*/ 2 << Instantiation->getDeclName()
902 << Instantiation->getDeclContext();
903 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
904 }
905 }
906
907 // In general, Instantiation isn't marked invalid to get more than one
908 // error for multiple undefined instantiations. But the code that does
909 // explicit declaration -> explicit definition conversion can't handle
910 // invalid declarations, so mark as invalid in that case.
912 Instantiation->setInvalidDecl();
913 return true;
914}
915
917 bool SupportedForCompatibility) {
918 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
919
920 // C++23 [temp.local]p6:
921 // The name of a template-parameter shall not be bound to any following.
922 // declaration whose locus is contained by the scope to which the
923 // template-parameter belongs.
924 //
925 // When MSVC compatibility is enabled, the diagnostic is always a warning
926 // by default. Otherwise, it an error unless SupportedForCompatibility is
927 // true, in which case it is a default-to-error warning.
928 unsigned DiagId =
929 getLangOpts().MSVCCompat
930 ? diag::ext_template_param_shadow
931 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
932 : diag::err_template_param_shadow);
933 const auto *ND = cast<NamedDecl>(PrevDecl);
934 Diag(Loc, DiagId) << ND->getDeclName();
936}
937
939 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
940 D = Temp->getTemplatedDecl();
941 return Temp;
942 }
943 return nullptr;
944}
945
947 SourceLocation EllipsisLoc) const {
948 assert(Kind == Template &&
949 "Only template template arguments can be pack expansions here");
950 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
951 "Template template argument pack expansion without packs");
953 Result.EllipsisLoc = EllipsisLoc;
954 return Result;
955}
956
958 const ParsedTemplateArgument &Arg) {
959
960 switch (Arg.getKind()) {
962 TypeSourceInfo *TSI;
963 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
964 if (!TSI)
965 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
967 }
968
970 Expr *E = Arg.getAsExpr();
971 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
972 }
973
976 TemplateArgument TArg;
977 if (Arg.getEllipsisLoc().isValid())
978 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
979 else
980 TArg = Template;
981 return TemplateArgumentLoc(
982 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
984 Arg.getNameLoc(), Arg.getEllipsisLoc());
985 }
986 }
987
988 llvm_unreachable("Unhandled parsed template argument");
989}
990
992 TemplateArgumentListInfo &TemplateArgs) {
993 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
994 TemplateArgs.addArgument(translateTemplateArgument(*this,
995 TemplateArgsIn[I]));
996}
997
999 SourceLocation Loc,
1000 const IdentifierInfo *Name) {
1001 NamedDecl *PrevDecl =
1002 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
1004 if (PrevDecl && PrevDecl->isTemplateParameter())
1005 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1006}
1007
1009 TypeSourceInfo *TInfo;
1010 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1011 if (T.isNull())
1012 return ParsedTemplateArgument();
1013 assert(TInfo && "template argument with no location");
1014
1015 // If we might have formed a deduced template specialization type, convert
1016 // it to a template template argument.
1017 if (getLangOpts().CPlusPlus17) {
1018 TypeLoc TL = TInfo->getTypeLoc();
1019 SourceLocation EllipsisLoc;
1020 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1021 EllipsisLoc = PET.getEllipsisLoc();
1022 TL = PET.getPatternLoc();
1023 }
1024
1025 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1026 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1027 CXXScopeSpec SS;
1028 SS.Adopt(DTST.getQualifierLoc());
1029 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1030 TemplateTy::make(Name),
1031 DTST.getTemplateNameLoc());
1032 if (EllipsisLoc.isValid())
1033 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1034 return Result;
1035 }
1036 }
1037
1038 // This is a normal type template argument. Note, if the type template
1039 // argument is an injected-class-name for a template, it has a dual nature
1040 // and can be used as either a type or a template. We handle that in
1041 // convertTypeTemplateArgumentToTemplate.
1043 ParsedType.get().getAsOpaquePtr(),
1044 TInfo->getTypeLoc().getBeginLoc());
1045}
1046
1048 SourceLocation EllipsisLoc,
1049 SourceLocation KeyLoc,
1050 IdentifierInfo *ParamName,
1051 SourceLocation ParamNameLoc,
1052 unsigned Depth, unsigned Position,
1053 SourceLocation EqualLoc,
1054 ParsedType DefaultArg,
1055 bool HasTypeConstraint) {
1056 assert(S->isTemplateParamScope() &&
1057 "Template type parameter not in template parameter scope!");
1058
1059 bool IsParameterPack = EllipsisLoc.isValid();
1061 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1062 KeyLoc, ParamNameLoc, Depth, Position,
1063 ParamName, Typename, IsParameterPack,
1064 HasTypeConstraint);
1065 Param->setAccess(AS_public);
1066
1067 if (Param->isParameterPack())
1068 if (auto *CSI = getEnclosingLambdaOrBlock())
1069 CSI->LocalPacks.push_back(Param);
1070
1071 if (ParamName) {
1072 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1073
1074 // Add the template parameter into the current scope.
1075 S->AddDecl(Param);
1076 IdResolver.AddDecl(Param);
1077 }
1078
1079 // C++0x [temp.param]p9:
1080 // A default template-argument may be specified for any kind of
1081 // template-parameter that is not a template parameter pack.
1082 if (DefaultArg && IsParameterPack) {
1083 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1084 DefaultArg = nullptr;
1085 }
1086
1087 // Handle the default argument, if provided.
1088 if (DefaultArg) {
1089 TypeSourceInfo *DefaultTInfo;
1090 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1091
1092 assert(DefaultTInfo && "expected source information for type");
1093
1094 // Check for unexpanded parameter packs.
1095 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1097 return Param;
1098
1099 // Check the template argument itself.
1100 if (CheckTemplateArgument(DefaultTInfo)) {
1101 Param->setInvalidDecl();
1102 return Param;
1103 }
1104
1105 Param->setDefaultArgument(
1106 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1107 }
1108
1109 return Param;
1110}
1111
1112/// Convert the parser's template argument list representation into our form.
1115 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1116 TemplateId.RAngleLoc);
1117 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1118 TemplateId.NumArgs);
1119 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1120 return TemplateArgs;
1121}
1122
1124
1125 TemplateName TN = TypeConstr->Template.get();
1126 NamedDecl *CD = nullptr;
1127 bool IsTypeConcept = false;
1128 bool RequiresArguments = false;
1129 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1130 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1131 RequiresArguments =
1132 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1133 CD = TTP;
1134 } else {
1135 CD = TN.getAsTemplateDecl();
1136 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1137 RequiresArguments = cast<ConceptDecl>(CD)
1138 ->getTemplateParameters()
1139 ->getMinRequiredArguments() > 1;
1140 }
1141
1142 // C++2a [temp.param]p4:
1143 // [...] The concept designated by a type-constraint shall be a type
1144 // concept ([temp.concept]).
1145 if (!IsTypeConcept) {
1146 Diag(TypeConstr->TemplateNameLoc,
1147 diag::err_type_constraint_non_type_concept);
1148 return true;
1149 }
1150
1151 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1152 return true;
1153
1154 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1155
1156 if (!WereArgsSpecified && RequiresArguments) {
1157 Diag(TypeConstr->TemplateNameLoc,
1158 diag::err_type_constraint_missing_arguments)
1159 << CD;
1160 return true;
1161 }
1162 return false;
1163}
1164
1166 TemplateIdAnnotation *TypeConstr,
1167 TemplateTypeParmDecl *ConstrainedParameter,
1168 SourceLocation EllipsisLoc) {
1169 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1170 false);
1171}
1172
1174 TemplateIdAnnotation *TypeConstr,
1175 TemplateTypeParmDecl *ConstrainedParameter,
1176 SourceLocation EllipsisLoc,
1177 bool AllowUnexpandedPack) {
1178
1179 if (CheckTypeConstraint(TypeConstr))
1180 return true;
1181
1182 TemplateName TN = TypeConstr->Template.get();
1185
1186 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1187 TypeConstr->TemplateNameLoc);
1188
1189 TemplateArgumentListInfo TemplateArgs;
1190 if (TypeConstr->LAngleLoc.isValid()) {
1191 TemplateArgs =
1192 makeTemplateArgumentListInfo(*this, *TypeConstr);
1193
1194 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1195 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1197 return true;
1198 }
1199 }
1200 }
1201 return AttachTypeConstraint(
1203 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1204 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1205 ConstrainedParameter, EllipsisLoc);
1206}
1207
1208template <typename ArgumentLocAppender>
1211 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1212 SourceLocation RAngleLoc, QualType ConstrainedType,
1213 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1214 SourceLocation EllipsisLoc) {
1215
1216 TemplateArgumentListInfo ConstraintArgs;
1217 ConstraintArgs.addArgument(
1219 /*NTTPType=*/QualType(), ParamNameLoc));
1220
1221 ConstraintArgs.setRAngleLoc(RAngleLoc);
1222 ConstraintArgs.setLAngleLoc(LAngleLoc);
1223 Appender(ConstraintArgs);
1224
1225 // C++2a [temp.param]p4:
1226 // [...] This constraint-expression E is called the immediately-declared
1227 // constraint of T. [...]
1228 CXXScopeSpec SS;
1229 SS.Adopt(NS);
1230 ExprResult ImmediatelyDeclaredConstraint;
1231 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1232 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1233 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1234 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1235 /*DoCheckConstraintSatisfaction=*/
1237 }
1238 // We have a template template parameter
1239 else {
1240 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1241 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1242 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1243 }
1244 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1245 return ImmediatelyDeclaredConstraint;
1246
1247 // C++2a [temp.param]p4:
1248 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1249 //
1250 // We have the following case:
1251 //
1252 // template<typename T> concept C1 = true;
1253 // template<C1... T> struct s1;
1254 //
1255 // The constraint: (C1<T> && ...)
1256 //
1257 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1258 // any unqualified lookups for 'operator&&' here.
1259 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1260 /*LParenLoc=*/SourceLocation(),
1261 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1262 EllipsisLoc, /*RHS=*/nullptr,
1263 /*RParenLoc=*/SourceLocation(),
1264 /*NumExpansions=*/std::nullopt);
1265}
1266
1268 DeclarationNameInfo NameInfo,
1269 TemplateDecl *NamedConcept,
1270 NamedDecl *FoundDecl,
1271 const TemplateArgumentListInfo *TemplateArgs,
1272 TemplateTypeParmDecl *ConstrainedParameter,
1273 SourceLocation EllipsisLoc) {
1274 // C++2a [temp.param]p4:
1275 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1276 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1277 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1279 *TemplateArgs) : nullptr;
1280
1281 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1282
1283 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1284 *this, NS, NameInfo, NamedConcept, FoundDecl,
1285 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1286 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1287 ParamAsArgument, ConstrainedParameter->getLocation(),
1288 [&](TemplateArgumentListInfo &ConstraintArgs) {
1289 if (TemplateArgs)
1290 for (const auto &ArgLoc : TemplateArgs->arguments())
1291 ConstraintArgs.addArgument(ArgLoc);
1292 },
1293 EllipsisLoc);
1294 if (ImmediatelyDeclaredConstraint.isInvalid())
1295 return true;
1296
1297 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1298 /*TemplateKWLoc=*/SourceLocation{},
1299 /*ConceptNameInfo=*/NameInfo,
1300 /*FoundDecl=*/FoundDecl,
1301 /*NamedConcept=*/NamedConcept,
1302 /*ArgsWritten=*/ArgsAsWritten);
1303 ConstrainedParameter->setTypeConstraint(
1304 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1305 return false;
1306}
1307
1309 NonTypeTemplateParmDecl *NewConstrainedParm,
1310 NonTypeTemplateParmDecl *OrigConstrainedParm,
1311 SourceLocation EllipsisLoc) {
1312 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1314 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1315 diag::err_unsupported_placeholder_constraint)
1316 << NewConstrainedParm->getTypeSourceInfo()
1317 ->getTypeLoc()
1318 .getSourceRange();
1319 return true;
1320 }
1321 // FIXME: Concepts: This should be the type of the placeholder, but this is
1322 // unclear in the wording right now.
1323 DeclRefExpr *Ref =
1324 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1325 VK_PRValue, OrigConstrainedParm->getLocation());
1326 if (!Ref)
1327 return true;
1328 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1330 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1332 OrigConstrainedParm->getLocation(),
1333 [&](TemplateArgumentListInfo &ConstraintArgs) {
1334 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1335 ConstraintArgs.addArgument(TL.getArgLoc(I));
1336 },
1337 EllipsisLoc);
1338 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1339 !ImmediatelyDeclaredConstraint.isUsable())
1340 return true;
1341
1342 NewConstrainedParm->setPlaceholderTypeConstraint(
1343 ImmediatelyDeclaredConstraint.get());
1344 return false;
1345}
1346
1348 SourceLocation Loc) {
1349 if (TSI->getType()->isUndeducedType()) {
1350 // C++17 [temp.dep.expr]p3:
1351 // An id-expression is type-dependent if it contains
1352 // - an identifier associated by name lookup with a non-type
1353 // template-parameter declared with a type that contains a
1354 // placeholder type (7.1.7.4),
1356 if (!NewTSI)
1357 return QualType();
1358 TSI = NewTSI;
1359 }
1360
1361 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1362}
1363
1365 if (T->isDependentType())
1366 return false;
1367
1368 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1369 return true;
1370
1371 if (T->isStructuralType())
1372 return false;
1373
1374 // Structural types are required to be object types or lvalue references.
1375 if (T->isRValueReferenceType()) {
1376 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1377 return true;
1378 }
1379
1380 // Don't mention structural types in our diagnostic prior to C++20. Also,
1381 // there's not much more we can say about non-scalar non-class types --
1382 // because we can't see functions or arrays here, those can only be language
1383 // extensions.
1384 if (!getLangOpts().CPlusPlus20 ||
1385 (!T->isScalarType() && !T->isRecordType())) {
1386 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1387 return true;
1388 }
1389
1390 // Structural types are required to be literal types.
1391 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1392 return true;
1393
1394 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1395
1396 // Drill down into the reason why the class is non-structural.
1397 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1398 // All members are required to be public and non-mutable, and can't be of
1399 // rvalue reference type. Check these conditions first to prefer a "local"
1400 // reason over a more distant one.
1401 for (const FieldDecl *FD : RD->fields()) {
1402 if (FD->getAccess() != AS_public) {
1403 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1404 return true;
1405 }
1406 if (FD->isMutable()) {
1407 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1408 return true;
1409 }
1410 if (FD->getType()->isRValueReferenceType()) {
1411 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1412 << T;
1413 return true;
1414 }
1415 }
1416
1417 // All bases are required to be public.
1418 for (const auto &BaseSpec : RD->bases()) {
1419 if (BaseSpec.getAccessSpecifier() != AS_public) {
1420 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1421 << T << 1;
1422 return true;
1423 }
1424 }
1425
1426 // All subobjects are required to be of structural types.
1427 SourceLocation SubLoc;
1428 QualType SubType;
1429 int Kind = -1;
1430
1431 for (const FieldDecl *FD : RD->fields()) {
1432 QualType T = Context.getBaseElementType(FD->getType());
1433 if (!T->isStructuralType()) {
1434 SubLoc = FD->getLocation();
1435 SubType = T;
1436 Kind = 0;
1437 break;
1438 }
1439 }
1440
1441 if (Kind == -1) {
1442 for (const auto &BaseSpec : RD->bases()) {
1443 QualType T = BaseSpec.getType();
1444 if (!T->isStructuralType()) {
1445 SubLoc = BaseSpec.getBaseTypeLoc();
1446 SubType = T;
1447 Kind = 1;
1448 break;
1449 }
1450 }
1451 }
1452
1453 assert(Kind != -1 && "couldn't find reason why type is not structural");
1454 Diag(SubLoc, diag::note_not_structural_subobject)
1455 << T << Kind << SubType;
1456 T = SubType;
1457 RD = T->getAsCXXRecordDecl();
1458 }
1459
1460 return true;
1461}
1462
1464 SourceLocation Loc) {
1465 // We don't allow variably-modified types as the type of non-type template
1466 // parameters.
1467 if (T->isVariablyModifiedType()) {
1468 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1469 << T;
1470 return QualType();
1471 }
1472
1473 if (T->isBlockPointerType()) {
1474 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1475 return QualType();
1476 }
1477
1478 // C++ [temp.param]p4:
1479 //
1480 // A non-type template-parameter shall have one of the following
1481 // (optionally cv-qualified) types:
1482 //
1483 // -- integral or enumeration type,
1484 if (T->isIntegralOrEnumerationType() ||
1485 // -- pointer to object or pointer to function,
1486 T->isPointerType() ||
1487 // -- lvalue reference to object or lvalue reference to function,
1488 T->isLValueReferenceType() ||
1489 // -- pointer to member,
1490 T->isMemberPointerType() ||
1491 // -- std::nullptr_t, or
1492 T->isNullPtrType() ||
1493 // -- a type that contains a placeholder type.
1494 T->isUndeducedType()) {
1495 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1496 // are ignored when determining its type.
1497 return T.getUnqualifiedType();
1498 }
1499
1500 // C++ [temp.param]p8:
1501 //
1502 // A non-type template-parameter of type "array of T" or
1503 // "function returning T" is adjusted to be of type "pointer to
1504 // T" or "pointer to function returning T", respectively.
1505 if (T->isArrayType() || T->isFunctionType())
1506 return Context.getDecayedType(T);
1507
1508 // If T is a dependent type, we can't do the check now, so we
1509 // assume that it is well-formed. Note that stripping off the
1510 // qualifiers here is not really correct if T turns out to be
1511 // an array type, but we'll recompute the type everywhere it's
1512 // used during instantiation, so that should be OK. (Using the
1513 // qualified type is equally wrong.)
1514 if (T->isDependentType())
1515 return T.getUnqualifiedType();
1516
1517 // C++20 [temp.param]p6:
1518 // -- a structural type
1519 if (RequireStructuralType(T, Loc))
1520 return QualType();
1521
1522 if (!getLangOpts().CPlusPlus20) {
1523 // FIXME: Consider allowing structural types as an extension in C++17. (In
1524 // earlier language modes, the template argument evaluation rules are too
1525 // inflexible.)
1526 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1527 return QualType();
1528 }
1529
1530 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1531 return T.getUnqualifiedType();
1532}
1533
1535 unsigned Depth,
1536 unsigned Position,
1537 SourceLocation EqualLoc,
1538 Expr *Default) {
1540
1541 // Check that we have valid decl-specifiers specified.
1542 auto CheckValidDeclSpecifiers = [this, &D] {
1543 // C++ [temp.param]
1544 // p1
1545 // template-parameter:
1546 // ...
1547 // parameter-declaration
1548 // p2
1549 // ... A storage class shall not be specified in a template-parameter
1550 // declaration.
1551 // [dcl.typedef]p1:
1552 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1553 // of a parameter-declaration
1554 const DeclSpec &DS = D.getDeclSpec();
1555 auto EmitDiag = [this](SourceLocation Loc) {
1556 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1558 };
1560 EmitDiag(DS.getStorageClassSpecLoc());
1561
1563 EmitDiag(DS.getThreadStorageClassSpecLoc());
1564
1565 // [dcl.inline]p1:
1566 // The inline specifier can be applied only to the declaration or
1567 // definition of a variable or function.
1568
1569 if (DS.isInlineSpecified())
1570 EmitDiag(DS.getInlineSpecLoc());
1571
1572 // [dcl.constexpr]p1:
1573 // The constexpr specifier shall be applied only to the definition of a
1574 // variable or variable template or the declaration of a function or
1575 // function template.
1576
1577 if (DS.hasConstexprSpecifier())
1578 EmitDiag(DS.getConstexprSpecLoc());
1579
1580 // [dcl.fct.spec]p1:
1581 // Function-specifiers can be used only in function declarations.
1582
1583 if (DS.isVirtualSpecified())
1584 EmitDiag(DS.getVirtualSpecLoc());
1585
1586 if (DS.hasExplicitSpecifier())
1587 EmitDiag(DS.getExplicitSpecLoc());
1588
1589 if (DS.isNoreturnSpecified())
1590 EmitDiag(DS.getNoreturnSpecLoc());
1591 };
1592
1593 CheckValidDeclSpecifiers();
1594
1595 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1596 if (isa<AutoType>(T))
1598 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1599 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1600
1601 assert(S->isTemplateParamScope() &&
1602 "Non-type template parameter not in template parameter scope!");
1603 bool Invalid = false;
1604
1606 if (T.isNull()) {
1607 T = Context.IntTy; // Recover with an 'int' type.
1608 Invalid = true;
1609 }
1610
1612
1613 const IdentifierInfo *ParamName = D.getIdentifier();
1614 bool IsParameterPack = D.hasEllipsis();
1616 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1617 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1618 TInfo);
1619 Param->setAccess(AS_public);
1620
1622 if (TL.isConstrained()) {
1623 if (D.getEllipsisLoc().isInvalid() &&
1624 T->containsUnexpandedParameterPack()) {
1625 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1626 for (auto &Loc :
1627 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1630 }
1631 if (!Invalid &&
1632 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1633 Invalid = true;
1634 }
1635
1636 if (Invalid)
1637 Param->setInvalidDecl();
1638
1639 if (Param->isParameterPack())
1640 if (auto *CSI = getEnclosingLambdaOrBlock())
1641 CSI->LocalPacks.push_back(Param);
1642
1643 if (ParamName) {
1645 ParamName);
1646
1647 // Add the template parameter into the current scope.
1648 S->AddDecl(Param);
1649 IdResolver.AddDecl(Param);
1650 }
1651
1652 // C++0x [temp.param]p9:
1653 // A default template-argument may be specified for any kind of
1654 // template-parameter that is not a template parameter pack.
1655 if (Default && IsParameterPack) {
1656 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1657 Default = nullptr;
1658 }
1659
1660 // Check the well-formedness of the default template argument, if provided.
1661 if (Default) {
1662 // Check for unexpanded parameter packs.
1664 return Param;
1665
1666 Param->setDefaultArgument(
1668 TemplateArgument(Default, /*IsCanonical=*/false),
1669 QualType(), SourceLocation()));
1670 }
1671
1672 return Param;
1673}
1674
1675/// ActOnTemplateTemplateParameter - Called when a C++ template template
1676/// parameter (e.g. T in template <template <typename> class T> class array)
1677/// has been parsed. S is the current scope.
1679 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1680 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1681 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1682 unsigned Position, SourceLocation EqualLoc,
1684 assert(S->isTemplateParamScope() &&
1685 "Template template parameter not in template parameter scope!");
1686
1687 bool IsParameterPack = EllipsisLoc.isValid();
1688
1689 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1690 if (Params->size() == 0) {
1691 Diag(Loc, diag::err_template_template_parm_no_parms)
1692 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1693
1694 // Recover as if there was a type template parameter pack.
1695 SmallVector<NamedDecl *, 4> ParamDecls;
1696 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1697 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1698 Depth + 1, 0, /*Id=*/nullptr,
1699 /*Typename=*/false, /*ParameterPack=*/true));
1701 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1702 Params->getRAngleLoc(), Params->getRequiresClause());
1703 }
1704
1705 bool Invalid = false;
1707 Params,
1708 /*OldParams=*/nullptr,
1709 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1710 Invalid = true;
1711
1712 // Construct the parameter object.
1714 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1715 IsParameterPack, Name, Kind, Typename, Params);
1716 Param->setAccess(AS_public);
1717
1718 if (Param->isParameterPack())
1719 if (auto *LSI = getEnclosingLambdaOrBlock())
1720 LSI->LocalPacks.push_back(Param);
1721
1722 // If the template template parameter has a name, then link the identifier
1723 // into the scope and lookup mechanisms.
1724 if (Name) {
1725 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1726
1727 S->AddDecl(Param);
1728 IdResolver.AddDecl(Param);
1729 }
1730
1731 if (Invalid)
1732 Param->setInvalidDecl();
1733
1734 // C++0x [temp.param]p9:
1735 // A default template-argument may be specified for any kind of
1736 // template-parameter that is not a template parameter pack.
1737 if (IsParameterPack && !Default.isInvalid()) {
1738 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1740 }
1741
1742 if (!Default.isInvalid()) {
1743 // Check only that we have a template template argument. We don't want to
1744 // try to check well-formedness now, because our template template parameter
1745 // might have dependent types in its template parameters, which we wouldn't
1746 // be able to match now.
1747 //
1748 // If none of the template template parameter's template arguments mention
1749 // other template parameters, we could actually perform more checking here.
1750 // However, it isn't worth doing.
1752 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1753 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1754 << DefaultArg.getSourceRange();
1755 return Param;
1756 }
1757
1758 TemplateName Name =
1761 if (Template &&
1763 return Param;
1764 }
1765
1766 // Check for unexpanded parameter packs.
1768 DefaultArg.getArgument().getAsTemplate(),
1770 return Param;
1771
1772 Param->setDefaultArgument(Context, DefaultArg);
1773 }
1774
1775 return Param;
1776}
1777
1778namespace {
1779class ConstraintRefersToContainingTemplateChecker
1781 using inherited = ConstDynamicRecursiveASTVisitor;
1782 bool Result = false;
1783 const FunctionDecl *Friend = nullptr;
1784 unsigned TemplateDepth = 0;
1785
1786 // Check a record-decl that we've seen to see if it is a lexical parent of the
1787 // Friend, likely because it was referred to without its template arguments.
1788 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1789 CheckingRD = CheckingRD->getMostRecentDecl();
1790 if (!CheckingRD->isTemplated())
1791 return true;
1792
1793 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1794 DC && !DC->isFileContext(); DC = DC->getParent())
1795 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1796 if (CheckingRD == RD->getMostRecentDecl()) {
1797 Result = true;
1798 return false;
1799 }
1800
1801 return true;
1802 }
1803
1804 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1805 if (D->getDepth() < TemplateDepth)
1806 Result = true;
1807
1808 // Necessary because the type of the NTTP might be what refers to the parent
1809 // constriant.
1810 return TraverseType(D->getType());
1811 }
1812
1813public:
1814 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1815 unsigned TemplateDepth)
1816 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1817
1818 bool getResult() const { return Result; }
1819
1820 // This should be the only template parm type that we have to deal with.
1821 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1822 // FunctionParmPackExpr are all partially substituted, which cannot happen
1823 // with concepts at this point in translation.
1824 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1825 if (Type->getDecl()->getDepth() < TemplateDepth) {
1826 Result = true;
1827 return false;
1828 }
1829 return true;
1830 }
1831
1832 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1833 return TraverseDecl(E->getDecl());
1834 }
1835
1836 bool TraverseTypedefType(const TypedefType *TT,
1837 bool /*TraverseQualifier*/) override {
1838 return TraverseType(TT->desugar());
1839 }
1840
1841 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1842 // We don't care about TypeLocs. So traverse Types instead.
1843 return TraverseType(TL.getType(), TraverseQualifier);
1844 }
1845
1846 bool VisitTagType(const TagType *T) override {
1847 return TraverseDecl(T->getDecl());
1848 }
1849
1850 bool TraverseDecl(const Decl *D) override {
1851 assert(D);
1852 // FIXME : This is possibly an incomplete list, but it is unclear what other
1853 // Decl kinds could be used to refer to the template parameters. This is a
1854 // best guess so far based on examples currently available, but the
1855 // unreachable should catch future instances/cases.
1856 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1857 return TraverseType(TD->getUnderlyingType());
1858 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1859 return CheckNonTypeTemplateParmDecl(NTTPD);
1860 if (auto *VD = dyn_cast<ValueDecl>(D))
1861 return TraverseType(VD->getType());
1862 if (isa<TemplateDecl>(D))
1863 return true;
1864 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1865 return CheckIfContainingRecord(RD);
1866
1868 // No direct types to visit here I believe.
1869 } else
1870 llvm_unreachable("Don't know how to handle this declaration type yet");
1871 return true;
1872 }
1873};
1874} // namespace
1875
1877 const FunctionDecl *Friend, unsigned TemplateDepth,
1878 const Expr *Constraint) {
1879 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1880 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1881 Checker.TraverseStmt(Constraint);
1882 return Checker.getResult();
1883}
1884
1887 SourceLocation ExportLoc,
1888 SourceLocation TemplateLoc,
1889 SourceLocation LAngleLoc,
1890 ArrayRef<NamedDecl *> Params,
1891 SourceLocation RAngleLoc,
1892 Expr *RequiresClause) {
1893 if (ExportLoc.isValid())
1894 Diag(ExportLoc, diag::warn_template_export_unsupported);
1895
1896 for (NamedDecl *P : Params)
1898
1899 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1900 llvm::ArrayRef(Params), RAngleLoc,
1901 RequiresClause);
1902}
1903
1905 const CXXScopeSpec &SS) {
1906 if (SS.isSet())
1907 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1908}
1909
1910// Returns the template parameter list with all default template argument
1911// information.
1913 // Make sure we get the template parameter list from the most
1914 // recent declaration, since that is the only one that is guaranteed to
1915 // have all the default template argument information.
1916 Decl *D = TD->getMostRecentDecl();
1917 // C++11 N3337 [temp.param]p12:
1918 // A default template argument shall not be specified in a friend class
1919 // template declaration.
1920 //
1921 // Skip past friend *declarations* because they are not supposed to contain
1922 // default template arguments. Moreover, these declarations may introduce
1923 // template parameters living in different template depths than the
1924 // corresponding template parameters in TD, causing unmatched constraint
1925 // substitution.
1926 //
1927 // FIXME: Diagnose such cases within a class template:
1928 // template <class T>
1929 // struct S {
1930 // template <class = void> friend struct C;
1931 // };
1932 // template struct S<int>;
1934 D->getPreviousDecl())
1935 D = D->getPreviousDecl();
1936 return cast<TemplateDecl>(D)->getTemplateParameters();
1937}
1938
1940 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1941 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1942 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1943 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1944 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1945 TemplateParameterList **OuterTemplateParamLists,
1946 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1947 assert(TemplateParams && TemplateParams->size() > 0 &&
1948 "No template parameters");
1949 assert(TUK != TagUseKind::Reference &&
1950 "Can only declare or define class templates");
1951 bool Invalid = false;
1952
1953 // Check that we can declare a template here.
1954 if (CheckTemplateDeclScope(S, TemplateParams))
1955 return true;
1956
1958 assert(Kind != TagTypeKind::Enum &&
1959 "can't build template of enumerated type");
1960
1961 // There is no such thing as an unnamed class template.
1962 if (!Name) {
1963 Diag(KWLoc, diag::err_template_unnamed_class);
1964 return true;
1965 }
1966
1967 // Find any previous declaration with this name. For a friend with no
1968 // scope explicitly specified, we only look for tag declarations (per
1969 // C++11 [basic.lookup.elab]p2).
1970 DeclContext *SemanticContext;
1971 LookupResult Previous(*this, Name, NameLoc,
1972 (SS.isEmpty() && TUK == TagUseKind::Friend)
1976 if (SS.isNotEmpty() && !SS.isInvalid()) {
1977 SemanticContext = computeDeclContext(SS, true);
1978 if (!SemanticContext) {
1979 // FIXME: Horrible, horrible hack! We can't currently represent this
1980 // in the AST, and historically we have just ignored such friend
1981 // class templates, so don't complain here.
1982 Diag(NameLoc, TUK == TagUseKind::Friend
1983 ? diag::warn_template_qualified_friend_ignored
1984 : diag::err_template_qualified_declarator_no_match)
1985 << SS.getScopeRep() << SS.getRange();
1986 return TUK != TagUseKind::Friend;
1987 }
1988
1989 if (RequireCompleteDeclContext(SS, SemanticContext))
1990 return true;
1991
1992 // If we're adding a template to a dependent context, we may need to
1993 // rebuilding some of the types used within the template parameter list,
1994 // now that we know what the current instantiation is.
1995 if (SemanticContext->isDependentContext()) {
1996 ContextRAII SavedContext(*this, SemanticContext);
1998 Invalid = true;
1999 }
2000
2001 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2002 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2003 /*TemplateId=*/nullptr,
2004 IsMemberSpecialization))
2005 return true;
2006
2007 LookupQualifiedName(Previous, SemanticContext);
2008 } else {
2009 SemanticContext = CurContext;
2010
2011 // C++14 [class.mem]p14:
2012 // If T is the name of a class, then each of the following shall have a
2013 // name different from T:
2014 // -- every member template of class T
2015 if (TUK != TagUseKind::Friend &&
2016 DiagnoseClassNameShadow(SemanticContext,
2017 DeclarationNameInfo(Name, NameLoc)))
2018 return true;
2019
2020 LookupName(Previous, S);
2021 }
2022
2023 if (Previous.isAmbiguous())
2024 return true;
2025
2026 // Let the template parameter scope enter the lookup chain of the current
2027 // class template. For example, given
2028 //
2029 // namespace ns {
2030 // template <class> bool Param = false;
2031 // template <class T> struct N;
2032 // }
2033 //
2034 // template <class Param> struct ns::N { void foo(Param); };
2035 //
2036 // When we reference Param inside the function parameter list, our name lookup
2037 // chain for it should be like:
2038 // FunctionScope foo
2039 // -> RecordScope N
2040 // -> TemplateParamScope (where we will find Param)
2041 // -> NamespaceScope ns
2042 //
2043 // See also CppLookupName().
2044 if (S->isTemplateParamScope())
2045 EnterTemplatedContext(S, SemanticContext);
2046
2047 NamedDecl *PrevDecl = nullptr;
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050
2051 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2052 // Maybe we will complain about the shadowed template parameter.
2053 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2054 // Just pretend that we didn't see the previous declaration.
2055 PrevDecl = nullptr;
2056 }
2057
2058 // If there is a previous declaration with the same name, check
2059 // whether this is a valid redeclaration.
2060 ClassTemplateDecl *PrevClassTemplate =
2061 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2062
2063 // We may have found the injected-class-name of a class template,
2064 // class template partial specialization, or class template specialization.
2065 // In these cases, grab the template that is being defined or specialized.
2066 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2067 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2068 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2069 PrevClassTemplate
2070 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2071 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2072 PrevClassTemplate
2074 ->getSpecializedTemplate();
2075 }
2076 }
2077
2078 if (TUK == TagUseKind::Friend) {
2079 // C++ [namespace.memdef]p3:
2080 // [...] When looking for a prior declaration of a class or a function
2081 // declared as a friend, and when the name of the friend class or
2082 // function is neither a qualified name nor a template-id, scopes outside
2083 // the innermost enclosing namespace scope are not considered.
2084 if (!SS.isSet()) {
2085 DeclContext *OutermostContext = CurContext;
2086 while (!OutermostContext->isFileContext())
2087 OutermostContext = OutermostContext->getLookupParent();
2088
2089 if (PrevDecl &&
2090 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2091 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2092 SemanticContext = PrevDecl->getDeclContext();
2093 } else {
2094 // Declarations in outer scopes don't matter. However, the outermost
2095 // context we computed is the semantic context for our new
2096 // declaration.
2097 PrevDecl = PrevClassTemplate = nullptr;
2098 SemanticContext = OutermostContext;
2099
2100 // Check that the chosen semantic context doesn't already contain a
2101 // declaration of this name as a non-tag type.
2103 DeclContext *LookupContext = SemanticContext;
2104 while (LookupContext->isTransparentContext())
2105 LookupContext = LookupContext->getLookupParent();
2106 LookupQualifiedName(Previous, LookupContext);
2107
2108 if (Previous.isAmbiguous())
2109 return true;
2110
2111 if (Previous.begin() != Previous.end())
2112 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2113 }
2114 }
2115 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2116 SemanticContext, S, SS.isValid()))
2117 PrevDecl = PrevClassTemplate = nullptr;
2118
2119 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2120 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2121 if (SS.isEmpty() &&
2122 !(PrevClassTemplate &&
2123 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2124 SemanticContext->getRedeclContext()))) {
2125 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2126 Diag(Shadow->getTargetDecl()->getLocation(),
2127 diag::note_using_decl_target);
2128 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2129 // Recover by ignoring the old declaration.
2130 PrevDecl = PrevClassTemplate = nullptr;
2131 }
2132 }
2133
2134 if (PrevClassTemplate) {
2135 // Ensure that the template parameter lists are compatible. Skip this check
2136 // for a friend in a dependent context: the template parameter list itself
2137 // could be dependent.
2138 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2140 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2141 : CurContext,
2142 CurContext, KWLoc),
2143 TemplateParams, PrevClassTemplate,
2144 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2146 return true;
2147
2148 // C++ [temp.class]p4:
2149 // In a redeclaration, partial specialization, explicit
2150 // specialization or explicit instantiation of a class template,
2151 // the class-key shall agree in kind with the original class
2152 // template declaration (7.1.5.3).
2153 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2155 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2156 Diag(KWLoc, diag::err_use_with_wrong_tag)
2157 << Name
2158 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2159 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2160 Kind = PrevRecordDecl->getTagKind();
2161 }
2162
2163 // Check for redefinition of this class template.
2164 if (TUK == TagUseKind::Definition) {
2165 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2166 // If we have a prior definition that is not visible, treat this as
2167 // simply making that previous definition visible.
2168 NamedDecl *Hidden = nullptr;
2169 bool HiddenDefVisible = false;
2170 if (SkipBody &&
2171 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2172 SkipBody->ShouldSkip = true;
2173 SkipBody->Previous = Def;
2174 if (!HiddenDefVisible && Hidden) {
2175 auto *Tmpl =
2176 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2177 assert(Tmpl && "original definition of a class template is not a "
2178 "class template?");
2181 }
2182 } else {
2183 Diag(NameLoc, diag::err_redefinition) << Name;
2184 Diag(Def->getLocation(), diag::note_previous_definition);
2185 // FIXME: Would it make sense to try to "forget" the previous
2186 // definition, as part of error recovery?
2187 return true;
2188 }
2189 }
2190 }
2191 } else if (PrevDecl) {
2192 // C++ [temp]p5:
2193 // A class template shall not have the same name as any other
2194 // template, class, function, object, enumeration, enumerator,
2195 // namespace, or type in the same scope (3.3), except as specified
2196 // in (14.5.4).
2197 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2198 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2199 return true;
2200 }
2201
2202 // Check the template parameter list of this declaration, possibly
2203 // merging in the template parameter list from the previous class
2204 // template declaration. Skip this check for a friend in a dependent
2205 // context, because the template parameter list might be dependent.
2206 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2208 TemplateParams,
2209 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2210 : nullptr,
2211 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2212 SemanticContext->isDependentContext())
2215 : TPC_Other,
2216 SkipBody))
2217 Invalid = true;
2218
2219 if (SS.isSet()) {
2220 // If the name of the template was qualified, we must be defining the
2221 // template out-of-line.
2222 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2223 return Diag(NameLoc, TUK == TagUseKind::Friend
2224 ? diag::err_friend_decl_does_not_match
2225 : diag::err_member_decl_does_not_match)
2226 << Name << SemanticContext << /*IsDefinition*/ true
2227 << SS.getRange();
2228 }
2229
2230 // If this is a templated friend in a dependent context we should not put it
2231 // on the redecl chain. In some cases, the templated friend can be the most
2232 // recent declaration tricking the template instantiator to make substitutions
2233 // there.
2234 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2235 bool ShouldAddRedecl =
2236 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2237
2239 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2240 PrevClassTemplate && ShouldAddRedecl
2241 ? PrevClassTemplate->getTemplatedDecl()
2242 : nullptr);
2243 SetNestedNameSpecifier(*this, NewClass, SS);
2244 if (NumOuterTemplateParamLists > 0)
2246 Context,
2247 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2248
2249 // Add alignment attributes if necessary; these attributes are checked when
2250 // the ASTContext lays out the structure.
2251 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2252 if (LangOpts.HLSL)
2253 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2256 }
2257
2258 ClassTemplateDecl *NewTemplate
2259 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2260 DeclarationName(Name), TemplateParams,
2261 NewClass);
2262
2263 if (ShouldAddRedecl)
2264 NewTemplate->setPreviousDecl(PrevClassTemplate);
2265
2266 NewClass->setDescribedClassTemplate(NewTemplate);
2267
2268 if (ModulePrivateLoc.isValid())
2269 NewTemplate->setModulePrivate();
2270
2271 if (IsMemberSpecialization) {
2272 assert(PrevClassTemplate &&
2273 "Member specialization without a primary template?");
2274 NewTemplate->setMemberSpecialization();
2275 }
2276
2277 // Set the access specifier.
2278 if (!Invalid && TUK != TagUseKind::Friend &&
2279 NewTemplate->getDeclContext()->isRecord())
2280 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2281
2282 // Set the lexical context of these templates
2284 NewTemplate->setLexicalDeclContext(CurContext);
2285
2286 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2287 NewClass->startDefinition();
2288
2289 ProcessDeclAttributeList(S, NewClass, Attr);
2290
2291 if (PrevClassTemplate)
2292 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2293
2297
2298 if (TUK != TagUseKind::Friend) {
2299 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2300 Scope *Outer = S;
2301 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2302 Outer = Outer->getParent();
2303 PushOnScopeChains(NewTemplate, Outer);
2304 } else {
2305 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2306 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2307 NewClass->setAccess(PrevClassTemplate->getAccess());
2308 }
2309
2310 NewTemplate->setObjectOfFriendDecl();
2311
2312 // Friend templates are visible in fairly strange ways.
2313 if (!CurContext->isDependentContext()) {
2314 DeclContext *DC = SemanticContext->getRedeclContext();
2315 DC->makeDeclVisibleInContext(NewTemplate);
2316 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2317 PushOnScopeChains(NewTemplate, EnclosingScope,
2318 /* AddToContext = */ false);
2319 }
2320
2322 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2323 Friend->setAccess(AS_public);
2324 CurContext->addDecl(Friend);
2325 }
2326
2327 if (PrevClassTemplate)
2328 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2329
2330 if (Invalid) {
2331 NewTemplate->setInvalidDecl();
2332 NewClass->setInvalidDecl();
2333 }
2334
2335 ActOnDocumentableDecl(NewTemplate);
2336
2337 if (SkipBody && SkipBody->ShouldSkip)
2338 return SkipBody->Previous;
2339
2340 return NewTemplate;
2341}
2342
2343/// Diagnose the presence of a default template argument on a
2344/// template parameter, which is ill-formed in certain contexts.
2345///
2346/// \returns true if the default template argument should be dropped.
2349 SourceLocation ParamLoc,
2350 SourceRange DefArgRange) {
2351 switch (TPC) {
2352 case Sema::TPC_Other:
2354 return false;
2355
2358 // C++ [temp.param]p9:
2359 // A default template-argument shall not be specified in a
2360 // function template declaration or a function template
2361 // definition [...]
2362 // If a friend function template declaration specifies a default
2363 // template-argument, that declaration shall be a definition and shall be
2364 // the only declaration of the function template in the translation unit.
2365 // (C++98/03 doesn't have this wording; see DR226).
2366 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2367 << DefArgRange;
2368 return false;
2369
2371 // C++0x [temp.param]p9:
2372 // A default template-argument shall not be specified in the
2373 // template-parameter-lists of the definition of a member of a
2374 // class template that appears outside of the member's class.
2375 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2376 << DefArgRange;
2377 return true;
2378
2381 // C++ [temp.param]p9:
2382 // A default template-argument shall not be specified in a
2383 // friend template declaration.
2384 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2385 << DefArgRange;
2386 return true;
2387
2388 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2389 // for friend function templates if there is only a single
2390 // declaration (and it is a definition). Strange!
2391 }
2392
2393 llvm_unreachable("Invalid TemplateParamListContext!");
2394}
2395
2396/// Check for unexpanded parameter packs within the template parameters
2397/// of a template template parameter, recursively.
2400 // A template template parameter which is a parameter pack is also a pack
2401 // expansion.
2402 if (TTP->isParameterPack())
2403 return false;
2404
2406 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2407 NamedDecl *P = Params->getParam(I);
2408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2409 if (!TTP->isParameterPack())
2410 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2411 if (TC->hasExplicitTemplateArgs())
2412 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2415 return true;
2416 continue;
2417 }
2418
2419 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2420 if (!NTTP->isParameterPack() &&
2421 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2422 NTTP->getTypeSourceInfo(),
2424 return true;
2425
2426 continue;
2427 }
2428
2429 if (TemplateTemplateParmDecl *InnerTTP
2430 = dyn_cast<TemplateTemplateParmDecl>(P))
2431 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2432 return true;
2433 }
2434
2435 return false;
2436}
2437
2439 TemplateParameterList *OldParams,
2441 SkipBodyInfo *SkipBody) {
2442 bool Invalid = false;
2443
2444 // C++ [temp.param]p10:
2445 // The set of default template-arguments available for use with a
2446 // template declaration or definition is obtained by merging the
2447 // default arguments from the definition (if in scope) and all
2448 // declarations in scope in the same way default function
2449 // arguments are (8.3.6).
2450 bool SawDefaultArgument = false;
2451 SourceLocation PreviousDefaultArgLoc;
2452
2453 // Dummy initialization to avoid warnings.
2454 TemplateParameterList::iterator OldParam = NewParams->end();
2455 if (OldParams)
2456 OldParam = OldParams->begin();
2457
2458 bool RemoveDefaultArguments = false;
2459 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2460 NewParamEnd = NewParams->end();
2461 NewParam != NewParamEnd; ++NewParam) {
2462 // Whether we've seen a duplicate default argument in the same translation
2463 // unit.
2464 bool RedundantDefaultArg = false;
2465 // Whether we've found inconsis inconsitent default arguments in different
2466 // translation unit.
2467 bool InconsistentDefaultArg = false;
2468 // The name of the module which contains the inconsistent default argument.
2469 std::string PrevModuleName;
2470
2471 SourceLocation OldDefaultLoc;
2472 SourceLocation NewDefaultLoc;
2473
2474 // Variable used to diagnose missing default arguments
2475 bool MissingDefaultArg = false;
2476
2477 // Variable used to diagnose non-final parameter packs
2478 bool SawParameterPack = false;
2479
2480 if (TemplateTypeParmDecl *NewTypeParm
2481 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2482 // Check the presence of a default argument here.
2483 if (NewTypeParm->hasDefaultArgument() &&
2485 *this, TPC, NewTypeParm->getLocation(),
2486 NewTypeParm->getDefaultArgument().getSourceRange()))
2487 NewTypeParm->removeDefaultArgument();
2488
2489 // Merge default arguments for template type parameters.
2490 TemplateTypeParmDecl *OldTypeParm
2491 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2492 if (NewTypeParm->isParameterPack()) {
2493 assert(!NewTypeParm->hasDefaultArgument() &&
2494 "Parameter packs can't have a default argument!");
2495 SawParameterPack = true;
2496 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2497 NewTypeParm->hasDefaultArgument() &&
2498 (!SkipBody || !SkipBody->ShouldSkip)) {
2499 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2500 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2501 SawDefaultArgument = true;
2502
2503 if (!OldTypeParm->getOwningModule())
2504 RedundantDefaultArg = true;
2505 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2506 NewTypeParm)) {
2507 InconsistentDefaultArg = true;
2508 PrevModuleName =
2510 }
2511 PreviousDefaultArgLoc = NewDefaultLoc;
2512 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2513 // Merge the default argument from the old declaration to the
2514 // new declaration.
2515 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2516 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2517 } else if (NewTypeParm->hasDefaultArgument()) {
2518 SawDefaultArgument = true;
2519 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2520 } else if (SawDefaultArgument)
2521 MissingDefaultArg = true;
2522 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2523 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2524 // Check for unexpanded parameter packs, except in a template template
2525 // parameter pack, as in those any unexpanded packs should be expanded
2526 // along with the parameter itself.
2528 !NewNonTypeParm->isParameterPack() &&
2529 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2530 NewNonTypeParm->getTypeSourceInfo(),
2532 Invalid = true;
2533 continue;
2534 }
2535
2536 // Check the presence of a default argument here.
2537 if (NewNonTypeParm->hasDefaultArgument() &&
2539 *this, TPC, NewNonTypeParm->getLocation(),
2540 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2541 NewNonTypeParm->removeDefaultArgument();
2542 }
2543
2544 // Merge default arguments for non-type template parameters
2545 NonTypeTemplateParmDecl *OldNonTypeParm
2546 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2547 if (NewNonTypeParm->isParameterPack()) {
2548 assert(!NewNonTypeParm->hasDefaultArgument() &&
2549 "Parameter packs can't have a default argument!");
2550 if (!NewNonTypeParm->isPackExpansion())
2551 SawParameterPack = true;
2552 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2553 NewNonTypeParm->hasDefaultArgument() &&
2554 (!SkipBody || !SkipBody->ShouldSkip)) {
2555 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2556 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2557 SawDefaultArgument = true;
2558 if (!OldNonTypeParm->getOwningModule())
2559 RedundantDefaultArg = true;
2560 else if (!getASTContext().isSameDefaultTemplateArgument(
2561 OldNonTypeParm, NewNonTypeParm)) {
2562 InconsistentDefaultArg = true;
2563 PrevModuleName =
2564 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2565 }
2566 PreviousDefaultArgLoc = NewDefaultLoc;
2567 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2568 // Merge the default argument from the old declaration to the
2569 // new declaration.
2570 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2571 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2572 } else if (NewNonTypeParm->hasDefaultArgument()) {
2573 SawDefaultArgument = true;
2574 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2575 } else if (SawDefaultArgument)
2576 MissingDefaultArg = true;
2577 } else {
2578 TemplateTemplateParmDecl *NewTemplateParm
2579 = cast<TemplateTemplateParmDecl>(*NewParam);
2580
2581 // Check for unexpanded parameter packs, recursively.
2582 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2583 Invalid = true;
2584 continue;
2585 }
2586
2587 // Check the presence of a default argument here.
2588 if (NewTemplateParm->hasDefaultArgument() &&
2590 NewTemplateParm->getLocation(),
2591 NewTemplateParm->getDefaultArgument().getSourceRange()))
2592 NewTemplateParm->removeDefaultArgument();
2593
2594 // Merge default arguments for template template parameters
2595 TemplateTemplateParmDecl *OldTemplateParm
2596 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2597 if (NewTemplateParm->isParameterPack()) {
2598 assert(!NewTemplateParm->hasDefaultArgument() &&
2599 "Parameter packs can't have a default argument!");
2600 if (!NewTemplateParm->isPackExpansion())
2601 SawParameterPack = true;
2602 } else if (OldTemplateParm &&
2603 hasVisibleDefaultArgument(OldTemplateParm) &&
2604 NewTemplateParm->hasDefaultArgument() &&
2605 (!SkipBody || !SkipBody->ShouldSkip)) {
2606 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2607 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2608 SawDefaultArgument = true;
2609 if (!OldTemplateParm->getOwningModule())
2610 RedundantDefaultArg = true;
2611 else if (!getASTContext().isSameDefaultTemplateArgument(
2612 OldTemplateParm, NewTemplateParm)) {
2613 InconsistentDefaultArg = true;
2614 PrevModuleName =
2615 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2616 }
2617 PreviousDefaultArgLoc = NewDefaultLoc;
2618 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2619 // Merge the default argument from the old declaration to the
2620 // new declaration.
2621 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2622 PreviousDefaultArgLoc
2623 = OldTemplateParm->getDefaultArgument().getLocation();
2624 } else if (NewTemplateParm->hasDefaultArgument()) {
2625 SawDefaultArgument = true;
2626 PreviousDefaultArgLoc
2627 = NewTemplateParm->getDefaultArgument().getLocation();
2628 } else if (SawDefaultArgument)
2629 MissingDefaultArg = true;
2630 }
2631
2632 // C++11 [temp.param]p11:
2633 // If a template parameter of a primary class template or alias template
2634 // is a template parameter pack, it shall be the last template parameter.
2635 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2636 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2637 Diag((*NewParam)->getLocation(),
2638 diag::err_template_param_pack_must_be_last_template_parameter);
2639 Invalid = true;
2640 }
2641
2642 // [basic.def.odr]/13:
2643 // There can be more than one definition of a
2644 // ...
2645 // default template argument
2646 // ...
2647 // in a program provided that each definition appears in a different
2648 // translation unit and the definitions satisfy the [same-meaning
2649 // criteria of the ODR].
2650 //
2651 // Simply, the design of modules allows the definition of template default
2652 // argument to be repeated across translation unit. Note that the ODR is
2653 // checked elsewhere. But it is still not allowed to repeat template default
2654 // argument in the same translation unit.
2655 if (RedundantDefaultArg) {
2656 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2657 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2658 Invalid = true;
2659 } else if (InconsistentDefaultArg) {
2660 // We could only diagnose about the case that the OldParam is imported.
2661 // The case NewParam is imported should be handled in ASTReader.
2662 Diag(NewDefaultLoc,
2663 diag::err_template_param_default_arg_inconsistent_redefinition);
2664 Diag(OldDefaultLoc,
2665 diag::note_template_param_prev_default_arg_in_other_module)
2666 << PrevModuleName;
2667 Invalid = true;
2668 } else if (MissingDefaultArg &&
2669 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2670 TPC == TPC_FriendClassTemplate)) {
2671 // C++ 23[temp.param]p14:
2672 // If a template-parameter of a class template, variable template, or
2673 // alias template has a default template argument, each subsequent
2674 // template-parameter shall either have a default template argument
2675 // supplied or be a template parameter pack.
2676 Diag((*NewParam)->getLocation(),
2677 diag::err_template_param_default_arg_missing);
2678 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2679 Invalid = true;
2680 RemoveDefaultArguments = true;
2681 }
2682
2683 // If we have an old template parameter list that we're merging
2684 // in, move on to the next parameter.
2685 if (OldParams)
2686 ++OldParam;
2687 }
2688
2689 // We were missing some default arguments at the end of the list, so remove
2690 // all of the default arguments.
2691 if (RemoveDefaultArguments) {
2692 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2693 NewParamEnd = NewParams->end();
2694 NewParam != NewParamEnd; ++NewParam) {
2695 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2696 TTP->removeDefaultArgument();
2697 else if (NonTypeTemplateParmDecl *NTTP
2698 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2699 NTTP->removeDefaultArgument();
2700 else
2701 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2702 }
2703 }
2704
2705 return Invalid;
2706}
2707
2708namespace {
2709
2710/// A class which looks for a use of a certain level of template
2711/// parameter.
2712struct DependencyChecker : DynamicRecursiveASTVisitor {
2713 unsigned Depth;
2714
2715 // Whether we're looking for a use of a template parameter that makes the
2716 // overall construct type-dependent / a dependent type. This is strictly
2717 // best-effort for now; we may fail to match at all for a dependent type
2718 // in some cases if this is set.
2719 bool IgnoreNonTypeDependent;
2720
2721 bool Match;
2722 SourceLocation MatchLoc;
2723
2724 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2725 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2726 Match(false) {}
2727
2728 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2729 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2730 NamedDecl *ND = Params->getParam(0);
2731 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2732 Depth = PD->getDepth();
2733 } else if (NonTypeTemplateParmDecl *PD =
2734 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2735 Depth = PD->getDepth();
2736 } else {
2737 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2738 }
2739 }
2740
2741 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2742 if (ParmDepth >= Depth) {
2743 Match = true;
2744 MatchLoc = Loc;
2745 return true;
2746 }
2747 return false;
2748 }
2749
2750 bool TraverseStmt(Stmt *S) override {
2751 // Prune out non-type-dependent expressions if requested. This can
2752 // sometimes result in us failing to find a template parameter reference
2753 // (if a value-dependent expression creates a dependent type), but this
2754 // mode is best-effort only.
2755 if (auto *E = dyn_cast_or_null<Expr>(S))
2756 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2757 return true;
2759 }
2760
2761 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2762 if (IgnoreNonTypeDependent && !TL.isNull() &&
2763 !TL.getType()->isDependentType())
2764 return true;
2765 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2766 }
2767
2768 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2769 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2770 }
2771
2772 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2773 // For a best-effort search, keep looking until we find a location.
2774 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2775 }
2776
2777 bool TraverseTemplateName(TemplateName N) override {
2778 if (TemplateTemplateParmDecl *PD =
2779 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2780 if (Matches(PD->getDepth()))
2781 return false;
2783 }
2784
2785 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2786 if (NonTypeTemplateParmDecl *PD =
2787 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2788 if (Matches(PD->getDepth(), E->getExprLoc()))
2789 return false;
2790 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2791 }
2792
2793 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2794 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2795 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2796 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2797 return false;
2798 }
2799 for (auto &TLoc : ULE->template_arguments())
2801 }
2802 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2803 }
2804
2805 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2806 return TraverseType(T->getReplacementType());
2807 }
2808
2809 bool VisitSubstTemplateTypeParmPackType(
2810 SubstTemplateTypeParmPackType *T) override {
2811 return TraverseTemplateArgument(T->getArgumentPack());
2812 }
2813
2814 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2815 bool TraverseQualifier) override {
2816 // An InjectedClassNameType will never have a dependent template name,
2817 // so no need to traverse it.
2818 return TraverseTemplateArguments(
2819 T->getTemplateArgs(T->getDecl()->getASTContext()));
2820 }
2821};
2822} // end anonymous namespace
2823
2824/// Determines whether a given type depends on the given parameter
2825/// list.
2826static bool
2828 if (!Params->size())
2829 return false;
2830
2831 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2832 Checker.TraverseType(T);
2833 return Checker.Match;
2834}
2835
2836// Find the source range corresponding to the named type in the given
2837// nested-name-specifier, if any.
2839 QualType T,
2840 const CXXScopeSpec &SS) {
2842 for (;;) {
2845 break;
2846 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2847 return NNSLoc.castAsTypeLoc().getSourceRange();
2848 // FIXME: This will always be empty.
2849 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2850 }
2851
2852 return SourceRange();
2853}
2854
2856 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2857 TemplateIdAnnotation *TemplateId,
2858 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2859 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2860 IsMemberSpecialization = false;
2861 Invalid = false;
2862
2863 // The sequence of nested types to which we will match up the template
2864 // parameter lists. We first build this list by starting with the type named
2865 // by the nested-name-specifier and walking out until we run out of types.
2866 SmallVector<QualType, 4> NestedTypes;
2867 QualType T;
2868 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2869 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2870 if (CXXRecordDecl *Record =
2871 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2872 T = Context.getCanonicalTagType(Record);
2873 else
2874 T = QualType(Qualifier.getAsType(), 0);
2875 }
2876
2877 // If we found an explicit specialization that prevents us from needing
2878 // 'template<>' headers, this will be set to the location of that
2879 // explicit specialization.
2880 SourceLocation ExplicitSpecLoc;
2881
2882 while (!T.isNull()) {
2883 NestedTypes.push_back(T);
2884
2885 // Retrieve the parent of a record type.
2886 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2887 // If this type is an explicit specialization, we're done.
2889 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2891 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2892 ExplicitSpecLoc = Spec->getLocation();
2893 break;
2894 }
2895 } else if (Record->getTemplateSpecializationKind()
2897 ExplicitSpecLoc = Record->getLocation();
2898 break;
2899 }
2900
2901 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2902 T = Context.getTypeDeclType(Parent);
2903 else
2904 T = QualType();
2905 continue;
2906 }
2907
2908 if (const TemplateSpecializationType *TST
2909 = T->getAs<TemplateSpecializationType>()) {
2910 TemplateName Name = TST->getTemplateName();
2911 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2912 // Look one step prior in a dependent template specialization type.
2913 if (NestedNameSpecifier NNS = DTS->getQualifier();
2915 T = QualType(NNS.getAsType(), 0);
2916 else
2917 T = QualType();
2918 continue;
2919 }
2920 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2921 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2922 T = Context.getTypeDeclType(Parent);
2923 else
2924 T = QualType();
2925 continue;
2926 }
2927 }
2928
2929 // Look one step prior in a dependent name type.
2930 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2931 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2933 T = QualType(NNS.getAsType(), 0);
2934 else
2935 T = QualType();
2936 continue;
2937 }
2938
2939 // Retrieve the parent of an enumeration type.
2940 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2941 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2942 // check here.
2943 EnumDecl *Enum = EnumT->getDecl();
2944
2945 // Get to the parent type.
2946 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2947 T = Context.getCanonicalTypeDeclType(Parent);
2948 else
2949 T = QualType();
2950 continue;
2951 }
2952
2953 T = QualType();
2954 }
2955 // Reverse the nested types list, since we want to traverse from the outermost
2956 // to the innermost while checking template-parameter-lists.
2957 std::reverse(NestedTypes.begin(), NestedTypes.end());
2958
2959 // C++0x [temp.expl.spec]p17:
2960 // A member or a member template may be nested within many
2961 // enclosing class templates. In an explicit specialization for
2962 // such a member, the member declaration shall be preceded by a
2963 // template<> for each enclosing class template that is
2964 // explicitly specialized.
2965 bool SawNonEmptyTemplateParameterList = false;
2966
2967 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2968 if (SawNonEmptyTemplateParameterList) {
2969 if (!SuppressDiagnostic)
2970 Diag(DeclLoc, diag::err_specialize_member_of_template)
2971 << !Recovery << Range;
2972 Invalid = true;
2973 IsMemberSpecialization = false;
2974 return true;
2975 }
2976
2977 return false;
2978 };
2979
2980 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2981 // Check that we can have an explicit specialization here.
2982 if (CheckExplicitSpecialization(Range, true))
2983 return true;
2984
2985 // We don't have a template header, but we should.
2986 SourceLocation ExpectedTemplateLoc;
2987 if (!ParamLists.empty())
2988 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2989 else
2990 ExpectedTemplateLoc = DeclStartLoc;
2991
2992 if (!SuppressDiagnostic)
2993 Diag(DeclLoc, diag::err_template_spec_needs_header)
2994 << Range
2995 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2996 return false;
2997 };
2998
2999 unsigned ParamIdx = 0;
3000 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3001 ++TypeIdx) {
3002 T = NestedTypes[TypeIdx];
3003
3004 // Whether we expect a 'template<>' header.
3005 bool NeedEmptyTemplateHeader = false;
3006
3007 // Whether we expect a template header with parameters.
3008 bool NeedNonemptyTemplateHeader = false;
3009
3010 // For a dependent type, the set of template parameters that we
3011 // expect to see.
3012 TemplateParameterList *ExpectedTemplateParams = nullptr;
3013
3014 // C++0x [temp.expl.spec]p15:
3015 // A member or a member template may be nested within many enclosing
3016 // class templates. In an explicit specialization for such a member, the
3017 // member declaration shall be preceded by a template<> for each
3018 // enclosing class template that is explicitly specialized.
3019 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3021 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3022 ExpectedTemplateParams = Partial->getTemplateParameters();
3023 NeedNonemptyTemplateHeader = true;
3024 } else if (Record->isDependentType()) {
3025 if (Record->getDescribedClassTemplate()) {
3026 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3027 ->getTemplateParameters();
3028 NeedNonemptyTemplateHeader = true;
3029 }
3030 } else if (ClassTemplateSpecializationDecl *Spec
3031 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3032 // C++0x [temp.expl.spec]p4:
3033 // Members of an explicitly specialized class template are defined
3034 // in the same manner as members of normal classes, and not using
3035 // the template<> syntax.
3036 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3037 NeedEmptyTemplateHeader = true;
3038 else
3039 continue;
3040 } else if (Record->getTemplateSpecializationKind()) {
3041 if (Record->getTemplateSpecializationKind()
3043 TypeIdx == NumTypes - 1)
3044 IsMemberSpecialization = true;
3045
3046 continue;
3047 }
3048 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3049 TemplateName Name = TST->getTemplateName();
3050 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3051 ExpectedTemplateParams = Template->getTemplateParameters();
3052 NeedNonemptyTemplateHeader = true;
3053 } else if (Name.getAsDeducedTemplateName()) {
3054 // FIXME: We actually could/should check the template arguments here
3055 // against the corresponding template parameter list.
3056 NeedNonemptyTemplateHeader = false;
3057 }
3058 }
3059
3060 // C++ [temp.expl.spec]p16:
3061 // In an explicit specialization declaration for a member of a class
3062 // template or a member template that appears in namespace scope, the
3063 // member template and some of its enclosing class templates may remain
3064 // unspecialized, except that the declaration shall not explicitly
3065 // specialize a class member template if its enclosing class templates
3066 // are not explicitly specialized as well.
3067 if (ParamIdx < ParamLists.size()) {
3068 if (ParamLists[ParamIdx]->size() == 0) {
3069 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072 } else
3073 SawNonEmptyTemplateParameterList = true;
3074 }
3075
3076 if (NeedEmptyTemplateHeader) {
3077 // If we're on the last of the types, and we need a 'template<>' header
3078 // here, then it's a member specialization.
3079 if (TypeIdx == NumTypes - 1)
3080 IsMemberSpecialization = true;
3081
3082 if (ParamIdx < ParamLists.size()) {
3083 if (ParamLists[ParamIdx]->size() > 0) {
3084 // The header has template parameters when it shouldn't. Complain.
3085 if (!SuppressDiagnostic)
3086 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3087 diag::err_template_param_list_matches_nontemplate)
3088 << T
3089 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3090 ParamLists[ParamIdx]->getRAngleLoc())
3092 Invalid = true;
3093 return nullptr;
3094 }
3095
3096 // Consume this template header.
3097 ++ParamIdx;
3098 continue;
3099 }
3100
3101 if (!IsFriend)
3102 if (DiagnoseMissingExplicitSpecialization(
3104 return nullptr;
3105
3106 continue;
3107 }
3108
3109 if (NeedNonemptyTemplateHeader) {
3110 // In friend declarations we can have template-ids which don't
3111 // depend on the corresponding template parameter lists. But
3112 // assume that empty parameter lists are supposed to match this
3113 // template-id.
3114 if (IsFriend && T->isDependentType()) {
3115 if (ParamIdx < ParamLists.size() &&
3116 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3117 ExpectedTemplateParams = nullptr;
3118 else
3119 continue;
3120 }
3121
3122 if (ParamIdx < ParamLists.size()) {
3123 // Check the template parameter list, if we can.
3124 if (ExpectedTemplateParams &&
3126 ExpectedTemplateParams,
3127 !SuppressDiagnostic, TPL_TemplateMatch))
3128 Invalid = true;
3129
3130 if (!Invalid &&
3131 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3133 Invalid = true;
3134
3135 ++ParamIdx;
3136 continue;
3137 }
3138
3139 if (!SuppressDiagnostic)
3140 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3141 << T
3143 Invalid = true;
3144 continue;
3145 }
3146 }
3147
3148 // If there were at least as many template-ids as there were template
3149 // parameter lists, then there are no template parameter lists remaining for
3150 // the declaration itself.
3151 if (ParamIdx >= ParamLists.size()) {
3152 if (TemplateId && !IsFriend) {
3153 // We don't have a template header for the declaration itself, but we
3154 // should.
3155 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3156 TemplateId->RAngleLoc));
3157
3158 // Fabricate an empty template parameter list for the invented header.
3160 SourceLocation(), {},
3161 SourceLocation(), nullptr);
3162 }
3163
3164 return nullptr;
3165 }
3166
3167 // If there were too many template parameter lists, complain about that now.
3168 if (ParamIdx < ParamLists.size() - 1) {
3169 bool HasAnyExplicitSpecHeader = false;
3170 bool AllExplicitSpecHeaders = true;
3171 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3172 if (ParamLists[I]->size() == 0)
3173 HasAnyExplicitSpecHeader = true;
3174 else
3175 AllExplicitSpecHeaders = false;
3176 }
3177
3178 if (!SuppressDiagnostic)
3179 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3180 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3181 : diag::err_template_spec_extra_headers)
3182 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3183 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3184
3185 // If there was a specialization somewhere, such that 'template<>' is
3186 // not required, and there were any 'template<>' headers, note where the
3187 // specialization occurred.
3188 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3189 !SuppressDiagnostic)
3190 Diag(ExplicitSpecLoc,
3191 diag::note_explicit_template_spec_does_not_need_header)
3192 << NestedTypes.back();
3193
3194 // We have a template parameter list with no corresponding scope, which
3195 // means that the resulting template declaration can't be instantiated
3196 // properly (we'll end up with dependent nodes when we shouldn't).
3197 if (!AllExplicitSpecHeaders)
3198 Invalid = true;
3199 }
3200
3201 // C++ [temp.expl.spec]p16:
3202 // In an explicit specialization declaration for a member of a class
3203 // template or a member template that ap- pears in namespace scope, the
3204 // member template and some of its enclosing class templates may remain
3205 // unspecialized, except that the declaration shall not explicitly
3206 // specialize a class member template if its en- closing class templates
3207 // are not explicitly specialized as well.
3208 if (ParamLists.back()->size() == 0 &&
3209 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3210 false))
3211 return nullptr;
3212
3213 // Return the last template parameter list, which corresponds to the
3214 // entity being declared.
3215 return ParamLists.back();
3216}
3217
3219 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3220 Diag(Template->getLocation(), diag::note_template_declared_here)
3222 ? 0
3224 ? 1
3226 ? 2
3228 << Template->getDeclName();
3229 return;
3230 }
3231
3233 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3234 IEnd = OST->end();
3235 I != IEnd; ++I)
3236 Diag((*I)->getLocation(), diag::note_template_declared_here)
3237 << 0 << (*I)->getDeclName();
3238
3239 return;
3240 }
3241}
3242
3244 TemplateName BaseTemplate,
3245 SourceLocation TemplateLoc,
3247 auto lookUpCommonType = [&](TemplateArgument T1,
3248 TemplateArgument T2) -> QualType {
3249 // Don't bother looking for other specializations if both types are
3250 // builtins - users aren't allowed to specialize for them
3251 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3252 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3253 {T1, T2});
3254
3258 Args.addArgument(TemplateArgumentLoc(
3259 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3260
3261 EnterExpressionEvaluationContext UnevaluatedContext(
3263 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3265
3266 QualType BaseTemplateInst = S.CheckTemplateIdType(
3267 Keyword, BaseTemplate, TemplateLoc, Args,
3268 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3269
3270 if (SFINAE.hasErrorOccurred())
3271 return QualType();
3272
3273 return BaseTemplateInst;
3274 };
3275
3276 // Note A: For the common_type trait applied to a template parameter pack T of
3277 // types, the member type shall be either defined or not present as follows:
3278 switch (Ts.size()) {
3279
3280 // If sizeof...(T) is zero, there shall be no member type.
3281 case 0:
3282 return QualType();
3283
3284 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3285 // pack T. The member typedef-name type shall denote the same type, if any, as
3286 // common_type_t<T0, T0>; otherwise there shall be no member type.
3287 case 1:
3288 return lookUpCommonType(Ts[0], Ts[0]);
3289
3290 // If sizeof...(T) is two, let the first and second types constituting T be
3291 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3292 // as decay_t<T1> and decay_t<T2>, respectively.
3293 case 2: {
3294 QualType T1 = Ts[0].getAsType();
3295 QualType T2 = Ts[1].getAsType();
3296 QualType D1 = S.BuiltinDecay(T1, {});
3297 QualType D2 = S.BuiltinDecay(T2, {});
3298
3299 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3300 // the same type, if any, as common_type_t<D1, D2>.
3301 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3302 return lookUpCommonType(D1, D2);
3303
3304 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3305 // denotes a valid type, let C denote that type.
3306 {
3307 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3308 EnterExpressionEvaluationContext UnevaluatedContext(
3310 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3312
3313 // false
3315 VK_PRValue);
3316 ExprResult Cond = &CondExpr;
3317
3318 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3319 if (ConstRefQual) {
3320 D1.addConst();
3321 D2.addConst();
3322 }
3323
3324 // declval<D1>()
3325 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3326 ExprResult LHS = &LHSExpr;
3327
3328 // declval<D2>()
3329 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3330 ExprResult RHS = &RHSExpr;
3331
3334
3335 // decltype(false ? declval<D1>() : declval<D2>())
3337 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3338
3339 if (Result.isNull() || SFINAE.hasErrorOccurred())
3340 return QualType();
3341
3342 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3343 return S.BuiltinDecay(Result, TemplateLoc);
3344 };
3345
3346 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3347 return Res;
3348
3349 // Let:
3350 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3351 // COND-RES(X, Y) be
3352 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3353
3354 // C++20 only
3355 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3356 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3357 if (!S.Context.getLangOpts().CPlusPlus20)
3358 return QualType();
3359 return CheckConditionalOperands(true);
3360 }
3361 }
3362
3363 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3364 // denote the first, second, and (pack of) remaining types constituting T. Let
3365 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3366 // a type C, the member typedef-name type shall denote the same type, if any,
3367 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3368 default: {
3369 QualType Result = Ts.front().getAsType();
3370 for (auto T : llvm::drop_begin(Ts)) {
3371 Result = lookUpCommonType(Result, T.getAsType());
3372 if (Result.isNull())
3373 return QualType();
3374 }
3375 return Result;
3376 }
3377 }
3378}
3379
3380static bool isInVkNamespace(const RecordType *RT) {
3381 DeclContext *DC = RT->getDecl()->getDeclContext();
3382 if (!DC)
3383 return false;
3384
3385 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3386 if (!ND)
3387 return false;
3388
3389 return ND->getQualifiedNameAsString() == "hlsl::vk";
3390}
3391
3392static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3393 QualType OperandArg,
3394 SourceLocation Loc) {
3395 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3396 bool Literal = false;
3397 SourceLocation LiteralLoc;
3398 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3399 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3400 assert(SpecDecl);
3401
3402 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3403 QualType ConstantType = LiteralArgs[0].getAsType();
3404 RT = ConstantType->getAsCanonical<RecordType>();
3405 Literal = true;
3406 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3407 }
3408
3409 if (RT && isInVkNamespace(RT) &&
3410 RT->getDecl()->getName() == "integral_constant") {
3411 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3412 assert(SpecDecl);
3413
3414 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3415
3416 QualType ConstantType = ConstantArgs[0].getAsType();
3417 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3418
3419 if (Literal)
3420 return SpirvOperand::createLiteral(Value);
3421 return SpirvOperand::createConstant(ConstantType, Value);
3422 } else if (Literal) {
3423 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3424 return SpirvOperand();
3425 }
3426 }
3427 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3428 diag::err_call_incomplete_argument))
3429 return SpirvOperand();
3430 return SpirvOperand::createType(OperandArg);
3431}
3432
3435 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3436 TemplateArgumentListInfo &TemplateArgs) {
3437 ASTContext &Context = SemaRef.getASTContext();
3438
3439 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3440 "Builtin template arguments do not match its parameters");
3441
3442 switch (BTD->getBuiltinTemplateKind()) {
3443 case BTK__make_integer_seq: {
3444 // Specializations of __make_integer_seq<S, T, N> are treated like
3445 // S<T, 0, ..., N-1>.
3446
3447 QualType OrigType = Converted[1].getAsType();
3448 // C++14 [inteseq.intseq]p1:
3449 // T shall be an integer type.
3450 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3451 SemaRef.Diag(TemplateArgs[1].getLocation(),
3452 diag::err_integer_sequence_integral_element_type);
3453 return QualType();
3454 }
3455
3456 TemplateArgument NumArgsArg = Converted[2];
3457 if (NumArgsArg.isDependent())
3458 return QualType();
3459
3460 TemplateArgumentListInfo SyntheticTemplateArgs;
3461 // The type argument, wrapped in substitution sugar, gets reused as the
3462 // first template argument in the synthetic template argument list.
3463 SyntheticTemplateArgs.addArgument(
3466 OrigType, TemplateArgs[1].getLocation())));
3467
3468 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3469 // Expand N into 0 ... N-1.
3470 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3471 I < NumArgs; ++I) {
3472 TemplateArgument TA(Context, I, OrigType);
3473 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3474 TA, OrigType, TemplateArgs[2].getLocation()));
3475 }
3476 } else {
3477 // C++14 [inteseq.make]p1:
3478 // If N is negative the program is ill-formed.
3479 SemaRef.Diag(TemplateArgs[2].getLocation(),
3480 diag::err_integer_sequence_negative_length);
3481 return QualType();
3482 }
3483
3484 // The first template argument will be reused as the template decl that
3485 // our synthetic template arguments will be applied to.
3486 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3487 TemplateLoc, SyntheticTemplateArgs,
3488 /*Scope=*/nullptr,
3489 /*ForNestedNameSpecifier=*/false);
3490 }
3491
3492 case BTK__type_pack_element: {
3493 // Specializations of
3494 // __type_pack_element<Index, T_1, ..., T_N>
3495 // are treated like T_Index.
3496 assert(Converted.size() == 2 &&
3497 "__type_pack_element should be given an index and a parameter pack");
3498
3499 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3500 if (IndexArg.isDependent() || Ts.isDependent())
3501 return QualType();
3502
3503 llvm::APSInt Index = IndexArg.getAsIntegral();
3504 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3505 "type std::size_t, and hence be non-negative");
3506 // If the Index is out of bounds, the program is ill-formed.
3507 if (Index >= Ts.pack_size()) {
3508 SemaRef.Diag(TemplateArgs[0].getLocation(),
3509 diag::err_type_pack_element_out_of_bounds);
3510 return QualType();
3511 }
3512
3513 // We simply return the type at index `Index`.
3514 int64_t N = Index.getExtValue();
3515 return Ts.getPackAsArray()[N].getAsType();
3516 }
3517
3518 case BTK__builtin_common_type: {
3519 assert(Converted.size() == 4);
3520 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3521 return QualType();
3522
3523 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3524 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3525 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3526 TemplateLoc, Ts);
3527 !CT.isNull()) {
3531 CT, TemplateArgs[1].getLocation())));
3532 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3533 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3534 TAs, /*Scope=*/nullptr,
3535 /*ForNestedNameSpecifier=*/false);
3536 }
3537 QualType HasNoTypeMember = Converted[2].getAsType();
3538 return HasNoTypeMember;
3539 }
3540
3541 case BTK__hlsl_spirv_type: {
3542 assert(Converted.size() == 4);
3543
3544 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3545 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3546 }
3547
3548 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3549 return QualType();
3550
3551 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3552 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3553 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3554
3555 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3556
3558
3559 for (auto &OperandTA : OperandArgs) {
3560 QualType OperandArg = OperandTA.getAsType();
3561 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3562 TemplateArgs[3].getLocation());
3563 if (!Operand.isValid())
3564 return QualType();
3565 Operands.push_back(Operand);
3566 }
3567
3568 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3569 }
3570 case BTK__builtin_dedup_pack: {
3571 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3572 "a parameter pack");
3573 TemplateArgument Ts = Converted[0];
3574 // Delay the computation until we can compute the final result. We choose
3575 // not to remove the duplicates upfront before substitution to keep the code
3576 // simple.
3577 if (Ts.isDependent())
3578 return QualType();
3579 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3581 llvm::SmallDenseSet<QualType> Seen;
3582 // Synthesize a new template argument list, removing duplicates.
3583 for (auto T : Ts.getPackAsArray()) {
3584 assert(T.getKind() == clang::TemplateArgument::Type);
3585 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3586 continue;
3587 OutArgs.push_back(T);
3588 }
3589 return Context.getSubstBuiltinTemplatePack(
3590 TemplateArgument::CreatePackCopy(Context, OutArgs));
3591 }
3592 }
3593 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3594}
3595
3596/// Determine whether this alias template is "enable_if_t".
3597/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3599 return AliasTemplate->getName() == "enable_if_t" ||
3600 AliasTemplate->getName() == "__enable_if_t";
3601}
3602
3603/// Collect all of the separable terms in the given condition, which
3604/// might be a conjunction.
3605///
3606/// FIXME: The right answer is to convert the logical expression into
3607/// disjunctive normal form, so we can find the first failed term
3608/// within each possible clause.
3609static void collectConjunctionTerms(Expr *Clause,
3610 SmallVectorImpl<Expr *> &Terms) {
3611 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3612 if (BinOp->getOpcode() == BO_LAnd) {
3613 collectConjunctionTerms(BinOp->getLHS(), Terms);
3614 collectConjunctionTerms(BinOp->getRHS(), Terms);
3615 return;
3616 }
3617 }
3618
3619 Terms.push_back(Clause);
3620}
3621
3622// The ranges-v3 library uses an odd pattern of a top-level "||" with
3623// a left-hand side that is value-dependent but never true. Identify
3624// the idiom and ignore that term.
3626 // Top-level '||'.
3627 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3628 if (!BinOp) return Cond;
3629
3630 if (BinOp->getOpcode() != BO_LOr) return Cond;
3631
3632 // With an inner '==' that has a literal on the right-hand side.
3633 Expr *LHS = BinOp->getLHS();
3634 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3635 if (!InnerBinOp) return Cond;
3636
3637 if (InnerBinOp->getOpcode() != BO_EQ ||
3638 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3639 return Cond;
3640
3641 // If the inner binary operation came from a macro expansion named
3642 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3643 // of the '||', which is the real, user-provided condition.
3644 SourceLocation Loc = InnerBinOp->getExprLoc();
3645 if (!Loc.isMacroID()) return Cond;
3646
3647 StringRef MacroName = PP.getImmediateMacroName(Loc);
3648 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3649 return BinOp->getRHS();
3650
3651 return Cond;
3652}
3653
3654namespace {
3655
3656// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3657// within failing boolean expression, such as substituting template parameters
3658// for actual types.
3659class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3660public:
3661 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3662 : Policy(P) {}
3663
3664 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3665 const auto *DR = dyn_cast<DeclRefExpr>(E);
3666 if (DR && DR->getQualifier()) {
3667 // If this is a qualified name, expand the template arguments in nested
3668 // qualifiers.
3669 DR->getQualifier().print(OS, Policy, true);
3670 // Then print the decl itself.
3671 const ValueDecl *VD = DR->getDecl();
3672 OS << *VD;
3673 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3674 // This is a template variable, print the expanded template arguments.
3675 printTemplateArgumentList(
3676 OS, IV->getTemplateArgs().asArray(), Policy,
3677 IV->getSpecializedTemplate()->getTemplateParameters());
3678 }
3679 return true;
3680 }
3681 return false;
3682 }
3683
3684private:
3685 const PrintingPolicy Policy;
3686};
3687
3688} // end anonymous namespace
3689
3690std::pair<Expr *, std::string>
3693
3694 // Separate out all of the terms in a conjunction.
3697
3698 // Determine which term failed.
3699 Expr *FailedCond = nullptr;
3700 for (Expr *Term : Terms) {
3701 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3702
3703 // Literals are uninteresting.
3704 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3705 isa<IntegerLiteral>(TermAsWritten))
3706 continue;
3707
3708 // The initialization of the parameter from the argument is
3709 // a constant-evaluated context.
3712
3713 bool Succeeded;
3714 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3715 !Succeeded) {
3716 FailedCond = TermAsWritten;
3717 break;
3718 }
3719 }
3720 if (!FailedCond)
3721 FailedCond = Cond->IgnoreParenImpCasts();
3722
3723 std::string Description;
3724 {
3725 llvm::raw_string_ostream Out(Description);
3727 Policy.PrintAsCanonical = true;
3728 FailedBooleanConditionPrinterHelper Helper(Policy);
3729 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3730 }
3731 return { FailedCond, Description };
3732}
3733
3734static TemplateName
3736 const AssumedTemplateStorage *ATN,
3737 SourceLocation NameLoc) {
3738 // We assumed this undeclared identifier to be an (ADL-only) function
3739 // template name, but it was used in a context where a type was required.
3740 // Try to typo-correct it now.
3741 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3742 struct CandidateCallback : CorrectionCandidateCallback {
3743 bool ValidateCandidate(const TypoCorrection &TC) override {
3744 return TC.getCorrectionDecl() &&
3746 }
3747 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3748 return std::make_unique<CandidateCallback>(*this);
3749 }
3750 } FilterCCC;
3751
3752 TypoCorrection Corrected =
3753 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3754 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3755 if (Corrected && Corrected.getFoundDecl()) {
3756 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3757 << ATN->getDeclName());
3759 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3761 }
3762
3763 return TemplateName();
3764}
3765
3767 TemplateName Name,
3768 SourceLocation TemplateLoc,
3769 TemplateArgumentListInfo &TemplateArgs,
3770 Scope *Scope, bool ForNestedNameSpecifier) {
3771 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3772
3773 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3774 if (!Template) {
3775 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3776 Template = S->getParameterPack();
3777 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3778 if (DTN->getName().getIdentifier())
3779 // When building a template-id where the template-name is dependent,
3780 // assume the template is a type template. Either our assumption is
3781 // correct, or the code is ill-formed and will be diagnosed when the
3782 // dependent name is substituted.
3783 return Context.getTemplateSpecializationType(Keyword, Name,
3784 TemplateArgs.arguments(),
3785 /*CanonicalArgs=*/{});
3786 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3788 *this, Scope, ATN, TemplateLoc);
3789 CorrectedName.isNull()) {
3790 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3791 return QualType();
3792 } else {
3793 Name = CorrectedName;
3794 Template = Name.getAsTemplateDecl();
3795 }
3796 }
3797 }
3798 if (!Template ||
3800 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3801 if (ForNestedNameSpecifier)
3802 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3803 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3804 else
3805 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3807 return QualType();
3808 }
3809
3810 // Check that the template argument list is well-formed for this
3811 // template.
3813 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3814 DefaultArgs, /*PartialTemplateArgs=*/false,
3815 CTAI,
3816 /*UpdateArgsWithConversions=*/true))
3817 return QualType();
3818
3819 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3820 // and there are no diagnsotics currently implemented for TemplateDecls,
3821 // so avoid doing it for now.
3822 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3823
3824 QualType CanonType;
3825
3827 // We might have a substituted template template parameter pack. If so,
3828 // build a template specialization type for it.
3830 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3831
3832 // C++0x [dcl.type.elab]p2:
3833 // If the identifier resolves to a typedef-name or the simple-template-id
3834 // resolves to an alias template specialization, the
3835 // elaborated-type-specifier is ill-formed.
3838 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3841 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3842 }
3843
3844 // Find the canonical type for this type alias template specialization.
3845 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3846
3847 // Diagnose uses of the pattern of this template.
3848 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3849 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3850
3851 if (Pattern->isInvalidDecl())
3852 return QualType();
3853
3854 // Only substitute for the innermost template argument list.
3855 MultiLevelTemplateArgumentList TemplateArgLists;
3857 /*Final=*/true);
3858 TemplateArgLists.addOuterRetainedLevels(
3859 AliasTemplate->getTemplateParameters()->getDepth());
3860
3862
3863 // FIXME: The TemplateArgs passed here are not used for the context note,
3864 // nor they should, because this note will be pointing to the specialization
3865 // anyway. These arguments are needed for a hack for instantiating lambdas
3866 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3867 // arguments will be used for collating the template arguments needed to
3868 // instantiate the lambda.
3869 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3870 /*Entity=*/AliasTemplate,
3871 /*TemplateArgs=*/CTAI.SugaredConverted);
3872 if (Inst.isInvalid())
3873 return QualType();
3874
3875 std::optional<ContextRAII> SavedContext;
3876 if (!AliasTemplate->getDeclContext()->isFileContext())
3877 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3878
3879 CanonType =
3880 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3881 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3882 if (CanonType.isNull()) {
3883 // If this was enable_if and we failed to find the nested type
3884 // within enable_if in a SFINAE context, dig out the specific
3885 // enable_if condition that failed and present that instead.
3887 if (SFINAETrap *Trap = getSFINAEContext();
3888 TemplateDeductionInfo *DeductionInfo =
3889 Trap ? Trap->getDeductionInfo() : nullptr) {
3890 if (DeductionInfo->hasSFINAEDiagnostic() &&
3891 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3892 diag::err_typename_nested_not_found_enable_if &&
3893 TemplateArgs[0].getArgument().getKind() ==
3895 Expr *FailedCond;
3896 std::string FailedDescription;
3897 std::tie(FailedCond, FailedDescription) =
3898 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3899
3900 // Remove the old SFINAE diagnostic.
3901 PartialDiagnosticAt OldDiag =
3903 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3904
3905 // Add a new SFINAE diagnostic specifying which condition
3906 // failed.
3907 DeductionInfo->addSFINAEDiagnostic(
3908 OldDiag.first,
3909 PDiag(diag::err_typename_nested_not_found_requirement)
3910 << FailedDescription << FailedCond->getSourceRange());
3911 }
3912 }
3913 }
3914
3915 return QualType();
3916 }
3917 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3918 CanonType = checkBuiltinTemplateIdType(
3919 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3920 } else if (Name.isDependent() ||
3921 TemplateSpecializationType::anyDependentTemplateArguments(
3922 TemplateArgs, CTAI.CanonicalConverted)) {
3923 // This class template specialization is a dependent
3924 // type. Therefore, its canonical type is another class template
3925 // specialization type that contains all of the converted
3926 // arguments in canonical form. This ensures that, e.g., A<T> and
3927 // A<T, T> have identical types when A is declared as:
3928 //
3929 // template<typename T, typename U = T> struct A;
3930 CanonType = Context.getCanonicalTemplateSpecializationType(
3932 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3933 CTAI.CanonicalConverted);
3934 assert(CanonType->isCanonicalUnqualified());
3935
3936 // This might work out to be a current instantiation, in which
3937 // case the canonical type needs to be the InjectedClassNameType.
3938 //
3939 // TODO: in theory this could be a simple hashtable lookup; most
3940 // changes to CurContext don't change the set of current
3941 // instantiations.
3943 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3944 // If we get out to a namespace, we're done.
3945 if (Ctx->isFileContext()) break;
3946
3947 // If this isn't a record, keep looking.
3948 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3949 if (!Record) continue;
3950
3951 // Look for one of the two cases with InjectedClassNameTypes
3952 // and check whether it's the same template.
3954 !Record->getDescribedClassTemplate())
3955 continue;
3956
3957 // Fetch the injected class name type and check whether its
3958 // injected type is equal to the type we just built.
3959 CanQualType ICNT = Context.getCanonicalTagType(Record);
3960 CanQualType Injected =
3961 Record->getCanonicalTemplateSpecializationType(Context);
3962
3963 if (CanonType != Injected)
3964 continue;
3965
3966 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3967 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3968
3969 // If so, the canonical type of this TST is the injected
3970 // class name type of the record we just found.
3971 CanonType = ICNT;
3972 break;
3973 }
3974 }
3975 } else if (ClassTemplateDecl *ClassTemplate =
3976 dyn_cast<ClassTemplateDecl>(Template)) {
3977 // Find the class template specialization declaration that
3978 // corresponds to these arguments.
3979 void *InsertPos = nullptr;
3981 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3982 if (!Decl) {
3983 // This is the first time we have referenced this class template
3984 // specialization. Create the canonical declaration and add it to
3985 // the set of specializations.
3987 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3988 ClassTemplate->getDeclContext(),
3989 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3990 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3991 CTAI.StrictPackMatch, nullptr);
3992 ClassTemplate->AddSpecialization(Decl, InsertPos);
3993 if (ClassTemplate->isOutOfLine())
3994 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3995 }
3996
3997 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3998 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3999 NonSFINAEContext _(*this);
4000 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4001 if (!Inst.isInvalid()) {
4003 CTAI.CanonicalConverted,
4004 /*Final=*/false);
4005 InstantiateAttrsForDecl(TemplateArgLists,
4006 ClassTemplate->getTemplatedDecl(), Decl);
4007 }
4008 }
4009
4010 // Diagnose uses of this specialization.
4011 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4012 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4013
4014 CanonType = Context.getCanonicalTagType(Decl);
4015 assert(isa<RecordType>(CanonType) &&
4016 "type of non-dependent specialization is not a RecordType");
4017 } else {
4018 llvm_unreachable("Unhandled template kind");
4019 }
4020
4021 // Build the fully-sugared type for this class template
4022 // specialization, which refers back to the class template
4023 // specialization we created or found.
4024 return Context.getTemplateSpecializationType(
4025 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4026 CanonType);
4027}
4028
4030 TemplateNameKind &TNK,
4031 SourceLocation NameLoc,
4032 IdentifierInfo *&II) {
4033 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4034
4035 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4036 assert(ATN && "not an assumed template name");
4037 II = ATN->getDeclName().getAsIdentifierInfo();
4038
4039 if (TemplateName Name =
4040 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4041 !Name.isNull()) {
4042 // Resolved to a type template name.
4043 ParsedName = TemplateTy::make(Name);
4044 TNK = TNK_Type_template;
4045 }
4046}
4047
4049 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4050 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4051 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4052 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4053 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4054 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4055 ImplicitTypenameContext AllowImplicitTypename) {
4056 if (SS.isInvalid())
4057 return true;
4058
4059 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4060 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4061
4062 // C++ [temp.res]p3:
4063 // A qualified-id that refers to a type and in which the
4064 // nested-name-specifier depends on a template-parameter (14.6.2)
4065 // shall be prefixed by the keyword typename to indicate that the
4066 // qualified-id denotes a type, forming an
4067 // elaborated-type-specifier (7.1.5.3).
4068 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4069 // C++2a relaxes some of those restrictions in [temp.res]p5.
4070 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4071 SS.getScopeRep(), TemplateII);
4073 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4074 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4075 << NNS;
4076 if (!getLangOpts().CPlusPlus20)
4077 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4078 } else
4079 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4080
4081 // FIXME: This is not quite correct recovery as we don't transform SS
4082 // into the corresponding dependent form (and we don't diagnose missing
4083 // 'template' keywords within SS as a result).
4084 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4085 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4086 TemplateArgsIn, RAngleLoc);
4087 }
4088
4089 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4090 // it's not actually allowed to be used as a type in most cases. Because
4091 // we annotate it before we know whether it's valid, we have to check for
4092 // this case here.
4093 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4094 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4095 Diag(TemplateIILoc,
4096 TemplateKWLoc.isInvalid()
4097 ? diag::err_out_of_line_qualified_id_type_names_constructor
4098 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4099 << TemplateII << 0 /*injected-class-name used as template name*/
4100 << 1 /*if any keyword was present, it was 'template'*/;
4101 }
4102 }
4103
4104 // Translate the parser's template argument list in our AST format.
4105 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4106 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4107
4109 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4110 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4111 if (SpecTy.isNull())
4112 return true;
4113
4114 // Build type-source information.
4115 TypeLocBuilder TLB;
4116 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4117 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4118 TemplateIILoc, TemplateArgs);
4119 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4120}
4121
4123 TypeSpecifierType TagSpec,
4124 SourceLocation TagLoc,
4125 CXXScopeSpec &SS,
4126 SourceLocation TemplateKWLoc,
4127 TemplateTy TemplateD,
4128 SourceLocation TemplateLoc,
4129 SourceLocation LAngleLoc,
4130 ASTTemplateArgsPtr TemplateArgsIn,
4131 SourceLocation RAngleLoc) {
4132 if (SS.isInvalid())
4133 return TypeResult(true);
4134
4135 // Translate the parser's template argument list in our AST format.
4136 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4137 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4138
4139 // Determine the tag kind
4143
4145 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4146 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4147 if (Result.isNull())
4148 return TypeResult(true);
4149
4150 // Check the tag kind
4151 if (const RecordType *RT = Result->getAs<RecordType>()) {
4152 RecordDecl *D = RT->getDecl();
4153
4154 IdentifierInfo *Id = D->getIdentifier();
4155 assert(Id && "templated class must have an identifier");
4156
4158 TagLoc, Id)) {
4159 Diag(TagLoc, diag::err_use_with_wrong_tag)
4160 << Result
4162 Diag(D->getLocation(), diag::note_previous_use);
4163 }
4164 }
4165
4166 // Provide source-location information for the template specialization.
4167 TypeLocBuilder TLB;
4169 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4170 TemplateArgs);
4172}
4173
4174static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4175 NamedDecl *PrevDecl,
4176 SourceLocation Loc,
4178
4180
4182 unsigned Depth,
4183 unsigned Index) {
4184 switch (Arg.getKind()) {
4192 return false;
4193
4195 QualType Type = Arg.getAsType();
4196 const TemplateTypeParmType *TPT =
4197 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4198 return TPT && !Type.hasQualifiers() &&
4199 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4200 }
4201
4203 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4204 if (!DRE || !DRE->getDecl())
4205 return false;
4206 const NonTypeTemplateParmDecl *NTTP =
4207 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4208 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4209 }
4210
4212 const TemplateTemplateParmDecl *TTP =
4213 dyn_cast_or_null<TemplateTemplateParmDecl>(
4215 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4216 }
4217 llvm_unreachable("unexpected kind of template argument");
4218}
4219
4221 TemplateParameterList *SpecParams,
4223 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4224 return false;
4225
4226 unsigned Depth = Params->getDepth();
4227
4228 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4229 TemplateArgument Arg = Args[I];
4230
4231 // If the parameter is a pack expansion, the argument must be a pack
4232 // whose only element is a pack expansion.
4233 if (Params->getParam(I)->isParameterPack()) {
4234 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4235 !Arg.pack_begin()->isPackExpansion())
4236 return false;
4237 Arg = Arg.pack_begin()->getPackExpansionPattern();
4238 }
4239
4240 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4241 return false;
4242
4243 // For NTTPs further specialization is allowed via deduced types, so
4244 // we need to make sure to only reject here if primary template and
4245 // specialization use the same type for the NTTP.
4246 if (auto *SpecNTTP =
4247 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4248 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4249 if (!NTTP || NTTP->getType().getCanonicalType() !=
4250 SpecNTTP->getType().getCanonicalType())
4251 return false;
4252 }
4253 }
4254
4255 return true;
4256}
4257
4258template<typename PartialSpecDecl>
4259static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4260 if (Partial->getDeclContext()->isDependentContext())
4261 return;
4262
4263 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4264 // for non-substitution-failure issues?
4265 TemplateDeductionInfo Info(Partial->getLocation());
4266 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4267 return;
4268
4269 auto *Template = Partial->getSpecializedTemplate();
4270 S.Diag(Partial->getLocation(),
4271 diag::ext_partial_spec_not_more_specialized_than_primary)
4273
4274 if (Info.hasSFINAEDiagnostic()) {
4278 SmallString<128> SFINAEArgString;
4279 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4280 S.Diag(Diag.first,
4281 diag::note_partial_spec_not_more_specialized_than_primary)
4282 << SFINAEArgString;
4283 }
4284
4286 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4287 Template->getAssociatedConstraints(TemplateAC);
4288 Partial->getAssociatedConstraints(PartialAC);
4290 TemplateAC);
4291}
4292
4293static void
4295 const llvm::SmallBitVector &DeducibleParams) {
4296 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4297 if (!DeducibleParams[I]) {
4298 NamedDecl *Param = TemplateParams->getParam(I);
4299 if (Param->getDeclName())
4300 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4301 << Param->getDeclName();
4302 else
4303 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4304 << "(anonymous)";
4305 }
4306 }
4307}
4308
4309
4310template<typename PartialSpecDecl>
4312 PartialSpecDecl *Partial) {
4313 // C++1z [temp.class.spec]p8: (DR1495)
4314 // - The specialization shall be more specialized than the primary
4315 // template (14.5.5.2).
4317
4318 // C++ [temp.class.spec]p8: (DR1315)
4319 // - Each template-parameter shall appear at least once in the
4320 // template-id outside a non-deduced context.
4321 // C++1z [temp.class.spec.match]p3 (P0127R2)
4322 // If the template arguments of a partial specialization cannot be
4323 // deduced because of the structure of its template-parameter-list
4324 // and the template-id, the program is ill-formed.
4325 auto *TemplateParams = Partial->getTemplateParameters();
4326 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4327 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4328 TemplateParams->getDepth(), DeducibleParams);
4329
4330 if (!DeducibleParams.all()) {
4331 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4332 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4334 << (NumNonDeducible > 1)
4335 << SourceRange(Partial->getLocation(),
4336 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4337 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4338 }
4339}
4340
4345
4350
4352 // C++1z [temp.param]p11:
4353 // A template parameter of a deduction guide template that does not have a
4354 // default-argument shall be deducible from the parameter-type-list of the
4355 // deduction guide template.
4356 auto *TemplateParams = TD->getTemplateParameters();
4357 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4358 MarkDeducedTemplateParameters(TD, DeducibleParams);
4359 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4360 // A parameter pack is deducible (to an empty pack).
4361 auto *Param = TemplateParams->getParam(I);
4362 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4363 DeducibleParams[I] = true;
4364 }
4365
4366 if (!DeducibleParams.all()) {
4367 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4368 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4369 << (NumNonDeducible > 1);
4370 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4371 }
4372}
4373
4376 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4378 // D must be variable template id.
4380 "Variable template specialization is declared with a template id.");
4381
4382 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4383 TemplateArgumentListInfo TemplateArgs =
4384 makeTemplateArgumentListInfo(*this, *TemplateId);
4385 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4386 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4387 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4388
4389 TemplateName Name = TemplateId->Template.get();
4390
4391 // The template-id must name a variable template.
4393 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4394 if (!VarTemplate) {
4395 NamedDecl *FnTemplate;
4396 if (auto *OTS = Name.getAsOverloadedTemplate())
4397 FnTemplate = *OTS->begin();
4398 else
4399 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4400 if (FnTemplate)
4401 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4402 << FnTemplate->getDeclName();
4403 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4405 }
4406
4407 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4408 auto Message = DSA->getMessage();
4409 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4410 << VarTemplate << !Message.empty() << Message;
4411 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4412 }
4413
4414 // Check for unexpanded parameter packs in any of the template arguments.
4415 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4416 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4420 return true;
4421
4422 // Check that the template argument list is well-formed for this
4423 // template.
4425 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4426 /*DefaultArgs=*/{},
4427 /*PartialTemplateArgs=*/false, CTAI,
4428 /*UpdateArgsWithConversions=*/true))
4429 return true;
4430
4431 // Find the variable template (partial) specialization declaration that
4432 // corresponds to these arguments.
4435 TemplateArgs.size(),
4436 CTAI.CanonicalConverted))
4437 return true;
4438
4439 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4440 // we also do them during instantiation.
4441 if (!Name.isDependent() &&
4442 !TemplateSpecializationType::anyDependentTemplateArguments(
4443 TemplateArgs, CTAI.CanonicalConverted)) {
4444 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4445 << VarTemplate->getDeclName();
4447 }
4448
4449 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4450 TemplateParams, CTAI.CanonicalConverted) &&
4451 (!Context.getLangOpts().CPlusPlus20 ||
4452 !TemplateParams->hasAssociatedConstraints())) {
4453 // C++ [temp.class.spec]p9b3:
4454 //
4455 // -- The argument list of the specialization shall not be identical
4456 // to the implicit argument list of the primary template.
4457 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4458 << /*variable template*/ 1
4459 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4460 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4461 // FIXME: Recover from this by treating the declaration as a
4462 // redeclaration of the primary template.
4463 return true;
4464 }
4465 }
4466
4467 void *InsertPos = nullptr;
4468 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4469
4471 PrevDecl = VarTemplate->findPartialSpecialization(
4472 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4473 else
4474 PrevDecl =
4475 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4476
4478
4479 // Check whether we can declare a variable template specialization in
4480 // the current scope.
4481 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4482 TemplateNameLoc,
4484 return true;
4485
4486 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4487 // Since the only prior variable template specialization with these
4488 // arguments was referenced but not declared, reuse that
4489 // declaration node as our own, updating its source location and
4490 // the list of outer template parameters to reflect our new declaration.
4491 Specialization = PrevDecl;
4492 Specialization->setLocation(TemplateNameLoc);
4493 PrevDecl = nullptr;
4494 } else if (IsPartialSpecialization) {
4495 // Create a new class template partial specialization declaration node.
4497 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4500 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4501 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4502 SC, CTAI.CanonicalConverted);
4503 Partial->setTemplateArgsAsWritten(TemplateArgs);
4504
4505 if (!PrevPartial)
4506 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4507 Specialization = Partial;
4508
4510 } else {
4511 // Create a new class template specialization declaration node for
4512 // this explicit specialization or friend declaration.
4514 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4515 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4516 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4517
4518 if (!PrevDecl)
4519 VarTemplate->AddSpecialization(Specialization, InsertPos);
4520 }
4521
4522 // C++ [temp.expl.spec]p6:
4523 // If a template, a member template or the member of a class template is
4524 // explicitly specialized then that specialization shall be declared
4525 // before the first use of that specialization that would cause an implicit
4526 // instantiation to take place, in every translation unit in which such a
4527 // use occurs; no diagnostic is required.
4528 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4529 bool Okay = false;
4530 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4531 // Is there any previous explicit specialization declaration?
4533 Okay = true;
4534 break;
4535 }
4536 }
4537
4538 if (!Okay) {
4539 SourceRange Range(TemplateNameLoc, RAngleLoc);
4540 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4541 << Name << Range;
4542
4543 Diag(PrevDecl->getPointOfInstantiation(),
4544 diag::note_instantiation_required_here)
4545 << (PrevDecl->getTemplateSpecializationKind() !=
4547 return true;
4548 }
4549 }
4550
4551 Specialization->setLexicalDeclContext(CurContext);
4552
4553 // Add the specialization into its lexical context, so that it can
4554 // be seen when iterating through the list of declarations in that
4555 // context. However, specializations are not found by name lookup.
4556 CurContext->addDecl(Specialization);
4557
4558 // Note that this is an explicit specialization.
4559 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4560
4561 Previous.clear();
4562 if (PrevDecl)
4563 Previous.addDecl(PrevDecl);
4564 else if (Specialization->isStaticDataMember() &&
4565 Specialization->isOutOfLine())
4566 Specialization->setAccess(VarTemplate->getAccess());
4567
4568 return Specialization;
4569}
4570
4571namespace {
4572/// A partial specialization whose template arguments have matched
4573/// a given template-id.
4574struct PartialSpecMatchResult {
4577};
4578
4579// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4580// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4581static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4582 if (Var->getName() != "format_kind" ||
4583 !Var->getDeclContext()->isStdNamespace())
4584 return false;
4585
4586 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4587 // release in which users can access std::format_kind.
4588 // We can use 20250520 as the final date, see the following commits.
4589 // GCC releases/gcc-15 branch:
4590 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4591 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4592 // GCC master branch:
4593 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4594 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4595 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4596}
4597} // end anonymous namespace
4598
4601 SourceLocation TemplateNameLoc,
4602 const TemplateArgumentListInfo &TemplateArgs,
4603 bool SetWrittenArgs) {
4604 assert(Template && "A variable template id without template?");
4605
4606 // Check that the template argument list is well-formed for this template.
4609 Template, TemplateNameLoc,
4610 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4611 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4612 /*UpdateArgsWithConversions=*/true))
4613 return true;
4614
4615 // Produce a placeholder value if the specialization is dependent.
4616 if (Template->getDeclContext()->isDependentContext() ||
4617 TemplateSpecializationType::anyDependentTemplateArguments(
4618 TemplateArgs, CTAI.CanonicalConverted)) {
4619 if (ParsingInitForAutoVars.empty())
4620 return DeclResult();
4621
4622 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4623 const TemplateArgument &Arg2) {
4624 return Context.isSameTemplateArgument(Arg1, Arg2);
4625 };
4626
4627 if (VarDecl *Var = Template->getTemplatedDecl();
4628 ParsingInitForAutoVars.count(Var) &&
4629 // See comments on this function definition
4630 !IsLibstdcxxStdFormatKind(PP, Var) &&
4631 llvm::equal(
4632 CTAI.CanonicalConverted,
4633 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4634 IsSameTemplateArg)) {
4635 Diag(TemplateNameLoc,
4636 diag::err_auto_variable_cannot_appear_in_own_initializer)
4637 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4638 return true;
4639 }
4640
4642 Template->getPartialSpecializations(PartialSpecs);
4643 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4644 if (ParsingInitForAutoVars.count(Partial) &&
4645 llvm::equal(CTAI.CanonicalConverted,
4646 Partial->getTemplateArgs().asArray(),
4647 IsSameTemplateArg)) {
4648 Diag(TemplateNameLoc,
4649 diag::err_auto_variable_cannot_appear_in_own_initializer)
4650 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4651 << Partial->getType();
4652 return true;
4653 }
4654
4655 return DeclResult();
4656 }
4657
4658 // Find the variable template specialization declaration that
4659 // corresponds to these arguments.
4660 void *InsertPos = nullptr;
4662 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4663 checkSpecializationReachability(TemplateNameLoc, Spec);
4664 if (Spec->getType()->isUndeducedType()) {
4665 if (ParsingInitForAutoVars.count(Spec))
4666 Diag(TemplateNameLoc,
4667 diag::err_auto_variable_cannot_appear_in_own_initializer)
4668 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4669 << Spec->getType();
4670 else
4671 // We are substituting the initializer of this variable template
4672 // specialization.
4673 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4674 << Spec << Spec->getType();
4675
4676 return true;
4677 }
4678 // If we already have a variable template specialization, return it.
4679 return Spec;
4680 }
4681
4682 // This is the first time we have referenced this variable template
4683 // specialization. Create the canonical declaration and add it to
4684 // the set of specializations, based on the closest partial specialization
4685 // that it represents. That is,
4686 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4687 const TemplateArgumentList *PartialSpecArgs = nullptr;
4688 bool AmbiguousPartialSpec = false;
4689 typedef PartialSpecMatchResult MatchResult;
4691 SourceLocation PointOfInstantiation = TemplateNameLoc;
4692 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4693 /*ForTakingAddress=*/false);
4694
4695 // 1. Attempt to find the closest partial specialization that this
4696 // specializes, if any.
4697 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4698 // Perhaps better after unification of DeduceTemplateArguments() and
4699 // getMoreSpecializedPartialSpecialization().
4701 Template->getPartialSpecializations(PartialSpecs);
4702
4703 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4704 // C++ [temp.spec.partial.member]p2:
4705 // If the primary member template is explicitly specialized for a given
4706 // (implicit) specialization of the enclosing class template, the partial
4707 // specializations of the member template are ignored for this
4708 // specialization of the enclosing class template. If a partial
4709 // specialization of the member template is explicitly specialized for a
4710 // given (implicit) specialization of the enclosing class template, the
4711 // primary member template and its other partial specializations are still
4712 // considered for this specialization of the enclosing class template.
4713 if (Template->isMemberSpecialization() &&
4714 !Partial->isMemberSpecialization())
4715 continue;
4716
4717 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4718
4720 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4722 // Store the failed-deduction information for use in diagnostics, later.
4723 // TODO: Actually use the failed-deduction info?
4724 FailedCandidates.addCandidate().set(
4727 (void)Result;
4728 } else {
4729 Matched.push_back(PartialSpecMatchResult());
4730 Matched.back().Partial = Partial;
4731 Matched.back().Args = Info.takeSugared();
4732 }
4733 }
4734
4735 if (Matched.size() >= 1) {
4736 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4737 if (Matched.size() == 1) {
4738 // -- If exactly one matching specialization is found, the
4739 // instantiation is generated from that specialization.
4740 // We don't need to do anything for this.
4741 } else {
4742 // -- If more than one matching specialization is found, the
4743 // partial order rules (14.5.4.2) are used to determine
4744 // whether one of the specializations is more specialized
4745 // than the others. If none of the specializations is more
4746 // specialized than all of the other matching
4747 // specializations, then the use of the variable template is
4748 // ambiguous and the program is ill-formed.
4749 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4750 PEnd = Matched.end();
4751 P != PEnd; ++P) {
4752 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4753 PointOfInstantiation) ==
4754 P->Partial)
4755 Best = P;
4756 }
4757
4758 // Determine if the best partial specialization is more specialized than
4759 // the others.
4760 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4761 PEnd = Matched.end();
4762 P != PEnd; ++P) {
4764 P->Partial, Best->Partial,
4765 PointOfInstantiation) != Best->Partial) {
4766 AmbiguousPartialSpec = true;
4767 break;
4768 }
4769 }
4770 }
4771
4772 // Instantiate using the best variable template partial specialization.
4773 InstantiationPattern = Best->Partial;
4774 PartialSpecArgs = Best->Args;
4775 } else {
4776 // -- If no match is found, the instantiation is generated
4777 // from the primary template.
4778 // InstantiationPattern = Template->getTemplatedDecl();
4779 }
4780
4781 // 2. Create the canonical declaration.
4782 // Note that we do not instantiate a definition until we see an odr-use
4783 // in DoMarkVarDeclReferenced().
4784 // FIXME: LateAttrs et al.?
4785 if (AmbiguousPartialSpec) {
4786 // Partial ordering did not produce a clear winner. Complain.
4787 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4788 << Template;
4789 // Print the matching partial specializations.
4790 for (MatchResult P : Matched)
4791 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4792 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4793 *P.Args);
4794 return true;
4795 }
4796
4798 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4799 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4800 if (!Decl)
4801 return true;
4802 if (SetWrittenArgs)
4803 Decl->setTemplateArgsAsWritten(TemplateArgs);
4804
4806 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4807 Decl->setInstantiationOf(D, PartialSpecArgs);
4808
4809 checkSpecializationReachability(TemplateNameLoc, Decl);
4810
4811 assert(Decl && "No variable template specialization?");
4812 return Decl;
4813}
4814
4816 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4817 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4818 const TemplateArgumentListInfo *TemplateArgs) {
4819
4820 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4821 *TemplateArgs, /*SetWrittenArgs=*/false);
4822 if (Decl.isInvalid())
4823 return ExprError();
4824
4825 if (!Decl.get())
4826 return ExprResult();
4827
4828 VarDecl *Var = cast<VarDecl>(Decl.get());
4831 NameInfo.getLoc());
4832
4833 // Build an ordinary singleton decl ref.
4834 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4835}
4836
4838 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4840 const TemplateArgumentListInfo *TemplateArgs) {
4841 assert(Template && "A variable template id without template?");
4842
4843 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4844 Template->templateParameterKind() !=
4846 return ExprResult();
4847
4848 // Check that the template argument list is well-formed for this template.
4851 Template, TemplateLoc,
4852 // FIXME: TemplateArgs will not be modified because
4853 // UpdateArgsWithConversions is false, however, we should
4854 // CheckTemplateArgumentList to be const-correct.
4855 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4856 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4857 /*UpdateArgsWithConversions=*/false))
4858 return true;
4859
4861 R.addDecl(Template);
4862
4863 // FIXME: We model references to variable template and concept parameters
4864 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4865 // data, can generally be used in the same places and work the same way.
4866 // However, it might be cleaner to use a dedicated AST node in the long run.
4869 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4870 /*KnownDependent=*/false,
4871 /*KnownInstantiationDependent=*/false);
4872}
4873
4875 SourceLocation Loc) {
4876 Diag(Loc, diag::err_template_missing_args)
4877 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4878 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4879 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4880 }
4881}
4882
4884 bool TemplateKeyword,
4885 TemplateDecl *TD,
4886 SourceLocation Loc) {
4887 TemplateName Name = Context.getQualifiedTemplateName(
4888 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4890}
4891
4893 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4894 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4895 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4896 bool DoCheckConstraintSatisfaction) {
4897 assert(NamedConcept && "A concept template id without a template?");
4898
4899 if (NamedConcept->isInvalidDecl())
4900 return ExprError();
4901
4904 NamedConcept, ConceptNameInfo.getLoc(),
4905 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4906 /*DefaultArgs=*/{},
4907 /*PartialTemplateArgs=*/false, CTAI,
4908 /*UpdateArgsWithConversions=*/false))
4909 return ExprError();
4910
4911 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4912
4913 // There's a bug with CTAI.CanonicalConverted.
4914 // If the template argument contains a DependentDecltypeType that includes a
4915 // TypeAliasType, and the same written type had occurred previously in the
4916 // source, then the DependentDecltypeType would be canonicalized to that
4917 // previous type which would mess up the substitution.
4918 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4920 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4921 CTAI.SugaredConverted);
4922 ConstraintSatisfaction Satisfaction;
4923 bool AreArgsDependent =
4924 TemplateSpecializationType::anyDependentTemplateArguments(
4925 *TemplateArgs, CTAI.SugaredConverted);
4926 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4927 /*Final=*/false);
4929 Context,
4931 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4933
4934 bool Error = false;
4935 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4936 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4937 DoCheckConstraintSatisfaction) {
4938
4940
4943
4945 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4946 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4947 TemplateArgs->getRAngleLoc()),
4948 Satisfaction, CL);
4949 Satisfaction.ContainsErrors = Error;
4950 }
4951
4952 if (Error)
4953 return ExprError();
4954
4956 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4957}
4958
4960 SourceLocation TemplateKWLoc,
4961 LookupResult &R,
4962 bool RequiresADL,
4963 const TemplateArgumentListInfo *TemplateArgs) {
4964 // FIXME: Can we do any checking at this point? I guess we could check the
4965 // template arguments that we have against the template name, if the template
4966 // name refers to a single template. That's not a terribly common case,
4967 // though.
4968 // foo<int> could identify a single function unambiguously
4969 // This approach does NOT work, since f<int>(1);
4970 // gets resolved prior to resorting to overload resolution
4971 // i.e., template<class T> void f(double);
4972 // vs template<class T, class U> void f(U);
4973
4974 // These should be filtered out by our callers.
4975 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4976
4977 // Non-function templates require a template argument list.
4978 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4979 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4981 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4982 return ExprError();
4983 }
4984 }
4985 bool KnownDependent = false;
4986 // In C++1y, check variable template ids.
4987 if (R.getAsSingle<VarTemplateDecl>()) {
4989 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4990 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4991 if (Res.isInvalid() || Res.isUsable())
4992 return Res;
4993 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4994 KnownDependent = true;
4995 }
4996
4997 // We don't want lookup warnings at this point.
4998 R.suppressDiagnostics();
4999
5000 if (R.getAsSingle<ConceptDecl>()) {
5001 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5002 R.getRepresentativeDecl(),
5003 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5004 }
5005
5006 // Check variable template ids (C++17) and concept template parameters
5007 // (C++26).
5009 if (R.getAsSingle<TemplateTemplateParmDecl>())
5011 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
5012 TemplateKWLoc, TemplateArgs);
5013
5014 // Function templates
5016 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5017 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5018 R.begin(), R.end(), KnownDependent,
5019 /*KnownInstantiationDependent=*/false);
5020 // Model the templates with UnresolvedTemplateTy. The expression should then
5021 // either be transformed in an instantiation or be diagnosed in
5022 // CheckPlaceholderExpr.
5023 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5024 !R.getFoundDecl()->getAsFunction())
5025 ULE->setType(Context.UnresolvedTemplateTy);
5026
5027 return ULE;
5028}
5029
5031 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5032 const DeclarationNameInfo &NameInfo,
5033 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5034 assert(TemplateArgs || TemplateKWLoc.isValid());
5035
5036 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5037 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5038 /*EnteringContext=*/false, TemplateKWLoc))
5039 return ExprError();
5040
5041 if (R.isAmbiguous())
5042 return ExprError();
5043
5044 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5045 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5046
5047 if (R.empty()) {
5049 Diag(NameInfo.getLoc(), diag::err_no_member)
5050 << NameInfo.getName() << DC << SS.getRange();
5051 return ExprError();
5052 }
5053
5054 // If necessary, build an implicit class member access.
5055 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5056 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5057 /*S=*/nullptr);
5058
5059 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5060}
5061
5063 CXXScopeSpec &SS,
5064 SourceLocation TemplateKWLoc,
5065 const UnqualifiedId &Name,
5066 ParsedType ObjectType,
5067 bool EnteringContext,
5069 bool AllowInjectedClassName) {
5070 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5071 Diag(TemplateKWLoc,
5073 diag::warn_cxx98_compat_template_outside_of_template :
5074 diag::ext_template_outside_of_template)
5075 << FixItHint::CreateRemoval(TemplateKWLoc);
5076
5077 if (SS.isInvalid())
5078 return TNK_Non_template;
5079
5080 // Figure out where isTemplateName is going to look.
5081 DeclContext *LookupCtx = nullptr;
5082 if (SS.isNotEmpty())
5083 LookupCtx = computeDeclContext(SS, EnteringContext);
5084 else if (ObjectType)
5085 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5086
5087 // C++0x [temp.names]p5:
5088 // If a name prefixed by the keyword template is not the name of
5089 // a template, the program is ill-formed. [Note: the keyword
5090 // template may not be applied to non-template members of class
5091 // templates. -end note ] [ Note: as is the case with the
5092 // typename prefix, the template prefix is allowed in cases
5093 // where it is not strictly necessary; i.e., when the
5094 // nested-name-specifier or the expression on the left of the ->
5095 // or . is not dependent on a template-parameter, or the use
5096 // does not appear in the scope of a template. -end note]
5097 //
5098 // Note: C++03 was more strict here, because it banned the use of
5099 // the "template" keyword prior to a template-name that was not a
5100 // dependent name. C++ DR468 relaxed this requirement (the
5101 // "template" keyword is now permitted). We follow the C++0x
5102 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5103 bool MemberOfUnknownSpecialization;
5104 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5105 ObjectType, EnteringContext, Result,
5106 MemberOfUnknownSpecialization);
5107 if (TNK != TNK_Non_template) {
5108 // We resolved this to a (non-dependent) template name. Return it.
5109 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5110 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5112 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5113 // C++14 [class.qual]p2:
5114 // In a lookup in which function names are not ignored and the
5115 // nested-name-specifier nominates a class C, if the name specified
5116 // [...] is the injected-class-name of C, [...] the name is instead
5117 // considered to name the constructor
5118 //
5119 // We don't get here if naming the constructor would be valid, so we
5120 // just reject immediately and recover by treating the
5121 // injected-class-name as naming the template.
5122 Diag(Name.getBeginLoc(),
5123 diag::ext_out_of_line_qualified_id_type_names_constructor)
5124 << Name.Identifier
5125 << 0 /*injected-class-name used as template name*/
5126 << TemplateKWLoc.isValid();
5127 }
5128 return TNK;
5129 }
5130
5131 if (!MemberOfUnknownSpecialization) {
5132 // Didn't find a template name, and the lookup wasn't dependent.
5133 // Do the lookup again to determine if this is a "nothing found" case or
5134 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5135 // need to do this.
5137 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5139 // Tell LookupTemplateName that we require a template so that it diagnoses
5140 // cases where it finds a non-template.
5141 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5142 ? RequiredTemplateKind(TemplateKWLoc)
5144 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5145 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5146 !R.isAmbiguous()) {
5147 if (LookupCtx)
5148 Diag(Name.getBeginLoc(), diag::err_no_member)
5149 << DNI.getName() << LookupCtx << SS.getRange();
5150 else
5151 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5152 << DNI.getName() << SS.getRange();
5153 }
5154 return TNK_Non_template;
5155 }
5156
5157 NestedNameSpecifier Qualifier = SS.getScopeRep();
5158
5159 switch (Name.getKind()) {
5161 Result = TemplateTy::make(Context.getDependentTemplateName(
5162 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5164
5166 Result = TemplateTy::make(Context.getDependentTemplateName(
5167 {Qualifier, Name.OperatorFunctionId.Operator,
5168 TemplateKWLoc.isValid()}));
5169 return TNK_Function_template;
5170
5172 // This is a kind of template name, but can never occur in a dependent
5173 // scope (literal operators can only be declared at namespace scope).
5174 break;
5175
5176 default:
5177 break;
5178 }
5179
5180 // This name cannot possibly name a dependent template. Diagnose this now
5181 // rather than building a dependent template name that can never be valid.
5182 Diag(Name.getBeginLoc(),
5183 diag::err_template_kw_refers_to_dependent_non_template)
5185 << TemplateKWLoc.isValid() << TemplateKWLoc;
5186 return TNK_Non_template;
5187}
5188
5191 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5192 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5193 const TemplateArgument &Arg = AL.getArgument();
5195 TypeSourceInfo *TSI = nullptr;
5196
5197 // Check template type parameter.
5198 switch(Arg.getKind()) {
5200 // C++ [temp.arg.type]p1:
5201 // A template-argument for a template-parameter which is a
5202 // type shall be a type-id.
5203 ArgType = Arg.getAsType();
5204 TSI = AL.getTypeSourceInfo();
5205 break;
5208 // We have a template type parameter but the template argument
5209 // is a template without any arguments.
5210 SourceRange SR = AL.getSourceRange();
5213 return true;
5214 }
5216 // We have a template type parameter but the template argument is an
5217 // expression; see if maybe it is missing the "typename" keyword.
5218 CXXScopeSpec SS;
5219 DeclarationNameInfo NameInfo;
5220
5221 if (DependentScopeDeclRefExpr *ArgExpr =
5222 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5223 SS.Adopt(ArgExpr->getQualifierLoc());
5224 NameInfo = ArgExpr->getNameInfo();
5225 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5226 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5227 if (ArgExpr->isImplicitAccess()) {
5228 SS.Adopt(ArgExpr->getQualifierLoc());
5229 NameInfo = ArgExpr->getMemberNameInfo();
5230 }
5231 }
5232
5233 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5234 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5235 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5236
5237 if (Result.getAsSingle<TypeDecl>() ||
5238 Result.wasNotFoundInCurrentInstantiation()) {
5239 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5240 // Suggest that the user add 'typename' before the NNS.
5242 Diag(Loc, getLangOpts().MSVCCompat
5243 ? diag::ext_ms_template_type_arg_missing_typename
5244 : diag::err_template_arg_must_be_type_suggest)
5245 << FixItHint::CreateInsertion(Loc, "typename ");
5247
5248 // Recover by synthesizing a type using the location information that we
5249 // already have.
5250 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5251 SS.getScopeRep(), II);
5252 TypeLocBuilder TLB;
5254 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5256 TL.setNameLoc(NameInfo.getLoc());
5257 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5258
5259 // Overwrite our input TemplateArgumentLoc so that we can recover
5260 // properly.
5263
5264 break;
5265 }
5266 }
5267 // fallthrough
5268 [[fallthrough]];
5269 }
5270 default: {
5271 // We allow instantiating a template with template argument packs when
5272 // building deduction guides or mapping constraint template parameters.
5273 if (Arg.getKind() == TemplateArgument::Pack &&
5274 (CodeSynthesisContexts.back().Kind ==
5277 SugaredConverted.push_back(Arg);
5278 CanonicalConverted.push_back(Arg);
5279 return false;
5280 }
5281 // We have a template type parameter but the template argument
5282 // is not a type.
5283 SourceRange SR = AL.getSourceRange();
5284 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5286
5287 return true;
5288 }
5289 }
5290
5291 if (CheckTemplateArgument(TSI))
5292 return true;
5293
5294 // Objective-C ARC:
5295 // If an explicitly-specified template argument type is a lifetime type
5296 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5297 if (getLangOpts().ObjCAutoRefCount &&
5298 ArgType->isObjCLifetimeType() &&
5299 !ArgType.getObjCLifetime()) {
5300 Qualifiers Qs;
5302 ArgType = Context.getQualifiedType(ArgType, Qs);
5303 }
5304
5305 SugaredConverted.push_back(TemplateArgument(ArgType));
5306 CanonicalConverted.push_back(
5307 TemplateArgument(Context.getCanonicalType(ArgType)));
5308 return false;
5309}
5310
5311/// Substitute template arguments into the default template argument for
5312/// the given template type parameter.
5313///
5314/// \param SemaRef the semantic analysis object for which we are performing
5315/// the substitution.
5316///
5317/// \param Template the template that we are synthesizing template arguments
5318/// for.
5319///
5320/// \param TemplateLoc the location of the template name that started the
5321/// template-id we are checking.
5322///
5323/// \param RAngleLoc the location of the right angle bracket ('>') that
5324/// terminates the template-id.
5325///
5326/// \param Param the template template parameter whose default we are
5327/// substituting into.
5328///
5329/// \param Converted the list of template arguments provided for template
5330/// parameters that precede \p Param in the template parameter list.
5331///
5332/// \param Output the resulting substituted template argument.
5333///
5334/// \returns true if an error occurred.
5336 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5337 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5338 ArrayRef<TemplateArgument> SugaredConverted,
5339 ArrayRef<TemplateArgument> CanonicalConverted,
5340 TemplateArgumentLoc &Output) {
5341 Output = Param->getDefaultArgument();
5342
5343 // If the argument type is dependent, instantiate it now based
5344 // on the previously-computed template arguments.
5345 if (Output.getArgument().isInstantiationDependent()) {
5346 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5347 SugaredConverted,
5348 SourceRange(TemplateLoc, RAngleLoc));
5349 if (Inst.isInvalid())
5350 return true;
5351
5352 // Only substitute for the innermost template argument list.
5353 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5354 /*Final=*/true);
5355 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5356 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5357
5358 bool ForLambdaCallOperator = false;
5359 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5360 ForLambdaCallOperator = Rec->isLambda();
5361 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5362 !ForLambdaCallOperator);
5363
5364 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5365 Param->getDefaultArgumentLoc(),
5366 Param->getDeclName()))
5367 return true;
5368 }
5369
5370 return false;
5371}
5372
5373/// Substitute template arguments into the default template argument for
5374/// the given non-type template parameter.
5375///
5376/// \param SemaRef the semantic analysis object for which we are performing
5377/// the substitution.
5378///
5379/// \param Template the template that we are synthesizing template arguments
5380/// for.
5381///
5382/// \param TemplateLoc the location of the template name that started the
5383/// template-id we are checking.
5384///
5385/// \param RAngleLoc the location of the right angle bracket ('>') that
5386/// terminates the template-id.
5387///
5388/// \param Param the non-type template parameter whose default we are
5389/// substituting into.
5390///
5391/// \param Converted the list of template arguments provided for template
5392/// parameters that precede \p Param in the template parameter list.
5393///
5394/// \returns the substituted template argument, or NULL if an error occurred.
5396 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5397 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5398 ArrayRef<TemplateArgument> SugaredConverted,
5399 ArrayRef<TemplateArgument> CanonicalConverted,
5400 TemplateArgumentLoc &Output) {
5401 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5402 SugaredConverted,
5403 SourceRange(TemplateLoc, RAngleLoc));
5404 if (Inst.isInvalid())
5405 return true;
5406
5407 // Only substitute for the innermost template argument list.
5408 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5409 /*Final=*/true);
5410 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5411 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5412
5413 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5414 EnterExpressionEvaluationContext ConstantEvaluated(
5416 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5417 TemplateArgLists, Output);
5418}
5419
5420/// Substitute template arguments into the default template argument for
5421/// the given template template parameter.
5422///
5423/// \param SemaRef the semantic analysis object for which we are performing
5424/// the substitution.
5425///
5426/// \param Template the template that we are synthesizing template arguments
5427/// for.
5428///
5429/// \param TemplateLoc the location of the template name that started the
5430/// template-id we are checking.
5431///
5432/// \param RAngleLoc the location of the right angle bracket ('>') that
5433/// terminates the template-id.
5434///
5435/// \param Param the template template parameter whose default we are
5436/// substituting into.
5437///
5438/// \param Converted the list of template arguments provided for template
5439/// parameters that precede \p Param in the template parameter list.
5440///
5441/// \param QualifierLoc Will be set to the nested-name-specifier (with
5442/// source-location information) that precedes the template name.
5443///
5444/// \returns the substituted template argument, or NULL if an error occurred.
5446 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5447 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5449 ArrayRef<TemplateArgument> SugaredConverted,
5450 ArrayRef<TemplateArgument> CanonicalConverted,
5451 NestedNameSpecifierLoc &QualifierLoc) {
5453 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5454 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5455 if (Inst.isInvalid())
5456 return TemplateName();
5457
5458 // Only substitute for the innermost template argument list.
5459 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5460 /*Final=*/true);
5461 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5462 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5463
5464 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5465
5466 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5467 QualifierLoc = A.getTemplateQualifierLoc();
5468 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5470 A.getTemplateNameLoc(), TemplateArgLists);
5471}
5472
5474 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5475 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5476 ArrayRef<TemplateArgument> SugaredConverted,
5477 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5478 HasDefaultArg = false;
5479
5480 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5481 if (!hasReachableDefaultArgument(TypeParm))
5482 return TemplateArgumentLoc();
5483
5484 HasDefaultArg = true;
5485 TemplateArgumentLoc Output;
5486 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5487 RAngleLoc, TypeParm, SugaredConverted,
5488 CanonicalConverted, Output))
5489 return TemplateArgumentLoc();
5490 return Output;
5491 }
5492
5493 if (NonTypeTemplateParmDecl *NonTypeParm
5494 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5495 if (!hasReachableDefaultArgument(NonTypeParm))
5496 return TemplateArgumentLoc();
5497
5498 HasDefaultArg = true;
5499 TemplateArgumentLoc Output;
5500 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5501 RAngleLoc, NonTypeParm, SugaredConverted,
5502 CanonicalConverted, Output))
5503 return TemplateArgumentLoc();
5504 return Output;
5505 }
5506
5507 TemplateTemplateParmDecl *TempTempParm
5509 if (!hasReachableDefaultArgument(TempTempParm))
5510 return TemplateArgumentLoc();
5511
5512 HasDefaultArg = true;
5513 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5514 NestedNameSpecifierLoc QualifierLoc;
5516 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5517 SugaredConverted, CanonicalConverted, QualifierLoc);
5518 if (TName.isNull())
5519 return TemplateArgumentLoc();
5520
5521 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5522 QualifierLoc, A.getTemplateNameLoc());
5523}
5524
5525/// Convert a template-argument that we parsed as a type into a template, if
5526/// possible. C++ permits injected-class-names to perform dual service as
5527/// template template arguments and as template type arguments.
5530 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5531 if (!TagLoc)
5532 return TemplateArgumentLoc();
5533
5534 // If this type was written as an injected-class-name, it can be used as a
5535 // template template argument.
5536 // If this type was written as an injected-class-name, it may have been
5537 // converted to a RecordType during instantiation. If the RecordType is
5538 // *not* wrapped in a TemplateSpecializationType and denotes a class
5539 // template specialization, it must have come from an injected-class-name.
5540
5541 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5542 if (Name.isNull())
5543 return TemplateArgumentLoc();
5544
5545 return TemplateArgumentLoc(Context, Name,
5546 /*TemplateKWLoc=*/SourceLocation(),
5547 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5548}
5549
5552 SourceLocation TemplateLoc,
5553 SourceLocation RAngleLoc,
5554 unsigned ArgumentPackIndex,
5557 // Check template type parameters.
5558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5559 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5560 CTAI.CanonicalConverted);
5561
5562 const TemplateArgument &Arg = ArgLoc.getArgument();
5563 // Check non-type template parameters.
5564 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5565 // Do substitution on the type of the non-type template parameter
5566 // with the template arguments we've seen thus far. But if the
5567 // template has a dependent context then we cannot substitute yet.
5568 QualType NTTPType = NTTP->getType();
5569 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5570 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5571
5572 if (NTTPType->isInstantiationDependentType()) {
5573 // Do substitution on the type of the non-type template parameter.
5574 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5575 CTAI.SugaredConverted,
5576 SourceRange(TemplateLoc, RAngleLoc));
5577 if (Inst.isInvalid())
5578 return true;
5579
5581 /*Final=*/true);
5582 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5583 // If the parameter is a pack expansion, expand this slice of the pack.
5584 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5585 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5586 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5587 NTTP->getDeclName());
5588 } else {
5589 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5590 NTTP->getDeclName());
5591 }
5592
5593 // If that worked, check the non-type template parameter type
5594 // for validity.
5595 if (!NTTPType.isNull())
5596 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5597 NTTP->getLocation());
5598 if (NTTPType.isNull())
5599 return true;
5600 }
5601
5602 auto checkExpr = [&](Expr *E) -> Expr * {
5603 TemplateArgument SugaredResult, CanonicalResult;
5605 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5606 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5607 // If the current template argument causes an error, give up now.
5608 if (Res.isInvalid())
5609 return nullptr;
5610 CTAI.SugaredConverted.push_back(SugaredResult);
5611 CTAI.CanonicalConverted.push_back(CanonicalResult);
5612 return Res.get();
5613 };
5614
5615 switch (Arg.getKind()) {
5617 llvm_unreachable("Should never see a NULL template argument here");
5618
5620 Expr *E = Arg.getAsExpr();
5621 Expr *R = checkExpr(E);
5622 if (!R)
5623 return true;
5624 // If the resulting expression is new, then use it in place of the
5625 // old expression in the template argument.
5626 if (R != E) {
5627 TemplateArgument TA(R, /*IsCanonical=*/false);
5628 ArgLoc = TemplateArgumentLoc(TA, R);
5629 }
5630 break;
5631 }
5632
5633 // As for the converted NTTP kinds, they still might need another
5634 // conversion, as the new corresponding parameter might be different.
5635 // Ideally, we would always perform substitution starting with sugared types
5636 // and never need these, as we would still have expressions. Since these are
5637 // needed so rarely, it's probably a better tradeoff to just convert them
5638 // back to expressions.
5643 // FIXME: StructuralValue is untested here.
5644 ExprResult R =
5646 assert(R.isUsable());
5647 if (!checkExpr(R.get()))
5648 return true;
5649 break;
5650 }
5651
5654 // We were given a template template argument. It may not be ill-formed;
5655 // see below.
5658 // We have a template argument such as \c T::template X, which we
5659 // parsed as a template template argument. However, since we now
5660 // know that we need a non-type template argument, convert this
5661 // template name into an expression.
5662
5663 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5664 ArgLoc.getTemplateNameLoc());
5665
5666 CXXScopeSpec SS;
5667 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5668 // FIXME: the template-template arg was a DependentTemplateName,
5669 // so it was provided with a template keyword. However, its source
5670 // location is not stored in the template argument structure.
5671 SourceLocation TemplateKWLoc;
5673 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5674 nullptr);
5675
5676 // If we parsed the template argument as a pack expansion, create a
5677 // pack expansion expression.
5680 if (E.isInvalid())
5681 return true;
5682 }
5683
5684 TemplateArgument SugaredResult, CanonicalResult;
5686 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5687 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5688 if (E.isInvalid())
5689 return true;
5690
5691 CTAI.SugaredConverted.push_back(SugaredResult);
5692 CTAI.CanonicalConverted.push_back(CanonicalResult);
5693 break;
5694 }
5695
5696 // We have a template argument that actually does refer to a class
5697 // template, alias template, or template template parameter, and
5698 // therefore cannot be a non-type template argument.
5699 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5700 << ArgLoc.getSourceRange();
5702
5703 return true;
5704
5706 // We have a non-type template parameter but the template
5707 // argument is a type.
5708
5709 // C++ [temp.arg]p2:
5710 // In a template-argument, an ambiguity between a type-id and
5711 // an expression is resolved to a type-id, regardless of the
5712 // form of the corresponding template-parameter.
5713 //
5714 // We warn specifically about this case, since it can be rather
5715 // confusing for users.
5716 QualType T = Arg.getAsType();
5717 SourceRange SR = ArgLoc.getSourceRange();
5718 if (T->isFunctionType())
5719 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5720 else
5721 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5723 return true;
5724 }
5725
5727 llvm_unreachable("Caller must expand template argument packs");
5728 }
5729
5730 return false;
5731 }
5732
5733
5734 // Check template template parameters.
5736
5737 TemplateParameterList *Params = TempParm->getTemplateParameters();
5738 if (TempParm->isExpandedParameterPack())
5739 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5740
5741 // Substitute into the template parameter list of the template
5742 // template parameter, since previously-supplied template arguments
5743 // may appear within the template template parameter.
5744 //
5745 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5746 {
5747 // Set up a template instantiation context.
5749 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5750 CTAI.SugaredConverted,
5751 SourceRange(TemplateLoc, RAngleLoc));
5752 if (Inst.isInvalid())
5753 return true;
5754
5755 Params = SubstTemplateParams(
5756 Params, CurContext,
5758 /*Final=*/true),
5759 /*EvaluateConstraints=*/false);
5760 if (!Params)
5761 return true;
5762 }
5763
5764 // C++1z [temp.local]p1: (DR1004)
5765 // When [the injected-class-name] is used [...] as a template-argument for
5766 // a template template-parameter [...] it refers to the class template
5767 // itself.
5768 if (Arg.getKind() == TemplateArgument::Type) {
5770 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5771 if (!ConvertedArg.getArgument().isNull())
5772 ArgLoc = ConvertedArg;
5773 }
5774
5775 switch (Arg.getKind()) {
5777 llvm_unreachable("Should never see a NULL template argument here");
5778
5781 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5782 CTAI.PartialOrdering,
5783 &CTAI.StrictPackMatch))
5784 return true;
5785
5786 CTAI.SugaredConverted.push_back(Arg);
5787 CTAI.CanonicalConverted.push_back(
5788 Context.getCanonicalTemplateArgument(Arg));
5789 break;
5790
5793 auto Kind = 0;
5794 switch (TempParm->templateParameterKind()) {
5796 Kind = 1;
5797 break;
5799 Kind = 2;
5800 break;
5801 default:
5802 break;
5803 }
5804
5805 // We have a template template parameter but the template
5806 // argument does not refer to a template.
5807 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5808 << Kind << getLangOpts().CPlusPlus11;
5809 return true;
5810 }
5811
5816 llvm_unreachable("non-type argument with template template parameter");
5817
5819 llvm_unreachable("Caller must expand template argument packs");
5820 }
5821
5822 return false;
5823}
5824
5825/// Diagnose a missing template argument.
5826template<typename TemplateParmDecl>
5828 TemplateDecl *TD,
5829 const TemplateParmDecl *D,
5831 // Dig out the most recent declaration of the template parameter; there may be
5832 // declarations of the template that are more recent than TD.
5834 ->getTemplateParameters()
5835 ->getParam(D->getIndex()));
5836
5837 // If there's a default argument that's not reachable, diagnose that we're
5838 // missing a module import.
5840 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5842 D->getDefaultArgumentLoc(), Modules,
5844 /*Recover*/true);
5845 return true;
5846 }
5847
5848 // FIXME: If there's a more recent default argument that *is* visible,
5849 // diagnose that it was declared too late.
5850
5852
5853 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5854 << /*not enough args*/0
5856 << TD;
5857 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5858 return true;
5859}
5860
5861/// Check that the given template argument list is well-formed
5862/// for specializing the given template.
5864 TemplateDecl *Template, SourceLocation TemplateLoc,
5865 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5866 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5867 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5869 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5870 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5872}
5873
5874/// Check that the given template argument list is well-formed
5875/// for specializing the given template.
5878 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5879 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5880 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5882
5884 *ConstraintsNotSatisfied = false;
5885
5886 // Make a copy of the template arguments for processing. Only make the
5887 // changes at the end when successful in matching the arguments to the
5888 // template.
5889 TemplateArgumentListInfo NewArgs = TemplateArgs;
5890
5891 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5892
5893 // C++23 [temp.arg.general]p1:
5894 // [...] The type and form of each template-argument specified in
5895 // a template-id shall match the type and form specified for the
5896 // corresponding parameter declared by the template in its
5897 // template-parameter-list.
5898 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5899 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5900 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5901 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5902 LocalInstantiationScope InstScope(*this, true);
5903 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5904 ParamEnd = Params->end(),
5905 Param = ParamBegin;
5906 Param != ParamEnd;
5907 /* increment in loop */) {
5908 if (size_t ParamIdx = Param - ParamBegin;
5909 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5910 // All written arguments should have been consumed by this point.
5911 assert(ArgIdx == NumArgs && "bad default argument deduction");
5912 if (ParamIdx == DefaultArgs.StartPos) {
5913 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5914 // Default arguments from a DeducedTemplateName are already converted.
5915 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5916 CTAI.SugaredConverted.push_back(DefArg);
5917 CTAI.CanonicalConverted.push_back(
5918 Context.getCanonicalTemplateArgument(DefArg));
5919 ++Param;
5920 }
5921 continue;
5922 }
5923 }
5924
5925 // If we have an expanded parameter pack, make sure we don't have too
5926 // many arguments.
5927 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5928 if (*Expansions == SugaredArgumentPack.size()) {
5929 // We're done with this parameter pack. Pack up its arguments and add
5930 // them to the list.
5931 CTAI.SugaredConverted.push_back(
5932 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5933 SugaredArgumentPack.clear();
5934
5935 CTAI.CanonicalConverted.push_back(
5936 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5937 CanonicalArgumentPack.clear();
5938
5939 // This argument is assigned to the next parameter.
5940 ++Param;
5941 continue;
5942 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5943 // Not enough arguments for this parameter pack.
5944 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5945 << /*not enough args*/0
5947 << Template;
5949 return true;
5950 }
5951 }
5952
5953 // Check for builtins producing template packs in this context, we do not
5954 // support them yet.
5955 if (const NonTypeTemplateParmDecl *NTTP =
5956 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5957 NTTP && NTTP->isPackExpansion()) {
5958 auto TL = NTTP->getTypeSourceInfo()
5959 ->getTypeLoc()
5962 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5963 for (const auto &UPP : Unexpanded) {
5964 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5965 if (!TST)
5966 continue;
5967 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5968 // Expanding a built-in pack in this context is not yet supported.
5969 Diag(TL.getEllipsisLoc(),
5970 diag::err_unsupported_builtin_template_pack_expansion)
5971 << TST->getTemplateName();
5972 return true;
5973 }
5974 }
5975
5976 if (ArgIdx < NumArgs) {
5977 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5978 bool NonPackParameter =
5979 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5980 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5981
5982 if (ArgIsExpansion && CTAI.MatchingTTP) {
5983 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5984 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5985 ++Param) {
5986 TemplateArgument &Arg = Args[Param - First];
5987 Arg = ArgLoc.getArgument();
5988 if (!(*Param)->isTemplateParameterPack() ||
5989 getExpandedPackSize(*Param))
5990 Arg = Arg.getPackExpansionPattern();
5991 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5992 SaveAndRestore _1(CTAI.PartialOrdering, false);
5993 SaveAndRestore _2(CTAI.MatchingTTP, true);
5994 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5995 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5997 return true;
5998 Arg = NewArgLoc.getArgument();
5999 CTAI.CanonicalConverted.back().setIsDefaulted(
6000 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6001 CTAI.CanonicalConverted,
6002 Params->getDepth()));
6003 }
6004 ArgLoc = TemplateArgumentLoc(
6007 } else {
6008 SaveAndRestore _1(CTAI.PartialOrdering, false);
6009 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6010 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6012 return true;
6013 CTAI.CanonicalConverted.back().setIsDefaulted(
6014 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6015 *Param, CTAI.CanonicalConverted,
6016 Params->getDepth()));
6017 if (ArgIsExpansion && NonPackParameter) {
6018 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6019 // alias template, builtin template, or concept, and it's not part of
6020 // a parameter pack. This can't be canonicalized, so reject it now.
6022 Template)) {
6023 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6025 : 0;
6026 Diag(ArgLoc.getLocation(),
6027 diag::err_template_expansion_into_fixed_list)
6028 << DiagSelect << ArgLoc.getSourceRange();
6030 return true;
6031 }
6032 }
6033 }
6034
6035 // We're now done with this argument.
6036 ++ArgIdx;
6037
6038 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6039 // Directly convert the remaining arguments, because we don't know what
6040 // parameters they'll match up with.
6041
6042 if (!SugaredArgumentPack.empty()) {
6043 // If we were part way through filling in an expanded parameter pack,
6044 // fall back to just producing individual arguments.
6045 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6046 SugaredArgumentPack.begin(),
6047 SugaredArgumentPack.end());
6048 SugaredArgumentPack.clear();
6049
6050 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6051 CanonicalArgumentPack.begin(),
6052 CanonicalArgumentPack.end());
6053 CanonicalArgumentPack.clear();
6054 }
6055
6056 while (ArgIdx < NumArgs) {
6057 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6058 CTAI.SugaredConverted.push_back(Arg);
6059 CTAI.CanonicalConverted.push_back(
6060 Context.getCanonicalTemplateArgument(Arg));
6061 ++ArgIdx;
6062 }
6063
6064 return false;
6065 }
6066
6067 if ((*Param)->isTemplateParameterPack()) {
6068 // The template parameter was a template parameter pack, so take the
6069 // deduced argument and place it on the argument pack. Note that we
6070 // stay on the same template parameter so that we can deduce more
6071 // arguments.
6072 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6073 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6074 } else {
6075 // Move to the next template parameter.
6076 ++Param;
6077 }
6078 continue;
6079 }
6080
6081 // If we're checking a partial template argument list, we're done.
6082 if (PartialTemplateArgs) {
6083 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6084 CTAI.SugaredConverted.push_back(
6085 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6086 CTAI.CanonicalConverted.push_back(
6087 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6088 }
6089 return false;
6090 }
6091
6092 // If we have a template parameter pack with no more corresponding
6093 // arguments, just break out now and we'll fill in the argument pack below.
6094 if ((*Param)->isTemplateParameterPack()) {
6095 assert(!getExpandedPackSize(*Param) &&
6096 "Should have dealt with this already");
6097
6098 // A non-expanded parameter pack before the end of the parameter list
6099 // only occurs for an ill-formed template parameter list, unless we've
6100 // got a partial argument list for a function template, so just bail out.
6101 if (Param + 1 != ParamEnd) {
6102 assert(
6103 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6104 "Concept templates must have parameter packs at the end.");
6105 return true;
6106 }
6107
6108 CTAI.SugaredConverted.push_back(
6109 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6110 SugaredArgumentPack.clear();
6111
6112 CTAI.CanonicalConverted.push_back(
6113 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6114 CanonicalArgumentPack.clear();
6115
6116 ++Param;
6117 continue;
6118 }
6119
6120 // Check whether we have a default argument.
6121 bool HasDefaultArg;
6122
6123 // Retrieve the default template argument from the template
6124 // parameter. For each kind of template parameter, we substitute the
6125 // template arguments provided thus far and any "outer" template arguments
6126 // (when the template parameter was part of a nested template) into
6127 // the default argument.
6129 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6130 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6131
6132 if (Arg.getArgument().isNull()) {
6133 if (!HasDefaultArg) {
6134 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6135 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6136 NewArgs);
6137 if (NonTypeTemplateParmDecl *NTTP =
6138 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6139 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6140 NewArgs);
6141 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6143 NewArgs);
6144 }
6145 return true;
6146 }
6147
6148 // Introduce an instantiation record that describes where we are using
6149 // the default template argument. We're not actually instantiating a
6150 // template here, we just create this object to put a note into the
6151 // context stack.
6152 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6153 CTAI.SugaredConverted,
6154 SourceRange(TemplateLoc, RAngleLoc));
6155 if (Inst.isInvalid())
6156 return true;
6157
6158 SaveAndRestore _1(CTAI.PartialOrdering, false);
6159 SaveAndRestore _2(CTAI.MatchingTTP, false);
6160 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6161 // Check the default template argument.
6162 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6163 CTAI, CTAK_Specified))
6164 return true;
6165
6166 CTAI.SugaredConverted.back().setIsDefaulted(true);
6167 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6168
6169 // Core issue 150 (assumed resolution): if this is a template template
6170 // parameter, keep track of the default template arguments from the
6171 // template definition.
6172 if (isTemplateTemplateParameter)
6173 NewArgs.addArgument(Arg);
6174
6175 // Move to the next template parameter and argument.
6176 ++Param;
6177 ++ArgIdx;
6178 }
6179
6180 // If we're performing a partial argument substitution, allow any trailing
6181 // pack expansions; they might be empty. This can happen even if
6182 // PartialTemplateArgs is false (the list of arguments is complete but
6183 // still dependent).
6184 if (CTAI.MatchingTTP ||
6186 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6187 while (ArgIdx < NumArgs &&
6188 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6189 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6190 CTAI.SugaredConverted.push_back(Arg);
6191 CTAI.CanonicalConverted.push_back(
6192 Context.getCanonicalTemplateArgument(Arg));
6193 }
6194 }
6195
6196 // If we have any leftover arguments, then there were too many arguments.
6197 // Complain and fail.
6198 if (ArgIdx < NumArgs) {
6199 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6200 << /*too many args*/1
6202 << Template
6203 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6205 return true;
6206 }
6207
6208 // No problems found with the new argument list, propagate changes back
6209 // to caller.
6210 if (UpdateArgsWithConversions)
6211 TemplateArgs = std::move(NewArgs);
6212
6213 if (!PartialTemplateArgs) {
6214 // Setup the context/ThisScope for the case where we are needing to
6215 // re-instantiate constraints outside of normal instantiation.
6216 DeclContext *NewContext = Template->getDeclContext();
6217
6218 // If this template is in a template, make sure we extract the templated
6219 // decl.
6220 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6221 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6222 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6223
6224 Qualifiers ThisQuals;
6225 if (const auto *Method =
6226 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6227 ThisQuals = Method->getMethodQualifiers();
6228
6229 ContextRAII Context(*this, NewContext);
6230 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6231
6233 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6234 /*RelativeToPrimary=*/true,
6235 /*Pattern=*/nullptr,
6236 /*ForConceptInstantiation=*/true);
6237 if (!isa<ConceptDecl>(Template) &&
6239 Template, MLTAL,
6240 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6243 return true;
6244 }
6245 }
6246
6247 return false;
6248}
6249
6250namespace {
6251 class UnnamedLocalNoLinkageFinder
6252 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6253 {
6254 Sema &S;
6255 SourceRange SR;
6256
6258
6259 public:
6260 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6261
6262 bool Visit(QualType T) {
6263 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6264 }
6265
6266#define TYPE(Class, Parent) \
6267 bool Visit##Class##Type(const Class##Type *);
6268#define ABSTRACT_TYPE(Class, Parent) \
6269 bool Visit##Class##Type(const Class##Type *) { return false; }
6270#define NON_CANONICAL_TYPE(Class, Parent) \
6271 bool Visit##Class##Type(const Class##Type *) { return false; }
6272#include "clang/AST/TypeNodes.inc"
6273
6274 bool VisitTagDecl(const TagDecl *Tag);
6275 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6276 };
6277} // end anonymous namespace
6278
6279bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6280 return false;
6281}
6282
6283bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6284 return Visit(T->getElementType());
6285}
6286
6287bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6288 return Visit(T->getPointeeType());
6289}
6290
6291bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6292 const BlockPointerType* T) {
6293 return Visit(T->getPointeeType());
6294}
6295
6296bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6297 const LValueReferenceType* T) {
6298 return Visit(T->getPointeeType());
6299}
6300
6301bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6302 const RValueReferenceType* T) {
6303 return Visit(T->getPointeeType());
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6307 const MemberPointerType *T) {
6308 if (Visit(T->getPointeeType()))
6309 return true;
6310 if (auto *RD = T->getMostRecentCXXRecordDecl())
6311 return VisitTagDecl(RD);
6312 return VisitNestedNameSpecifier(T->getQualifier());
6313}
6314
6315bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6316 const ConstantArrayType* T) {
6317 return Visit(T->getElementType());
6318}
6319
6320bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6321 const IncompleteArrayType* T) {
6322 return Visit(T->getElementType());
6323}
6324
6325bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6326 const VariableArrayType* T) {
6327 return Visit(T->getElementType());
6328}
6329
6330bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6331 const DependentSizedArrayType* T) {
6332 return Visit(T->getElementType());
6333}
6334
6335bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6336 const DependentSizedExtVectorType* T) {
6337 return Visit(T->getElementType());
6338}
6339
6340bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6341 const DependentSizedMatrixType *T) {
6342 return Visit(T->getElementType());
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6346 const DependentAddressSpaceType *T) {
6347 return Visit(T->getPointeeType());
6348}
6349
6350bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6351 return Visit(T->getElementType());
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6355 const DependentVectorType *T) {
6356 return Visit(T->getElementType());
6357}
6358
6359bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6360 return Visit(T->getElementType());
6361}
6362
6363bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6364 const ConstantMatrixType *T) {
6365 return Visit(T->getElementType());
6366}
6367
6368bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6369 const FunctionProtoType* T) {
6370 for (const auto &A : T->param_types()) {
6371 if (Visit(A))
6372 return true;
6373 }
6374
6375 return Visit(T->getReturnType());
6376}
6377
6378bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6379 const FunctionNoProtoType* T) {
6380 return Visit(T->getReturnType());
6381}
6382
6383bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6384 const UnresolvedUsingType*) {
6385 return false;
6386}
6387
6388bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6389 return false;
6390}
6391
6392bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6393 return Visit(T->getUnmodifiedType());
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6397 return false;
6398}
6399
6400bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6401 const PackIndexingType *) {
6402 return false;
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6406 const UnaryTransformType*) {
6407 return false;
6408}
6409
6410bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6411 return Visit(T->getDeducedType());
6412}
6413
6414bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6415 const DeducedTemplateSpecializationType *T) {
6416 return Visit(T->getDeducedType());
6417}
6418
6419bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6420 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6421}
6422
6423bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6424 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6425}
6426
6427bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6428 const TemplateTypeParmType*) {
6429 return false;
6430}
6431
6432bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6433 const SubstTemplateTypeParmPackType *) {
6434 return false;
6435}
6436
6437bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6438 const SubstBuiltinTemplatePackType *) {
6439 return false;
6440}
6441
6442bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6443 const TemplateSpecializationType*) {
6444 return false;
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6448 const InjectedClassNameType* T) {
6449 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6450}
6451
6452bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6453 const DependentNameType* T) {
6454 return VisitNestedNameSpecifier(T->getQualifier());
6455}
6456
6457bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6458 const PackExpansionType* T) {
6459 return Visit(T->getPattern());
6460}
6461
6462bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6463 return false;
6464}
6465
6466bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6467 const ObjCInterfaceType *) {
6468 return false;
6469}
6470
6471bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6472 const ObjCObjectPointerType *) {
6473 return false;
6474}
6475
6476bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6477 return Visit(T->getValueType());
6478}
6479
6480bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6481 const OverflowBehaviorType *T) {
6482 return Visit(T->getUnderlyingType());
6483}
6484
6485bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6486 return false;
6487}
6488
6489bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6490 return false;
6491}
6492
6493bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6494 const ArrayParameterType *T) {
6495 return VisitConstantArrayType(T);
6496}
6497
6498bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6499 const DependentBitIntType *T) {
6500 return false;
6501}
6502
6503bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6504 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6505 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6506 ? diag::warn_cxx98_compat_template_arg_local_type
6507 : diag::ext_template_arg_local_type)
6508 << S.Context.getCanonicalTagType(Tag) << SR;
6509 return true;
6510 }
6511
6512 if (!Tag->hasNameForLinkage()) {
6513 S.Diag(SR.getBegin(),
6514 S.getLangOpts().CPlusPlus11 ?
6515 diag::warn_cxx98_compat_template_arg_unnamed_type :
6516 diag::ext_template_arg_unnamed_type) << SR;
6517 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6518 return true;
6519 }
6520
6521 return false;
6522}
6523
6524bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6525 NestedNameSpecifier NNS) {
6526 switch (NNS.getKind()) {
6531 return false;
6533 return Visit(QualType(NNS.getAsType(), 0));
6534 }
6535 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6536}
6537
6538bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6539 const HLSLAttributedResourceType *T) {
6540 if (T->hasContainedType() && Visit(T->getContainedType()))
6541 return true;
6542 return Visit(T->getWrappedType());
6543}
6544
6545bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6546 const HLSLInlineSpirvType *T) {
6547 for (auto &Operand : T->getOperands())
6548 if (Operand.isConstant() && Operand.isLiteral())
6549 if (Visit(Operand.getResultType()))
6550 return true;
6551 return false;
6552}
6553
6555 assert(ArgInfo && "invalid TypeSourceInfo");
6556 QualType Arg = ArgInfo->getType();
6557 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6558 QualType CanonArg = Context.getCanonicalType(Arg);
6559
6560 if (CanonArg->isVariablyModifiedType()) {
6561 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6562 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6563 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6564 }
6565
6566 // C++03 [temp.arg.type]p2:
6567 // A local type, a type with no linkage, an unnamed type or a type
6568 // compounded from any of these types shall not be used as a
6569 // template-argument for a template type-parameter.
6570 //
6571 // C++11 allows these, and even in C++03 we allow them as an extension with
6572 // a warning.
6573 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6574 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6575 (void)Finder.Visit(CanonArg);
6576 }
6577
6578 return false;
6579}
6580
6586
6587/// Determine whether the given template argument is a null pointer
6588/// value of the appropriate type.
6591 QualType ParamType, Expr *Arg,
6592 Decl *Entity = nullptr) {
6593 if (Arg->isValueDependent() || Arg->isTypeDependent())
6594 return NPV_NotNullPointer;
6595
6596 // dllimport'd entities aren't constant but are available inside of template
6597 // arguments.
6598 if (Entity && Entity->hasAttr<DLLImportAttr>())
6599 return NPV_NotNullPointer;
6600
6601 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6602 llvm_unreachable(
6603 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6604
6605 if (!S.getLangOpts().CPlusPlus11)
6606 return NPV_NotNullPointer;
6607
6608 // Determine whether we have a constant expression.
6610 if (ArgRV.isInvalid())
6611 return NPV_Error;
6612 Arg = ArgRV.get();
6613
6614 Expr::EvalResult EvalResult;
6616 EvalResult.Diag = &Notes;
6617 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6618 EvalResult.HasSideEffects) {
6619 SourceLocation DiagLoc = Arg->getExprLoc();
6620
6621 // If our only note is the usual "invalid subexpression" note, just point
6622 // the caret at its location rather than producing an essentially
6623 // redundant note.
6624 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6625 diag::note_invalid_subexpr_in_const_expr) {
6626 DiagLoc = Notes[0].first;
6627 Notes.clear();
6628 }
6629
6630 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6631 << Arg->getType() << Arg->getSourceRange();
6632 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6633 S.Diag(Notes[I].first, Notes[I].second);
6634
6636 return NPV_Error;
6637 }
6638
6639 // C++11 [temp.arg.nontype]p1:
6640 // - an address constant expression of type std::nullptr_t
6641 if (Arg->getType()->isNullPtrType())
6642 return NPV_NullPointer;
6643
6644 // - a constant expression that evaluates to a null pointer value (4.10); or
6645 // - a constant expression that evaluates to a null member pointer value
6646 // (4.11); or
6647 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6648 (EvalResult.Val.isMemberPointer() &&
6649 !EvalResult.Val.getMemberPointerDecl())) {
6650 // If our expression has an appropriate type, we've succeeded.
6651 bool ObjCLifetimeConversion;
6652 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6653 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6654 ObjCLifetimeConversion))
6655 return NPV_NullPointer;
6656
6657 // The types didn't match, but we know we got a null pointer; complain,
6658 // then recover as if the types were correct.
6659 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6660 << Arg->getType() << ParamType << Arg->getSourceRange();
6662 return NPV_NullPointer;
6663 }
6664
6665 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6666 // We found a pointer that isn't null, but doesn't refer to an object.
6667 // We could just return NPV_NotNullPointer, but we can print a better
6668 // message with the information we have here.
6669 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6670 << EvalResult.Val.getAsString(S.Context, ParamType);
6672 return NPV_Error;
6673 }
6674
6675 // If we don't have a null pointer value, but we do have a NULL pointer
6676 // constant, suggest a cast to the appropriate type.
6678 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6679 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6680 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6682 ")");
6684 return NPV_NullPointer;
6685 }
6686
6687 // FIXME: If we ever want to support general, address-constant expressions
6688 // as non-type template arguments, we should return the ExprResult here to
6689 // be interpreted by the caller.
6690 return NPV_NotNullPointer;
6691}
6692
6693/// Checks whether the given template argument is compatible with its
6694/// template parameter.
6695static bool
6697 QualType ParamType, Expr *ArgIn,
6698 Expr *Arg, QualType ArgType) {
6699 bool ObjCLifetimeConversion;
6700 if (ParamType->isPointerType() &&
6701 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6702 S.IsQualificationConversion(ArgType, ParamType, false,
6703 ObjCLifetimeConversion)) {
6704 // For pointer-to-object types, qualification conversions are
6705 // permitted.
6706 } else {
6707 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6708 if (!ParamRef->getPointeeType()->isFunctionType()) {
6709 // C++ [temp.arg.nontype]p5b3:
6710 // For a non-type template-parameter of type reference to
6711 // object, no conversions apply. The type referred to by the
6712 // reference may be more cv-qualified than the (otherwise
6713 // identical) type of the template- argument. The
6714 // template-parameter is bound directly to the
6715 // template-argument, which shall be an lvalue.
6716
6717 // FIXME: Other qualifiers?
6718 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6719 unsigned ArgQuals = ArgType.getCVRQualifiers();
6720
6721 if ((ParamQuals | ArgQuals) != ParamQuals) {
6722 S.Diag(Arg->getBeginLoc(),
6723 diag::err_template_arg_ref_bind_ignores_quals)
6724 << ParamType << Arg->getType() << Arg->getSourceRange();
6726 return true;
6727 }
6728 }
6729 }
6730
6731 // At this point, the template argument refers to an object or
6732 // function with external linkage. We now need to check whether the
6733 // argument and parameter types are compatible.
6734 if (!S.Context.hasSameUnqualifiedType(ArgType,
6735 ParamType.getNonReferenceType())) {
6736 // We can't perform this conversion or binding.
6737 if (ParamType->isReferenceType())
6738 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6739 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6740 else
6741 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6742 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6744 return true;
6745 }
6746 }
6747
6748 return false;
6749}
6750
6751/// Checks whether the given template argument is the address
6752/// of an object or function according to C++ [temp.arg.nontype]p1.
6754 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6755 bool IsSpecified, TemplateArgument &SugaredConverted,
6756 TemplateArgument &CanonicalConverted) {
6757 Expr *Arg = ArgIn;
6758 QualType ArgType = Arg->getType();
6759
6760 bool AddressTaken = false;
6761 SourceLocation AddrOpLoc;
6762 if (S.getLangOpts().MicrosoftExt) {
6763 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6764 // dereference and address-of operators.
6765 Arg = Arg->IgnoreParenCasts();
6766
6767 bool ExtWarnMSTemplateArg = false;
6768 UnaryOperatorKind FirstOpKind;
6769 SourceLocation FirstOpLoc;
6770 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6771 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6772 if (UnOpKind == UO_Deref)
6773 ExtWarnMSTemplateArg = true;
6774 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6775 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6776 if (!AddrOpLoc.isValid()) {
6777 FirstOpKind = UnOpKind;
6778 FirstOpLoc = UnOp->getOperatorLoc();
6779 }
6780 } else
6781 break;
6782 }
6783 if (FirstOpLoc.isValid()) {
6784 if (ExtWarnMSTemplateArg)
6785 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6786 << ArgIn->getSourceRange();
6787
6788 if (FirstOpKind == UO_AddrOf)
6789 AddressTaken = true;
6790 else if (Arg->getType()->isPointerType()) {
6791 // We cannot let pointers get dereferenced here, that is obviously not a
6792 // constant expression.
6793 assert(FirstOpKind == UO_Deref);
6794 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6795 << Arg->getSourceRange();
6796 }
6797 }
6798 } else {
6799 // See through any implicit casts we added to fix the type.
6800 // Also ignore parentheses for deduced template arguments.
6801 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6802
6803 // C++ [temp.arg.nontype]p1:
6804 //
6805 // A template-argument for a non-type, non-template
6806 // template-parameter shall be one of: [...]
6807 //
6808 // -- the address of an object or function with external
6809 // linkage, including function templates and function
6810 // template-ids but excluding non-static class members,
6811 // expressed as & id-expression where the & is optional if
6812 // the name refers to a function or array, or if the
6813 // corresponding template-parameter is a reference; or
6814
6815 // In C++98/03 mode, give an extension warning on any extra parentheses.
6816 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6817 if (IsSpecified) {
6818 bool ExtraParens = false;
6819 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6820 if (!ExtraParens) {
6821 S.DiagCompat(Arg->getBeginLoc(),
6822 diag_compat::template_arg_extra_parens)
6823 << Arg->getSourceRange();
6824 ExtraParens = true;
6825 }
6826
6827 Arg = Parens->getSubExpr();
6828 }
6829 }
6830
6831 while (SubstNonTypeTemplateParmExpr *subst =
6832 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6833 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6834
6835 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6836 if (UnOp->getOpcode() == UO_AddrOf) {
6837 Arg = UnOp->getSubExpr();
6838 AddressTaken = true;
6839 AddrOpLoc = UnOp->getOperatorLoc();
6840 }
6841 }
6842
6843 while (SubstNonTypeTemplateParmExpr *subst =
6844 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6845 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6846 }
6847
6848 ValueDecl *Entity = nullptr;
6849 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6850 Entity = DRE->getDecl();
6851 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6852 Entity = CUE->getGuidDecl();
6853
6854 // If our parameter has pointer type, check for a null template value.
6855 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6856 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6857 Entity)) {
6858 case NPV_NullPointer:
6859 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6860 SugaredConverted = TemplateArgument(ParamType,
6861 /*isNullPtr=*/true);
6862 CanonicalConverted =
6864 /*isNullPtr=*/true);
6865 return false;
6866
6867 case NPV_Error:
6868 return true;
6869
6870 case NPV_NotNullPointer:
6871 break;
6872 }
6873 }
6874
6875 // Stop checking the precise nature of the argument if it is value dependent,
6876 // it should be checked when instantiated.
6877 if (Arg->isValueDependent()) {
6878 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6879 CanonicalConverted =
6880 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6881 return false;
6882 }
6883
6884 if (!Entity) {
6885 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6886 << Arg->getSourceRange();
6888 return true;
6889 }
6890
6891 // Cannot refer to non-static data members
6892 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6893 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6894 << Entity << Arg->getSourceRange();
6896 return true;
6897 }
6898
6899 // Cannot refer to non-static member functions
6900 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6901 if (!Method->isStatic()) {
6902 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6903 << Method << Arg->getSourceRange();
6905 return true;
6906 }
6907 }
6908
6909 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6910 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6911 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6912
6913 // A non-type template argument must refer to an object or function.
6914 if (!Func && !Var && !Guid) {
6915 // We found something, but we don't know specifically what it is.
6916 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6917 << Arg->getSourceRange();
6918 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6919 return true;
6920 }
6921
6922 // Address / reference template args must have external linkage in C++98.
6923 if (Entity->getFormalLinkage() == Linkage::Internal) {
6924 S.Diag(Arg->getBeginLoc(),
6925 S.getLangOpts().CPlusPlus11
6926 ? diag::warn_cxx98_compat_template_arg_object_internal
6927 : diag::ext_template_arg_object_internal)
6928 << !Func << Entity << Arg->getSourceRange();
6929 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6930 << !Func;
6931 } else if (!Entity->hasLinkage()) {
6932 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6933 << !Func << Entity << Arg->getSourceRange();
6934 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6935 << !Func;
6936 return true;
6937 }
6938
6939 if (Var) {
6940 // A value of reference type is not an object.
6941 if (Var->getType()->isReferenceType()) {
6942 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6943 << Var->getType() << Arg->getSourceRange();
6945 return true;
6946 }
6947
6948 // A template argument must have static storage duration.
6949 if (Var->getTLSKind()) {
6950 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6951 << Arg->getSourceRange();
6952 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6953 return true;
6954 }
6955 }
6956
6957 if (AddressTaken && ParamType->isReferenceType()) {
6958 // If we originally had an address-of operator, but the
6959 // parameter has reference type, complain and (if things look
6960 // like they will work) drop the address-of operator.
6961 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6962 ParamType.getNonReferenceType())) {
6963 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6964 << ParamType;
6966 return true;
6967 }
6968
6969 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6970 << ParamType
6971 << FixItHint::CreateRemoval(AddrOpLoc);
6973
6974 ArgType = Entity->getType();
6975 }
6976
6977 // If the template parameter has pointer type, either we must have taken the
6978 // address or the argument must decay to a pointer.
6979 if (!AddressTaken && ParamType->isPointerType()) {
6980 if (Func) {
6981 // Function-to-pointer decay.
6982 ArgType = S.Context.getPointerType(Func->getType());
6983 } else if (Entity->getType()->isArrayType()) {
6984 // Array-to-pointer decay.
6985 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6986 } else {
6987 // If the template parameter has pointer type but the address of
6988 // this object was not taken, complain and (possibly) recover by
6989 // taking the address of the entity.
6990 ArgType = S.Context.getPointerType(Entity->getType());
6991 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6992 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6993 << ParamType;
6995 return true;
6996 }
6997
6998 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6999 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7000
7002 }
7003 }
7004
7005 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7006 Arg, ArgType))
7007 return true;
7008
7009 // Create the template argument.
7010 SugaredConverted = TemplateArgument(Entity, ParamType);
7011 CanonicalConverted =
7013 S.Context.getCanonicalType(ParamType));
7014 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7015 return false;
7016}
7017
7018/// Checks whether the given template argument is a pointer to
7019/// member constant according to C++ [temp.arg.nontype]p1.
7021 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7022 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7023 bool Invalid = false;
7024
7025 Expr *Arg = ResultArg;
7026 bool ObjCLifetimeConversion;
7027
7028 // C++ [temp.arg.nontype]p1:
7029 //
7030 // A template-argument for a non-type, non-template
7031 // template-parameter shall be one of: [...]
7032 //
7033 // -- a pointer to member expressed as described in 5.3.1.
7034 DeclRefExpr *DRE = nullptr;
7035
7036 // In C++98/03 mode, give an extension warning on any extra parentheses.
7037 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7038 bool ExtraParens = false;
7039 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7040 if (!Invalid && !ExtraParens) {
7041 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7042 << Arg->getSourceRange();
7043 ExtraParens = true;
7044 }
7045
7046 Arg = Parens->getSubExpr();
7047 }
7048
7049 while (SubstNonTypeTemplateParmExpr *subst =
7050 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7051 Arg = subst->getReplacement()->IgnoreImpCasts();
7052
7053 // A pointer-to-member constant written &Class::member.
7054 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7055 if (UnOp->getOpcode() == UO_AddrOf) {
7056 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7057 if (DRE && !DRE->getQualifier())
7058 DRE = nullptr;
7059 }
7060 }
7061 // A constant of pointer-to-member type.
7062 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7063 ValueDecl *VD = DRE->getDecl();
7064 if (VD->getType()->isMemberPointerType()) {
7066 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7067 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7068 CanonicalConverted =
7069 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7070 } else {
7071 SugaredConverted = TemplateArgument(VD, ParamType);
7072 CanonicalConverted =
7074 S.Context.getCanonicalType(ParamType));
7075 }
7076 return Invalid;
7077 }
7078 }
7079
7080 DRE = nullptr;
7081 }
7082
7083 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7084
7085 // Check for a null pointer value.
7086 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7087 Entity)) {
7088 case NPV_Error:
7089 return true;
7090 case NPV_NullPointer:
7091 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7092 SugaredConverted = TemplateArgument(ParamType,
7093 /*isNullPtr*/ true);
7094 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7095 /*isNullPtr*/ true);
7096 return false;
7097 case NPV_NotNullPointer:
7098 break;
7099 }
7100
7101 if (S.IsQualificationConversion(ResultArg->getType(),
7102 ParamType.getNonReferenceType(), false,
7103 ObjCLifetimeConversion)) {
7104 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7105 ResultArg->getValueKind())
7106 .get();
7107 } else if (!S.Context.hasSameUnqualifiedType(
7108 ResultArg->getType(), ParamType.getNonReferenceType())) {
7109 // We can't perform this conversion.
7110 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7111 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7113 return true;
7114 }
7115
7116 if (!DRE)
7117 return S.Diag(Arg->getBeginLoc(),
7118 diag::err_template_arg_not_pointer_to_member_form)
7119 << Arg->getSourceRange();
7120
7121 if (isa<FieldDecl>(DRE->getDecl()) ||
7123 isa<CXXMethodDecl>(DRE->getDecl())) {
7124 assert((isa<FieldDecl>(DRE->getDecl()) ||
7127 ->isImplicitObjectMemberFunction()) &&
7128 "Only non-static member pointers can make it here");
7129
7130 // Okay: this is the address of a non-static member, and therefore
7131 // a member pointer constant.
7132 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7133 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7134 CanonicalConverted =
7135 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7136 } else {
7137 ValueDecl *D = DRE->getDecl();
7138 SugaredConverted = TemplateArgument(D, ParamType);
7139 CanonicalConverted =
7141 S.Context.getCanonicalType(ParamType));
7142 }
7143 return Invalid;
7144 }
7145
7146 // We found something else, but we don't know specifically what it is.
7147 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7148 << Arg->getSourceRange();
7149 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7150 return true;
7151}
7152
7153/// Check a template argument against its corresponding
7154/// non-type template parameter.
7155///
7156/// This routine implements the semantics of C++ [temp.arg.nontype].
7157/// If an error occurred, it returns ExprError(); otherwise, it
7158/// returns the converted template argument. \p ParamType is the
7159/// type of the non-type template parameter after it has been instantiated.
7161 Expr *Arg,
7162 TemplateArgument &SugaredConverted,
7163 TemplateArgument &CanonicalConverted,
7164 bool StrictCheck,
7166 SourceLocation StartLoc = Arg->getBeginLoc();
7167 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7168 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7169 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7170 DeductionArg = NewDeductionArg;
7171 if (ArgPE) {
7172 // Recreate a pack expansion if we unwrapped one.
7173 Arg = new (Context) PackExpansionExpr(
7174 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7175 } else {
7176 Arg = DeductionArg;
7177 }
7178 };
7179
7180 // If the parameter type somehow involves auto, deduce the type now.
7181 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7182 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7183 if (IsDeduced) {
7184 // When checking a deduced template argument, deduce from its type even if
7185 // the type is dependent, in order to check the types of non-type template
7186 // arguments line up properly in partial ordering.
7187 TypeSourceInfo *TSI =
7188 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7190 InitializedEntity Entity =
7193 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7194 Expr *Inits[1] = {DeductionArg};
7195 ParamType =
7197 if (ParamType.isNull())
7198 return ExprError();
7199 } else {
7200 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7201 Param->getTemplateDepth() + 1);
7202 ParamType = QualType();
7204 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7205 /*DependentDeduction=*/true,
7206 // We do not check constraints right now because the
7207 // immediately-declared constraint of the auto type is
7208 // also an associated constraint, and will be checked
7209 // along with the other associated constraints after
7210 // checking the template argument list.
7211 /*IgnoreConstraints=*/true);
7213 ParamType = TSI->getType();
7214 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7216 return ExprError();
7217 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7218 Diag(Arg->getExprLoc(),
7219 diag::err_non_type_template_parm_type_deduction_failure)
7220 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7221 << Arg->getSourceRange();
7223 return ExprError();
7224 }
7225 ParamType = SubstAutoTypeDependent(ParamType);
7226 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7227 }
7228 }
7229 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7230 // an error. The error message normally references the parameter
7231 // declaration, but here we'll pass the argument location because that's
7232 // where the parameter type is deduced.
7233 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7234 if (ParamType.isNull()) {
7236 return ExprError();
7237 }
7238 }
7239
7240 // We should have already dropped all cv-qualifiers by now.
7241 assert(!ParamType.hasQualifiers() &&
7242 "non-type template parameter type cannot be qualified");
7243
7244 // If either the parameter has a dependent type or the argument is
7245 // type-dependent, there's nothing we can check now.
7246 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7247 // Force the argument to the type of the parameter to maintain invariants.
7248 if (!IsDeduced) {
7250 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7251 ParamType->isLValueReferenceType() ? VK_LValue
7252 : ParamType->isRValueReferenceType() ? VK_XValue
7253 : VK_PRValue);
7254 if (E.isInvalid())
7255 return ExprError();
7256 setDeductionArg(E.get());
7257 }
7258 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7259 CanonicalConverted = TemplateArgument(
7260 Context.getCanonicalTemplateArgument(SugaredConverted));
7261 return Arg;
7262 }
7263
7264 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7265 if (CTAK == CTAK_Deduced && !StrictCheck &&
7266 (ParamType->isReferenceType()
7267 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7268 DeductionArg->getType())
7269 : !Context.hasSameUnqualifiedType(ParamType,
7270 DeductionArg->getType()))) {
7271 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7272 // we should actually be checking the type of the template argument in P,
7273 // not the type of the template argument deduced from A, against the
7274 // template parameter type.
7275 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7276 << Arg->getType() << ParamType.getUnqualifiedType();
7278 return ExprError();
7279 }
7280
7281 // If the argument is a pack expansion, we don't know how many times it would
7282 // expand. If we continue checking the argument, this will make the template
7283 // definition ill-formed if it would be ill-formed for any number of
7284 // expansions during instantiation time. When partial ordering or matching
7285 // template template parameters, this is exactly what we want. Otherwise, the
7286 // normal template rules apply: we accept the template if it would be valid
7287 // for any number of expansions (i.e. none).
7288 if (ArgPE && !StrictCheck) {
7289 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7290 CanonicalConverted = TemplateArgument(
7291 Context.getCanonicalTemplateArgument(SugaredConverted));
7292 return Arg;
7293 }
7294
7295 // Avoid making a copy when initializing a template parameter of class type
7296 // from a template parameter object of the same type. This is going beyond
7297 // the standard, but is required for soundness: in
7298 // template<A a> struct X { X *p; X<a> *q; };
7299 // ... we need p and q to have the same type.
7300 //
7301 // Similarly, don't inject a call to a copy constructor when initializing
7302 // from a template parameter of the same type.
7303 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7304 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7305 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7306 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7307 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7308
7309 SugaredConverted = TemplateArgument(TPO, ParamType);
7310 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7311 ParamType.getCanonicalType());
7312 return Arg;
7313 }
7315 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7316 CanonicalConverted =
7317 Context.getCanonicalTemplateArgument(SugaredConverted);
7318 return Arg;
7319 }
7320 }
7321
7322 // The initialization of the parameter from the argument is
7323 // a constant-evaluated context.
7326
7327 bool IsConvertedConstantExpression = true;
7328 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7330 StartLoc, /*DirectInit=*/false, DeductionArg);
7331 Expr *Inits[1] = {DeductionArg};
7332 InitializedEntity Entity =
7334 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7335 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7336 if (Result.isInvalid() || !Result.get())
7337 return ExprError();
7339 if (Result.isInvalid() || !Result.get())
7340 return ExprError();
7341 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7342 /*DiscardedValue=*/false,
7343 /*IsConstexpr=*/true,
7344 /*IsTemplateArgument=*/true)
7345 .get());
7346 IsConvertedConstantExpression = false;
7347 }
7348
7349 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7350 // C++17 [temp.arg.nontype]p1:
7351 // A template-argument for a non-type template parameter shall be
7352 // a converted constant expression of the type of the template-parameter.
7353 APValue Value;
7354 ExprResult ArgResult;
7355 if (IsConvertedConstantExpression) {
7357 DeductionArg, ParamType,
7358 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7359 assert(!ArgResult.isUnset());
7360 if (ArgResult.isInvalid()) {
7362 return ExprError();
7363 }
7364 } else {
7365 ArgResult = DeductionArg;
7366 }
7367
7368 // For a value-dependent argument, CheckConvertedConstantExpression is
7369 // permitted (and expected) to be unable to determine a value.
7370 if (ArgResult.get()->isValueDependent()) {
7371 setDeductionArg(ArgResult.get());
7372 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7373 CanonicalConverted =
7374 Context.getCanonicalTemplateArgument(SugaredConverted);
7375 return Arg;
7376 }
7377
7378 APValue PreNarrowingValue;
7380 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7381 false, PreNarrowingValue);
7382 if (ArgResult.isInvalid())
7383 return ExprError();
7384 setDeductionArg(ArgResult.get());
7385
7386 if (Value.isLValue()) {
7387 APValue::LValueBase Base = Value.getLValueBase();
7388 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7389 // For a non-type template-parameter of pointer or reference type,
7390 // the value of the constant expression shall not refer to
7391 assert(ParamType->isPointerOrReferenceType() ||
7392 ParamType->isNullPtrType());
7393 // -- a temporary object
7394 // -- a string literal
7395 // -- the result of a typeid expression, or
7396 // -- a predefined __func__ variable
7397 if (Base &&
7398 (!VD ||
7400 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7401 << Arg->getSourceRange();
7402 return ExprError();
7403 }
7404
7405 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7406 VD->getType()->isArrayType() &&
7407 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7408 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7409 if (ArgPE) {
7410 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7411 CanonicalConverted =
7412 Context.getCanonicalTemplateArgument(SugaredConverted);
7413 } else {
7414 SugaredConverted = TemplateArgument(VD, ParamType);
7415 CanonicalConverted =
7416 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7417 ParamType.getCanonicalType());
7418 }
7419 return Arg;
7420 }
7421
7422 // -- a subobject [until C++20]
7423 if (!getLangOpts().CPlusPlus20) {
7424 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7425 Value.isLValueOnePastTheEnd()) {
7426 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7427 << Value.getAsString(Context, ParamType);
7428 return ExprError();
7429 }
7430 assert((VD || !ParamType->isReferenceType()) &&
7431 "null reference should not be a constant expression");
7432 assert((!VD || !ParamType->isNullPtrType()) &&
7433 "non-null value of type nullptr_t?");
7434 }
7435 }
7436
7437 if (Value.isAddrLabelDiff())
7438 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7439
7440 if (ArgPE) {
7441 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7442 CanonicalConverted =
7443 Context.getCanonicalTemplateArgument(SugaredConverted);
7444 } else {
7445 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7446 CanonicalConverted =
7448 }
7449 return Arg;
7450 }
7451
7452 // These should have all been handled above using the C++17 rules.
7453 assert(!ArgPE && !StrictCheck);
7454
7455 // C++ [temp.arg.nontype]p5:
7456 // The following conversions are performed on each expression used
7457 // as a non-type template-argument. If a non-type
7458 // template-argument cannot be converted to the type of the
7459 // corresponding template-parameter then the program is
7460 // ill-formed.
7461 if (ParamType->isIntegralOrEnumerationType()) {
7462 // C++11:
7463 // -- for a non-type template-parameter of integral or
7464 // enumeration type, conversions permitted in a converted
7465 // constant expression are applied.
7466 //
7467 // C++98:
7468 // -- for a non-type template-parameter of integral or
7469 // enumeration type, integral promotions (4.5) and integral
7470 // conversions (4.7) are applied.
7471
7472 if (getLangOpts().CPlusPlus11) {
7473 // C++ [temp.arg.nontype]p1:
7474 // A template-argument for a non-type, non-template template-parameter
7475 // shall be one of:
7476 //
7477 // -- for a non-type template-parameter of integral or enumeration
7478 // type, a converted constant expression of the type of the
7479 // template-parameter; or
7480 llvm::APSInt Value;
7482 Arg, ParamType, Value, CCEKind::TemplateArg);
7483 if (ArgResult.isInvalid())
7484 return ExprError();
7485 Arg = ArgResult.get();
7486
7487 // We can't check arbitrary value-dependent arguments.
7488 if (Arg->isValueDependent()) {
7489 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7490 CanonicalConverted =
7491 Context.getCanonicalTemplateArgument(SugaredConverted);
7492 return Arg;
7493 }
7494
7495 // Widen the argument value to sizeof(parameter type). This is almost
7496 // always a no-op, except when the parameter type is bool. In
7497 // that case, this may extend the argument from 1 bit to 8 bits.
7498 QualType IntegerType = ParamType;
7499 if (const auto *ED = IntegerType->getAsEnumDecl())
7500 IntegerType = ED->getIntegerType();
7501 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7502 ? Context.getIntWidth(IntegerType)
7503 : Context.getTypeSize(IntegerType));
7504
7505 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7506 CanonicalConverted =
7507 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7508 return Arg;
7509 }
7510
7511 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7512 if (ArgResult.isInvalid())
7513 return ExprError();
7514 Arg = ArgResult.get();
7515
7516 QualType ArgType = Arg->getType();
7517
7518 // C++ [temp.arg.nontype]p1:
7519 // A template-argument for a non-type, non-template
7520 // template-parameter shall be one of:
7521 //
7522 // -- an integral constant-expression of integral or enumeration
7523 // type; or
7524 // -- the name of a non-type template-parameter; or
7525 llvm::APSInt Value;
7526 if (!ArgType->isIntegralOrEnumerationType()) {
7527 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7528 << ArgType << Arg->getSourceRange();
7530 return ExprError();
7531 }
7532 if (!Arg->isValueDependent()) {
7533 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7534 QualType T;
7535
7536 public:
7537 TmplArgICEDiagnoser(QualType T) : T(T) { }
7538
7539 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7540 SourceLocation Loc) override {
7541 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7542 }
7543 } Diagnoser(ArgType);
7544
7545 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7546 if (!Arg)
7547 return ExprError();
7548 }
7549
7550 // From here on out, all we care about is the unqualified form
7551 // of the argument type.
7552 ArgType = ArgType.getUnqualifiedType();
7553
7554 // Try to convert the argument to the parameter's type.
7555 if (Context.hasSameType(ParamType, ArgType)) {
7556 // Okay: no conversion necessary
7557 } else if (ParamType->isBooleanType()) {
7558 // This is an integral-to-boolean conversion.
7559 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7560 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7561 !ParamType->isEnumeralType()) {
7562 // This is an integral promotion or conversion.
7563 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7564 } else {
7565 // We can't perform this conversion.
7566 Diag(StartLoc, diag::err_template_arg_not_convertible)
7567 << Arg->getType() << ParamType << Arg->getSourceRange();
7569 return ExprError();
7570 }
7571
7572 // Add the value of this argument to the list of converted
7573 // arguments. We use the bitwidth and signedness of the template
7574 // parameter.
7575 if (Arg->isValueDependent()) {
7576 // The argument is value-dependent. Create a new
7577 // TemplateArgument with the converted expression.
7578 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7579 CanonicalConverted =
7580 Context.getCanonicalTemplateArgument(SugaredConverted);
7581 return Arg;
7582 }
7583
7584 QualType IntegerType = ParamType;
7585 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7586 IntegerType = ED->getIntegerType();
7587 }
7588
7589 if (ParamType->isBooleanType()) {
7590 // Value must be zero or one.
7591 Value = Value != 0;
7592 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7593 if (Value.getBitWidth() != AllowedBits)
7594 Value = Value.extOrTrunc(AllowedBits);
7595 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7596 } else {
7597 llvm::APSInt OldValue = Value;
7598
7599 // Coerce the template argument's value to the value it will have
7600 // based on the template parameter's type.
7601 unsigned AllowedBits = IntegerType->isBitIntType()
7602 ? Context.getIntWidth(IntegerType)
7603 : Context.getTypeSize(IntegerType);
7604 if (Value.getBitWidth() != AllowedBits)
7605 Value = Value.extOrTrunc(AllowedBits);
7606 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7607
7608 // Complain if an unsigned parameter received a negative value.
7609 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7610 (OldValue.isSigned() && OldValue.isNegative())) {
7611 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7612 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7613 << Arg->getSourceRange();
7615 }
7616
7617 // Complain if we overflowed the template parameter's type.
7618 unsigned RequiredBits;
7619 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7620 RequiredBits = OldValue.getActiveBits();
7621 else if (OldValue.isUnsigned())
7622 RequiredBits = OldValue.getActiveBits() + 1;
7623 else
7624 RequiredBits = OldValue.getSignificantBits();
7625 if (RequiredBits > AllowedBits) {
7626 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7627 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7628 << Arg->getSourceRange();
7630 }
7631 }
7632
7633 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7634 SugaredConverted = TemplateArgument(Context, Value, T);
7635 CanonicalConverted =
7636 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7637 return Arg;
7638 }
7639
7640 QualType ArgType = Arg->getType();
7641 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7642 bool IsSpecified = CTAK == CTAK_Specified;
7643
7644 // Handle pointer-to-function, reference-to-function, and
7645 // pointer-to-member-function all in (roughly) the same way.
7646 if (// -- For a non-type template-parameter of type pointer to
7647 // function, only the function-to-pointer conversion (4.3) is
7648 // applied. If the template-argument represents a set of
7649 // overloaded functions (or a pointer to such), the matching
7650 // function is selected from the set (13.4).
7651 (ParamType->isPointerType() &&
7652 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7653 // -- For a non-type template-parameter of type reference to
7654 // function, no conversions apply. If the template-argument
7655 // represents a set of overloaded functions, the matching
7656 // function is selected from the set (13.4).
7657 (ParamType->isReferenceType() &&
7658 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7659 // -- For a non-type template-parameter of type pointer to
7660 // member function, no conversions apply. If the
7661 // template-argument represents a set of overloaded member
7662 // functions, the matching member function is selected from
7663 // the set (13.4).
7664 (ParamType->isMemberPointerType() &&
7665 ParamType->castAs<MemberPointerType>()->getPointeeType()
7666 ->isFunctionType())) {
7667
7668 if (Arg->getType() == Context.OverloadTy) {
7669 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7670 true,
7671 FoundResult)) {
7672 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7673 return ExprError();
7674
7675 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7676 if (Res.isInvalid())
7677 return ExprError();
7678 Arg = Res.get();
7679 ArgType = Arg->getType();
7680 } else
7681 return ExprError();
7682 }
7683
7684 if (!ParamType->isMemberPointerType()) {
7686 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7687 CanonicalConverted))
7688 return ExprError();
7689 return Arg;
7690 }
7691
7693 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7694 return ExprError();
7695 return Arg;
7696 }
7697
7698 if (ParamType->isPointerType()) {
7699 // -- for a non-type template-parameter of type pointer to
7700 // object, qualification conversions (4.4) and the
7701 // array-to-pointer conversion (4.2) are applied.
7702 // C++0x also allows a value of std::nullptr_t.
7703 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7704 "Only object pointers allowed here");
7705
7707 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7708 CanonicalConverted))
7709 return ExprError();
7710 return Arg;
7711 }
7712
7713 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7714 // -- For a non-type template-parameter of type reference to
7715 // object, no conversions apply. The type referred to by the
7716 // reference may be more cv-qualified than the (otherwise
7717 // identical) type of the template-argument. The
7718 // template-parameter is bound directly to the
7719 // template-argument, which must be an lvalue.
7720 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7721 "Only object references allowed here");
7722
7723 if (Arg->getType() == Context.OverloadTy) {
7725 ParamRefType->getPointeeType(),
7726 true,
7727 FoundResult)) {
7728 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7729 return ExprError();
7730 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7731 if (Res.isInvalid())
7732 return ExprError();
7733 Arg = Res.get();
7734 ArgType = Arg->getType();
7735 } else
7736 return ExprError();
7737 }
7738
7740 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7741 CanonicalConverted))
7742 return ExprError();
7743 return Arg;
7744 }
7745
7746 // Deal with parameters of type std::nullptr_t.
7747 if (ParamType->isNullPtrType()) {
7748 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7749 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7750 CanonicalConverted =
7751 Context.getCanonicalTemplateArgument(SugaredConverted);
7752 return Arg;
7753 }
7754
7755 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7756 case NPV_NotNullPointer:
7757 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7758 << Arg->getType() << ParamType;
7760 return ExprError();
7761
7762 case NPV_Error:
7763 return ExprError();
7764
7765 case NPV_NullPointer:
7766 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7767 SugaredConverted = TemplateArgument(ParamType,
7768 /*isNullPtr=*/true);
7769 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7770 /*isNullPtr=*/true);
7771 return Arg;
7772 }
7773 }
7774
7775 // -- For a non-type template-parameter of type pointer to data
7776 // member, qualification conversions (4.4) are applied.
7777 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7778
7780 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7781 return ExprError();
7782 return Arg;
7783}
7784
7788
7791 const TemplateArgumentLoc &Arg) {
7792 // C++0x [temp.arg.template]p1:
7793 // A template-argument for a template template-parameter shall be
7794 // the name of a class template or an alias template, expressed as an
7795 // id-expression. When the template-argument names a class template, only
7796 // primary class templates are considered when matching the
7797 // template template argument with the corresponding parameter;
7798 // partial specializations are not considered even if their
7799 // parameter lists match that of the template template parameter.
7800 //
7801
7803 unsigned DiagFoundKind = 0;
7804
7805 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7806 switch (TTP->templateParameterKind()) {
7808 DiagFoundKind = 3;
7809 break;
7811 DiagFoundKind = 2;
7812 break;
7813 default:
7814 DiagFoundKind = 1;
7815 break;
7816 }
7817 Kind = TTP->templateParameterKind();
7818 } else if (isa<ConceptDecl>(Template)) {
7820 DiagFoundKind = 3;
7821 } else if (isa<FunctionTemplateDecl>(Template)) {
7823 DiagFoundKind = 0;
7824 } else if (isa<VarTemplateDecl>(Template)) {
7826 DiagFoundKind = 2;
7827 } else if (isa<ClassTemplateDecl>(Template) ||
7831 DiagFoundKind = 1;
7832 } else {
7833 assert(false && "Unexpected Decl");
7834 }
7835
7836 if (Kind == Param->templateParameterKind()) {
7837 return true;
7838 }
7839
7840 unsigned DiagKind = 0;
7841 switch (Param->templateParameterKind()) {
7843 DiagKind = 2;
7844 break;
7846 DiagKind = 1;
7847 break;
7848 default:
7849 DiagKind = 0;
7850 break;
7851 }
7852 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7853 << DiagKind;
7854 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7855 << DiagFoundKind << Template;
7856 return false;
7857}
7858
7859/// Check a template argument against its corresponding
7860/// template template parameter.
7861///
7862/// This routine implements the semantics of C++ [temp.arg.template].
7863/// It returns true if an error occurred, and false otherwise.
7865 TemplateParameterList *Params,
7867 bool PartialOrdering,
7868 bool *StrictPackMatch) {
7870 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7871 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7872 if (!Template) {
7873 // FIXME: Handle AssumedTemplateNames
7874 // Any dependent template name is fine.
7875 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7876 return false;
7877 }
7878
7879 if (Template->isInvalidDecl())
7880 return true;
7881
7883 return true;
7884 }
7885
7886 // C++1z [temp.arg.template]p3: (DR 150)
7887 // A template-argument matches a template template-parameter P when P
7888 // is at least as specialized as the template-argument A.
7890 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7891 PartialOrdering, StrictPackMatch))
7892 return true;
7893 // P2113
7894 // C++20[temp.func.order]p2
7895 // [...] If both deductions succeed, the partial ordering selects the
7896 // more constrained template (if one exists) as determined below.
7897 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7898 Params->getAssociatedConstraints(ParamsAC);
7899 // C++20[temp.arg.template]p3
7900 // [...] In this comparison, if P is unconstrained, the constraints on A
7901 // are not considered.
7902 if (ParamsAC.empty())
7903 return false;
7904
7905 Template->getAssociatedConstraints(TemplateAC);
7906
7907 bool IsParamAtLeastAsConstrained;
7908 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7909 IsParamAtLeastAsConstrained))
7910 return true;
7911 if (!IsParamAtLeastAsConstrained) {
7912 Diag(Arg.getLocation(),
7913 diag::err_template_template_parameter_not_at_least_as_constrained)
7914 << Template << Param << Arg.getSourceRange();
7915 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7916 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7918 TemplateAC);
7919 return true;
7920 }
7921 return false;
7922}
7923
7925 unsigned HereDiagID,
7926 unsigned ExternalDiagID) {
7927 if (Decl.getLocation().isValid())
7928 return S.Diag(Decl.getLocation(), HereDiagID);
7929
7930 SmallString<128> Str;
7931 llvm::raw_svector_ostream Out(Str);
7933 PP.TerseOutput = 1;
7934 Decl.print(Out, PP);
7935 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7936}
7937
7939 std::optional<SourceRange> ParamRange) {
7941 noteLocation(*this, Decl, diag::note_template_decl_here,
7942 diag::note_template_decl_external);
7943 if (ParamRange && ParamRange->isValid()) {
7944 assert(Decl.getLocation().isValid() &&
7945 "Parameter range has location when Decl does not");
7946 DB << *ParamRange;
7947 }
7948}
7949
7951 noteLocation(*this, Decl, diag::note_template_param_here,
7952 diag::note_template_param_external);
7953}
7954
7955/// Given a non-type template argument that refers to a
7956/// declaration and the type of its corresponding non-type template
7957/// parameter, produce an expression that properly refers to that
7958/// declaration.
7960 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7961 // C++ [temp.param]p8:
7962 //
7963 // A non-type template-parameter of type "array of T" or
7964 // "function returning T" is adjusted to be of type "pointer to
7965 // T" or "pointer to function returning T", respectively.
7966 if (ParamType->isArrayType())
7967 ParamType = Context.getArrayDecayedType(ParamType);
7968 else if (ParamType->isFunctionType())
7969 ParamType = Context.getPointerType(ParamType);
7970
7971 // For a NULL non-type template argument, return nullptr casted to the
7972 // parameter's type.
7973 if (Arg.getKind() == TemplateArgument::NullPtr) {
7974 return ImpCastExprToType(
7975 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7976 ParamType,
7977 ParamType->getAs<MemberPointerType>()
7978 ? CK_NullToMemberPointer
7979 : CK_NullToPointer);
7980 }
7981 assert(Arg.getKind() == TemplateArgument::Declaration &&
7982 "Only declaration template arguments permitted here");
7983
7984 ValueDecl *VD = Arg.getAsDecl();
7985
7986 CXXScopeSpec SS;
7987 if (ParamType->isMemberPointerType()) {
7988 // If this is a pointer to member, we need to use a qualified name to
7989 // form a suitable pointer-to-member constant.
7990 assert(VD->getDeclContext()->isRecord() &&
7991 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7993 CanQualType ClassType =
7994 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7995 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7996 SS.MakeTrivial(Context, Qualifier, Loc);
7997 }
7998
8000 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8001 if (RefExpr.isInvalid())
8002 return ExprError();
8003
8004 // For a pointer, the argument declaration is the pointee. Take its address.
8005 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8006 if (ParamType->isPointerType() && !ElemT.isNull() &&
8007 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8008 // Decay an array argument if we want a pointer to its first element.
8009 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8010 if (RefExpr.isInvalid())
8011 return ExprError();
8012 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8013 // For any other pointer, take the address (or form a pointer-to-member).
8014 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8015 if (RefExpr.isInvalid())
8016 return ExprError();
8017 } else if (ParamType->isRecordType()) {
8018 assert(isa<TemplateParamObjectDecl>(VD) &&
8019 "arg for class template param not a template parameter object");
8020 // No conversions apply in this case.
8021 return RefExpr;
8022 } else {
8023 assert(ParamType->isReferenceType() &&
8024 "unexpected type for decl template argument");
8025 // If the parameter has reference type, wrap it in paretheses so that this
8026 // expression will have the correct type under `decltype`.
8027 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8028 }
8029
8030 // At this point we should have the right value category.
8031 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8032 "value kind mismatch for non-type template argument");
8033
8034 // The type of the template parameter can differ from the type of the
8035 // argument in various ways; convert it now if necessary.
8036 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8037 QualType SrcExprType = RefExpr.get()->getType();
8038 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8039 CastKind CK;
8040 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8041 IsFunctionConversion(SrcExprType, DestExprType)) {
8042 CK = CK_NoOp;
8043 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8044 CK = CK_BitCast;
8045 } else {
8046 // FIXME: Pointers to members can need conversion derived-to-base or
8047 // base-to-derived conversions. We currently don't retain enough
8048 // information to convert properly (we need to track a cast path or
8049 // subobject number in the template argument).
8050 llvm_unreachable(
8051 "unexpected conversion required for non-type template argument");
8052 }
8053 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8054 RefExpr.get()->getValueKind());
8055 }
8056
8057 return RefExpr;
8058}
8059
8060/// Construct a new expression that refers to the given
8061/// integral template argument with the given source-location
8062/// information.
8063///
8064/// This routine takes care of the mapping from an integral template
8065/// argument (which may have any integral type) to the appropriate
8066/// literal value.
8068 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8069 assert(OrigT->isIntegralOrEnumerationType());
8070
8071 // If this is an enum type that we're instantiating, we need to use an integer
8072 // type the same size as the enumerator. We don't want to build an
8073 // IntegerLiteral with enum type. The integer type of an enum type can be of
8074 // any integral type with C++11 enum classes, make sure we create the right
8075 // type of literal for it.
8076 QualType T = OrigT;
8077 if (const auto *ED = OrigT->getAsEnumDecl())
8078 T = ED->getIntegerType();
8079
8080 Expr *E;
8081 if (T->isAnyCharacterType()) {
8083 if (T->isWideCharType())
8085 else if (T->isChar8Type() && S.getLangOpts().Char8)
8087 else if (T->isChar16Type())
8089 else if (T->isChar32Type())
8091 else
8093
8094 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8095 } else if (T->isBooleanType()) {
8096 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8097 } else {
8098 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8099 }
8100
8101 if (OrigT->isEnumeralType()) {
8102 // FIXME: This is a hack. We need a better way to handle substituted
8103 // non-type template parameters.
8104 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8105 nullptr, S.CurFPFeatureOverrides(),
8106 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8107 Loc, Loc);
8108 }
8109
8110 return E;
8111}
8112
8114 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8115 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8116 auto *ILE = new (S.Context)
8117 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8118 ILE->setType(T);
8119 return ILE;
8120 };
8121
8122 switch (Val.getKind()) {
8124 // This cannot occur in a template argument at all.
8125 case APValue::Array:
8126 case APValue::Struct:
8127 case APValue::Union:
8128 // These can only occur within a template parameter object, which is
8129 // represented as a TemplateArgument::Declaration.
8130 llvm_unreachable("unexpected template argument value");
8131
8132 case APValue::Int:
8134 Loc);
8135
8136 case APValue::Float:
8137 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8138 T, Loc);
8139
8142 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8143 Val.getFixedPoint().getScale());
8144
8145 case APValue::ComplexInt: {
8146 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8148 S, ElemT, Val.getComplexIntReal(), Loc),
8150 S, ElemT, Val.getComplexIntImag(), Loc)});
8151 }
8152
8153 case APValue::ComplexFloat: {
8154 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8155 return MakeInitList(
8157 ElemT, Loc),
8159 ElemT, Loc)});
8160 }
8161
8162 case APValue::Vector: {
8163 QualType ElemT = T->castAs<VectorType>()->getElementType();
8165 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8167 S, ElemT, Val.getVectorElt(I), Loc));
8168 return MakeInitList(Elts);
8169 }
8170
8171 case APValue::Matrix:
8172 llvm_unreachable("Matrix template argument expression not yet supported");
8173
8174 case APValue::None:
8176 llvm_unreachable("Unexpected APValue kind.");
8177 case APValue::LValue:
8179 // There isn't necessarily a valid equivalent source-level syntax for
8180 // these; in particular, a naive lowering might violate access control.
8181 // So for now we lower to a ConstantExpr holding the value, wrapped around
8182 // an OpaqueValueExpr.
8183 // FIXME: We should have a better representation for this.
8185 if (T->isReferenceType()) {
8186 T = T->getPointeeType();
8187 VK = VK_LValue;
8188 }
8189 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8190 return ConstantExpr::Create(S.Context, OVE, Val);
8191 }
8192 llvm_unreachable("Unhandled APValue::ValueKind enum");
8193}
8194
8197 SourceLocation Loc) {
8198 switch (Arg.getKind()) {
8204 llvm_unreachable("not a non-type template argument");
8205
8207 return Arg.getAsExpr();
8208
8212 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8213
8216 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8217
8220 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8221 }
8222 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8223}
8224
8225/// Match two template parameters within template parameter lists.
8227 Sema &S, NamedDecl *New,
8228 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8229 const NamedDecl *OldInstFrom, bool Complain,
8231 // Check the actual kind (type, non-type, template).
8232 if (Old->getKind() != New->getKind()) {
8233 if (Complain) {
8234 unsigned NextDiag = diag::err_template_param_different_kind;
8235 if (TemplateArgLoc.isValid()) {
8236 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8237 NextDiag = diag::note_template_param_different_kind;
8238 }
8239 S.Diag(New->getLocation(), NextDiag)
8240 << (Kind != Sema::TPL_TemplateMatch);
8241 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8242 << (Kind != Sema::TPL_TemplateMatch);
8243 }
8244
8245 return false;
8246 }
8247
8248 // Check that both are parameter packs or neither are parameter packs.
8249 // However, if we are matching a template template argument to a
8250 // template template parameter, the template template parameter can have
8251 // a parameter pack where the template template argument does not.
8252 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8253 if (Complain) {
8254 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8255 if (TemplateArgLoc.isValid()) {
8256 S.Diag(TemplateArgLoc,
8257 diag::err_template_arg_template_params_mismatch);
8258 NextDiag = diag::note_template_parameter_pack_non_pack;
8259 }
8260
8261 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8263 : 2;
8264 S.Diag(New->getLocation(), NextDiag)
8265 << ParamKind << New->isParameterPack();
8266 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8267 << ParamKind << Old->isParameterPack();
8268 }
8269
8270 return false;
8271 }
8272 // For non-type template parameters, check the type of the parameter.
8273 if (NonTypeTemplateParmDecl *OldNTTP =
8274 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8276
8277 // If we are matching a template template argument to a template
8278 // template parameter and one of the non-type template parameter types
8279 // is dependent, then we must wait until template instantiation time
8280 // to actually compare the arguments.
8282 (!OldNTTP->getType()->isDependentType() &&
8283 !NewNTTP->getType()->isDependentType())) {
8284 // C++20 [temp.over.link]p6:
8285 // Two [non-type] template-parameters are equivalent [if] they have
8286 // equivalent types ignoring the use of type-constraints for
8287 // placeholder types
8288 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8289 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8290 if (!S.Context.hasSameType(OldType, NewType)) {
8291 if (Complain) {
8292 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8293 if (TemplateArgLoc.isValid()) {
8294 S.Diag(TemplateArgLoc,
8295 diag::err_template_arg_template_params_mismatch);
8296 NextDiag = diag::note_template_nontype_parm_different_type;
8297 }
8298 S.Diag(NewNTTP->getLocation(), NextDiag)
8299 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8300 S.Diag(OldNTTP->getLocation(),
8301 diag::note_template_nontype_parm_prev_declaration)
8302 << OldNTTP->getType();
8303 }
8304 return false;
8305 }
8306 }
8307 }
8308 // For template template parameters, check the template parameter types.
8309 // The template parameter lists of template template
8310 // parameters must agree.
8311 else if (TemplateTemplateParmDecl *OldTTP =
8312 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8314 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8315 return false;
8317 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8318 OldTTP->getTemplateParameters(), Complain,
8321 : Kind),
8322 TemplateArgLoc))
8323 return false;
8324 }
8325
8329 const Expr *NewC = nullptr, *OldC = nullptr;
8330
8332 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8333 NewC = TC->getImmediatelyDeclaredConstraint();
8334 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8335 OldC = TC->getImmediatelyDeclaredConstraint();
8336 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8337 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8338 ->getPlaceholderTypeConstraint())
8339 NewC = E;
8340 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8341 ->getPlaceholderTypeConstraint())
8342 OldC = E;
8343 } else
8344 llvm_unreachable("unexpected template parameter type");
8345
8346 auto Diagnose = [&] {
8347 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8348 diag::err_template_different_type_constraint);
8349 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8350 diag::note_template_prev_declaration) << /*declaration*/0;
8351 };
8352
8353 if (!NewC != !OldC) {
8354 if (Complain)
8355 Diagnose();
8356 return false;
8357 }
8358
8359 if (NewC) {
8360 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8361 NewC)) {
8362 if (Complain)
8363 Diagnose();
8364 return false;
8365 }
8366 }
8367 }
8368
8369 return true;
8370}
8371
8372/// Diagnose a known arity mismatch when comparing template argument
8373/// lists.
8374static
8379 SourceLocation TemplateArgLoc) {
8380 unsigned NextDiag = diag::err_template_param_list_different_arity;
8381 if (TemplateArgLoc.isValid()) {
8382 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8383 NextDiag = diag::note_template_param_list_different_arity;
8384 }
8385 S.Diag(New->getTemplateLoc(), NextDiag)
8386 << (New->size() > Old->size())
8387 << (Kind != Sema::TPL_TemplateMatch)
8388 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8389 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8390 << (Kind != Sema::TPL_TemplateMatch)
8391 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8392}
8393
8396 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8397 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8398 if (Old->size() != New->size()) {
8399 if (Complain)
8401 TemplateArgLoc);
8402
8403 return false;
8404 }
8405
8406 // C++0x [temp.arg.template]p3:
8407 // A template-argument matches a template template-parameter (call it P)
8408 // when each of the template parameters in the template-parameter-list of
8409 // the template-argument's corresponding class template or alias template
8410 // (call it A) matches the corresponding template parameter in the
8411 // template-parameter-list of P. [...]
8412 TemplateParameterList::iterator NewParm = New->begin();
8413 TemplateParameterList::iterator NewParmEnd = New->end();
8414 for (TemplateParameterList::iterator OldParm = Old->begin(),
8415 OldParmEnd = Old->end();
8416 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8417 if (NewParm == NewParmEnd) {
8418 if (Complain)
8420 TemplateArgLoc);
8421 return false;
8422 }
8423 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8424 OldInstFrom, Complain, Kind,
8425 TemplateArgLoc))
8426 return false;
8427 }
8428
8429 // Make sure we exhausted all of the arguments.
8430 if (NewParm != NewParmEnd) {
8431 if (Complain)
8433 TemplateArgLoc);
8434
8435 return false;
8436 }
8437
8438 if (Kind != TPL_TemplateParamsEquivalent) {
8439 const Expr *NewRC = New->getRequiresClause();
8440 const Expr *OldRC = Old->getRequiresClause();
8441
8442 auto Diagnose = [&] {
8443 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8444 diag::err_template_different_requires_clause);
8445 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8446 diag::note_template_prev_declaration) << /*declaration*/0;
8447 };
8448
8449 if (!NewRC != !OldRC) {
8450 if (Complain)
8451 Diagnose();
8452 return false;
8453 }
8454
8455 if (NewRC) {
8456 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8457 NewRC)) {
8458 if (Complain)
8459 Diagnose();
8460 return false;
8461 }
8462 }
8463 }
8464
8465 return true;
8466}
8467
8468bool
8470 if (!S)
8471 return false;
8472
8473 // Find the nearest enclosing declaration scope.
8474 S = S->getDeclParent();
8475
8476 // C++ [temp.pre]p6: [P2096]
8477 // A template, explicit specialization, or partial specialization shall not
8478 // have C linkage.
8479 DeclContext *Ctx = S->getEntity();
8480 if (Ctx && Ctx->isExternCContext()) {
8481 SourceRange Range =
8482 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8483 ? TemplateParams->getParam(0)->getSourceRange()
8484 : TemplateParams->getSourceRange();
8485 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8486 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8487 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8488 return true;
8489 }
8490 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8491
8492 // C++ [temp]p2:
8493 // A template-declaration can appear only as a namespace scope or
8494 // class scope declaration.
8495 // C++ [temp.expl.spec]p3:
8496 // An explicit specialization may be declared in any scope in which the
8497 // corresponding primary template may be defined.
8498 // C++ [temp.class.spec]p6: [P2096]
8499 // A partial specialization may be declared in any scope in which the
8500 // corresponding primary template may be defined.
8501 if (Ctx) {
8502 if (Ctx->isFileContext())
8503 return false;
8504 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8505 // C++ [temp.mem]p2:
8506 // A local class shall not have member templates.
8507 if (RD->isLocalClass())
8508 return Diag(TemplateParams->getTemplateLoc(),
8509 diag::err_template_inside_local_class)
8510 << TemplateParams->getSourceRange();
8511 else
8512 return false;
8513 }
8514 }
8515
8516 return Diag(TemplateParams->getTemplateLoc(),
8517 diag::err_template_outside_namespace_or_class_scope)
8518 << TemplateParams->getSourceRange();
8519}
8520
8521/// Determine what kind of template specialization the given declaration
8522/// is.
8524 if (!D)
8525 return TSK_Undeclared;
8526
8527 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8528 return Record->getTemplateSpecializationKind();
8529 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8530 return Function->getTemplateSpecializationKind();
8531 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8532 return Var->getTemplateSpecializationKind();
8533
8534 return TSK_Undeclared;
8535}
8536
8537/// Check whether a specialization is well-formed in the current
8538/// context.
8539///
8540/// This routine determines whether a template specialization can be declared
8541/// in the current context (C++ [temp.expl.spec]p2).
8542///
8543/// \param S the semantic analysis object for which this check is being
8544/// performed.
8545///
8546/// \param Specialized the entity being specialized or instantiated, which
8547/// may be a kind of template (class template, function template, etc.) or
8548/// a member of a class template (member function, static data member,
8549/// member class).
8550///
8551/// \param PrevDecl the previous declaration of this entity, if any.
8552///
8553/// \param Loc the location of the explicit specialization or instantiation of
8554/// this entity.
8555///
8556/// \param IsPartialSpecialization whether this is a partial specialization of
8557/// a class template.
8558///
8559/// \returns true if there was an error that we cannot recover from, false
8560/// otherwise.
8562 NamedDecl *Specialized,
8563 NamedDecl *PrevDecl,
8564 SourceLocation Loc,
8566 // Keep these "kind" numbers in sync with the %select statements in the
8567 // various diagnostics emitted by this routine.
8568 int EntityKind = 0;
8569 if (isa<ClassTemplateDecl>(Specialized))
8570 EntityKind = IsPartialSpecialization? 1 : 0;
8571 else if (isa<VarTemplateDecl>(Specialized))
8572 EntityKind = IsPartialSpecialization ? 3 : 2;
8573 else if (isa<FunctionTemplateDecl>(Specialized))
8574 EntityKind = 4;
8575 else if (isa<CXXMethodDecl>(Specialized))
8576 EntityKind = 5;
8577 else if (isa<VarDecl>(Specialized))
8578 EntityKind = 6;
8579 else if (isa<RecordDecl>(Specialized))
8580 EntityKind = 7;
8581 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8582 EntityKind = 8;
8583 else {
8584 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8585 << S.getLangOpts().CPlusPlus11;
8586 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8587 return true;
8588 }
8589
8590 // C++ [temp.expl.spec]p2:
8591 // An explicit specialization may be declared in any scope in which
8592 // the corresponding primary template may be defined.
8594 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8595 << Specialized;
8596 return true;
8597 }
8598
8599 // C++ [temp.class.spec]p6:
8600 // A class template partial specialization may be declared in any
8601 // scope in which the primary template may be defined.
8602 DeclContext *SpecializedContext =
8603 Specialized->getDeclContext()->getRedeclContext();
8605
8606 // Make sure that this redeclaration (or definition) occurs in the same
8607 // scope or an enclosing namespace.
8608 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8609 : DC->Equals(SpecializedContext))) {
8610 if (isa<TranslationUnitDecl>(SpecializedContext))
8611 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8612 << EntityKind << Specialized;
8613 else {
8614 auto *ND = cast<NamedDecl>(SpecializedContext);
8615 int Diag = diag::err_template_spec_redecl_out_of_scope;
8616 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8617 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8618 S.Diag(Loc, Diag) << EntityKind << Specialized
8619 << ND << isa<CXXRecordDecl>(ND);
8620 }
8621
8622 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8623
8624 // Don't allow specializing in the wrong class during error recovery.
8625 // Otherwise, things can go horribly wrong.
8626 if (DC->isRecord())
8627 return true;
8628 }
8629
8630 return false;
8631}
8632
8634 if (!E->isTypeDependent())
8635 return SourceLocation();
8636 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8637 Checker.TraverseStmt(E);
8638 if (Checker.MatchLoc.isInvalid())
8639 return E->getSourceRange();
8640 return Checker.MatchLoc;
8641}
8642
8643static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8644 if (!TL.getType()->isDependentType())
8645 return SourceLocation();
8646 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8647 Checker.TraverseTypeLoc(TL);
8648 if (Checker.MatchLoc.isInvalid())
8649 return TL.getSourceRange();
8650 return Checker.MatchLoc;
8651}
8652
8653/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8654/// that checks non-type template partial specialization arguments.
8656 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8657 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8658 bool HasError = false;
8659 for (unsigned I = 0; I != NumArgs; ++I) {
8660 if (Args[I].getKind() == TemplateArgument::Pack) {
8662 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8663 Args[I].pack_size(), IsDefaultArgument))
8664 return true;
8665
8666 continue;
8667 }
8668
8669 if (Args[I].getKind() != TemplateArgument::Expression)
8670 continue;
8671
8672 Expr *ArgExpr = Args[I].getAsExpr();
8673 if (ArgExpr->containsErrors()) {
8674 HasError = true;
8675 continue;
8676 }
8677
8678 // We can have a pack expansion of any of the bullets below.
8679 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8680 ArgExpr = Expansion->getPattern();
8681
8682 // Strip off any implicit casts we added as part of type checking.
8683 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8684 ArgExpr = ICE->getSubExpr();
8685
8686 // C++ [temp.class.spec]p8:
8687 // A non-type argument is non-specialized if it is the name of a
8688 // non-type parameter. All other non-type arguments are
8689 // specialized.
8690 //
8691 // Below, we check the two conditions that only apply to
8692 // specialized non-type arguments, so skip any non-specialized
8693 // arguments.
8694 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8695 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8696 continue;
8697
8698 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8699 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8700 continue;
8701 }
8702
8703 // C++ [temp.class.spec]p9:
8704 // Within the argument list of a class template partial
8705 // specialization, the following restrictions apply:
8706 // -- A partially specialized non-type argument expression
8707 // shall not involve a template parameter of the partial
8708 // specialization except when the argument expression is a
8709 // simple identifier.
8710 // -- The type of a template parameter corresponding to a
8711 // specialized non-type argument shall not be dependent on a
8712 // parameter of the specialization.
8713 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8714 // We implement a compromise between the original rules and DR1315:
8715 // -- A specialized non-type template argument shall not be
8716 // type-dependent and the corresponding template parameter
8717 // shall have a non-dependent type.
8718 SourceRange ParamUseRange =
8719 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8720 if (ParamUseRange.isValid()) {
8721 if (IsDefaultArgument) {
8722 S.Diag(TemplateNameLoc,
8723 diag::err_dependent_non_type_arg_in_partial_spec);
8724 S.Diag(ParamUseRange.getBegin(),
8725 diag::note_dependent_non_type_default_arg_in_partial_spec)
8726 << ParamUseRange;
8727 } else {
8728 S.Diag(ParamUseRange.getBegin(),
8729 diag::err_dependent_non_type_arg_in_partial_spec)
8730 << ParamUseRange;
8731 }
8732 return true;
8733 }
8734
8735 ParamUseRange = findTemplateParameter(
8736 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8737 if (ParamUseRange.isValid()) {
8738 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8739 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8740 << Param->getType();
8742 return true;
8743 }
8744 }
8745
8746 return HasError;
8747}
8748
8750 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8751 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8752 // We have to be conservative when checking a template in a dependent
8753 // context.
8754 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8755 return false;
8756
8757 TemplateParameterList *TemplateParams =
8758 PrimaryTemplate->getTemplateParameters();
8759 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8761 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8762 if (!Param)
8763 continue;
8764
8765 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8766 Param, &TemplateArgs[I],
8767 1, I >= NumExplicit))
8768 return true;
8769 }
8770
8771 return false;
8772}
8773
8775 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8776 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8778 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8779 assert(TUK != TagUseKind::Reference && "References are not specializations");
8780
8781 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8782 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8783 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8784
8785 // Find the class template we're specializing
8786 TemplateName Name = TemplateId.Template.get();
8788 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8789
8790 if (!ClassTemplate) {
8791 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8792 << (Name.getAsTemplateDecl() &&
8794 return true;
8795 }
8796
8797 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8798 auto Message = DSA->getMessage();
8799 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8800 << ClassTemplate << !Message.empty() << Message;
8801 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8802 }
8803
8804 if (S->isTemplateParamScope())
8805 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8806
8807 DeclContext *DC = ClassTemplate->getDeclContext();
8808
8809 bool isMemberSpecialization = false;
8810 bool isPartialSpecialization = false;
8811
8812 if (SS.isSet()) {
8813 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8814 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8815 TemplateNameLoc, &TemplateId,
8816 /*IsMemberSpecialization=*/false))
8817 return true;
8818 }
8819
8820 // Check the validity of the template headers that introduce this
8821 // template.
8822 // FIXME: We probably shouldn't complain about these headers for
8823 // friend declarations.
8824 bool Invalid = false;
8825 TemplateParameterList *TemplateParams =
8827 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8828 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8829 if (Invalid)
8830 return true;
8831
8832 // Check that we can declare a template specialization here.
8833 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8834 return true;
8835
8836 if (TemplateParams && DC->isDependentContext()) {
8837 ContextRAII SavedContext(*this, DC);
8839 return true;
8840 }
8841
8842 if (TemplateParams && TemplateParams->size() > 0) {
8843 isPartialSpecialization = true;
8844
8845 if (TUK == TagUseKind::Friend) {
8846 Diag(KWLoc, diag::err_partial_specialization_friend)
8847 << SourceRange(LAngleLoc, RAngleLoc);
8848 return true;
8849 }
8850
8851 // C++ [temp.class.spec]p10:
8852 // The template parameter list of a specialization shall not
8853 // contain default template argument values.
8854 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8855 Decl *Param = TemplateParams->getParam(I);
8856 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8857 if (TTP->hasDefaultArgument()) {
8858 Diag(TTP->getDefaultArgumentLoc(),
8859 diag::err_default_arg_in_partial_spec);
8860 TTP->removeDefaultArgument();
8861 }
8862 } else if (NonTypeTemplateParmDecl *NTTP
8863 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8864 if (NTTP->hasDefaultArgument()) {
8865 Diag(NTTP->getDefaultArgumentLoc(),
8866 diag::err_default_arg_in_partial_spec)
8867 << NTTP->getDefaultArgument().getSourceRange();
8868 NTTP->removeDefaultArgument();
8869 }
8870 } else {
8872 if (TTP->hasDefaultArgument()) {
8874 diag::err_default_arg_in_partial_spec)
8876 TTP->removeDefaultArgument();
8877 }
8878 }
8879 }
8880 } else if (TemplateParams) {
8881 if (TUK == TagUseKind::Friend)
8882 Diag(KWLoc, diag::err_template_spec_friend)
8884 SourceRange(TemplateParams->getTemplateLoc(),
8885 TemplateParams->getRAngleLoc()))
8886 << SourceRange(LAngleLoc, RAngleLoc);
8887 } else {
8888 assert(TUK == TagUseKind::Friend &&
8889 "should have a 'template<>' for this decl");
8890 }
8891
8892 // Check that the specialization uses the same tag kind as the
8893 // original template.
8895 assert(Kind != TagTypeKind::Enum &&
8896 "Invalid enum tag in class template spec!");
8897 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8898 TUK == TagUseKind::Definition, KWLoc,
8899 ClassTemplate->getIdentifier())) {
8900 Diag(KWLoc, diag::err_use_with_wrong_tag)
8901 << ClassTemplate
8903 ClassTemplate->getTemplatedDecl()->getKindName());
8904 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8905 diag::note_previous_use);
8906 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8907 }
8908
8909 // Translate the parser's template argument list in our AST format.
8910 TemplateArgumentListInfo TemplateArgs =
8911 makeTemplateArgumentListInfo(*this, TemplateId);
8912
8913 // Check for unexpanded parameter packs in any of the template arguments.
8914 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8915 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8916 isPartialSpecialization
8919 return true;
8920
8921 // Check that the template argument list is well-formed for this
8922 // template.
8924 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8925 /*DefaultArgs=*/{},
8926 /*PartialTemplateArgs=*/false, CTAI,
8927 /*UpdateArgsWithConversions=*/true))
8928 return true;
8929
8930 // Find the class template (partial) specialization declaration that
8931 // corresponds to these arguments.
8932 if (isPartialSpecialization) {
8934 TemplateArgs.size(),
8935 CTAI.CanonicalConverted))
8936 return true;
8937
8938 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8939 // also do it during instantiation.
8940 if (!Name.isDependent() &&
8941 !TemplateSpecializationType::anyDependentTemplateArguments(
8942 TemplateArgs, CTAI.CanonicalConverted)) {
8943 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8944 << ClassTemplate->getDeclName();
8945 isPartialSpecialization = false;
8946 Invalid = true;
8947 }
8948 }
8949
8950 void *InsertPos = nullptr;
8951 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8952
8953 if (isPartialSpecialization)
8954 PrevDecl = ClassTemplate->findPartialSpecialization(
8955 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8956 else
8957 PrevDecl =
8958 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8959
8961
8962 // Check whether we can declare a class template specialization in
8963 // the current scope.
8964 if (TUK != TagUseKind::Friend &&
8966 TemplateNameLoc,
8967 isPartialSpecialization))
8968 return true;
8969
8970 if (!isPartialSpecialization) {
8971 // Create a new class template specialization declaration node for
8972 // this explicit specialization or friend declaration.
8974 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8975 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8976 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8978 if (TemplateParameterLists.size() > 0) {
8979 Specialization->setTemplateParameterListsInfo(Context,
8980 TemplateParameterLists);
8981 }
8982
8983 if (!PrevDecl)
8984 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8985 } else {
8987 Context.getCanonicalTemplateSpecializationType(
8989 TemplateName(ClassTemplate->getCanonicalDecl()),
8990 CTAI.CanonicalConverted));
8991 if (Context.hasSameType(
8992 CanonType,
8993 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8994 (!Context.getLangOpts().CPlusPlus20 ||
8995 !TemplateParams->hasAssociatedConstraints())) {
8996 // C++ [temp.class.spec]p9b3:
8997 //
8998 // -- The argument list of the specialization shall not be identical
8999 // to the implicit argument list of the primary template.
9000 //
9001 // This rule has since been removed, because it's redundant given DR1495,
9002 // but we keep it because it produces better diagnostics and recovery.
9003 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9004 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9005 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9006 return CheckClassTemplate(
9007 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9008 TemplateNameLoc, Attr, TemplateParams, AS_none,
9009 /*ModulePrivateLoc=*/SourceLocation(),
9010 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9011 TemplateParameterLists.data(), isMemberSpecialization);
9012 }
9013
9014 // Create a new class template partial specialization declaration node.
9016 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9019 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9020 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9021 Partial->setTemplateArgsAsWritten(TemplateArgs);
9022 SetNestedNameSpecifier(*this, Partial, SS);
9023 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9025 Context, TemplateParameterLists.drop_back(1));
9026 }
9027
9028 if (!PrevPartial)
9029 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9030 Specialization = Partial;
9031
9032 // If we are providing an explicit specialization of a member class
9033 // template specialization, make a note of that.
9034 if (isMemberSpecialization)
9035 Partial->setMemberSpecialization();
9036
9038 }
9039
9040 // C++ [temp.expl.spec]p6:
9041 // If a template, a member template or the member of a class template is
9042 // explicitly specialized then that specialization shall be declared
9043 // before the first use of that specialization that would cause an implicit
9044 // instantiation to take place, in every translation unit in which such a
9045 // use occurs; no diagnostic is required.
9046 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9047 bool Okay = false;
9048 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9049 // Is there any previous explicit specialization declaration?
9051 Okay = true;
9052 break;
9053 }
9054 }
9055
9056 if (!Okay) {
9057 SourceRange Range(TemplateNameLoc, RAngleLoc);
9058 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9059 << Context.getCanonicalTagType(Specialization) << Range;
9060
9061 Diag(PrevDecl->getPointOfInstantiation(),
9062 diag::note_instantiation_required_here)
9063 << (PrevDecl->getTemplateSpecializationKind()
9065 return true;
9066 }
9067 }
9068
9069 // If this is not a friend, note that this is an explicit specialization.
9070 if (TUK != TagUseKind::Friend)
9071 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9072
9073 // Check that this isn't a redefinition of this specialization.
9074 if (TUK == TagUseKind::Definition) {
9075 RecordDecl *Def = Specialization->getDefinition();
9076 NamedDecl *Hidden = nullptr;
9077 bool HiddenDefVisible = false;
9078 if (Def && SkipBody &&
9079 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9080 SkipBody->ShouldSkip = true;
9081 SkipBody->Previous = Def;
9082 if (!HiddenDefVisible && Hidden)
9084 } else if (Def) {
9085 SourceRange Range(TemplateNameLoc, RAngleLoc);
9086 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9087 Diag(Def->getLocation(), diag::note_previous_definition);
9088 Specialization->setInvalidDecl();
9089 return true;
9090 }
9091 }
9092
9095
9096 // Add alignment attributes if necessary; these attributes are checked when
9097 // the ASTContext lays out the structure.
9098 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9099 if (LangOpts.HLSL)
9100 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9103 }
9104
9105 if (ModulePrivateLoc.isValid())
9106 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9107 << (isPartialSpecialization? 1 : 0)
9108 << FixItHint::CreateRemoval(ModulePrivateLoc);
9109
9110 // C++ [temp.expl.spec]p9:
9111 // A template explicit specialization is in the scope of the
9112 // namespace in which the template was defined.
9113 //
9114 // We actually implement this paragraph where we set the semantic
9115 // context (in the creation of the ClassTemplateSpecializationDecl),
9116 // but we also maintain the lexical context where the actual
9117 // definition occurs.
9118 Specialization->setLexicalDeclContext(CurContext);
9119
9120 // We may be starting the definition of this specialization.
9121 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9122 Specialization->startDefinition();
9123
9124 if (TUK == TagUseKind::Friend) {
9125 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9126 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9127 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9129 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9130 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9131
9132 // Build the fully-sugared type for this class template
9133 // specialization as the user wrote in the specialization
9134 // itself. This means that we'll pretty-print the type retrieved
9135 // from the specialization's declaration the way that the user
9136 // actually wrote the specialization, rather than formatting the
9137 // name based on the "canonical" representation used to store the
9138 // template arguments in the specialization.
9140 TemplateNameLoc,
9141 WrittenTy,
9142 /*FIXME:*/KWLoc);
9143 Friend->setAccess(AS_public);
9144 CurContext->addDecl(Friend);
9145 } else {
9146 // Add the specialization into its lexical context, so that it can
9147 // be seen when iterating through the list of declarations in that
9148 // context. However, specializations are not found by name lookup.
9149 CurContext->addDecl(Specialization);
9150 }
9151
9152 if (SkipBody && SkipBody->ShouldSkip)
9153 return SkipBody->Previous;
9154
9155 Specialization->setInvalidDecl(Invalid);
9157 return Specialization;
9158}
9159
9161 MultiTemplateParamsArg TemplateParameterLists,
9162 Declarator &D) {
9163 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9164 ActOnDocumentableDecl(NewDecl);
9165 return NewDecl;
9166}
9167
9169 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9170 const IdentifierInfo *Name, SourceLocation NameLoc) {
9171 DeclContext *DC = CurContext;
9172
9173 if (!DC->getRedeclContext()->isFileContext()) {
9174 Diag(NameLoc,
9175 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9176 return nullptr;
9177 }
9178
9179 if (TemplateParameterLists.size() > 1) {
9180 Diag(NameLoc, diag::err_concept_extra_headers);
9181 return nullptr;
9182 }
9183
9184 TemplateParameterList *Params = TemplateParameterLists.front();
9185
9186 if (Params->size() == 0) {
9187 Diag(NameLoc, diag::err_concept_no_parameters);
9188 return nullptr;
9189 }
9190
9191 // Ensure that the parameter pack, if present, is the last parameter in the
9192 // template.
9193 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9194 ParamEnd = Params->end();
9195 ParamIt != ParamEnd; ++ParamIt) {
9196 Decl const *Param = *ParamIt;
9197 if (Param->isParameterPack()) {
9198 if (++ParamIt == ParamEnd)
9199 break;
9200 Diag(Param->getLocation(),
9201 diag::err_template_param_pack_must_be_last_template_parameter);
9202 return nullptr;
9203 }
9204 }
9205
9206 ConceptDecl *NewDecl =
9207 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9208
9209 if (NewDecl->hasAssociatedConstraints()) {
9210 // C++2a [temp.concept]p4:
9211 // A concept shall not have associated constraints.
9212 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9213 NewDecl->setInvalidDecl();
9214 }
9215
9216 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9217 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9219 LookupName(Previous, S);
9220 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9221 /*AllowInlineNamespace*/ false);
9222
9223 // We cannot properly handle redeclarations until we parse the constraint
9224 // expression, so only inject the name if we are sure we are not redeclaring a
9225 // symbol
9226 if (Previous.empty())
9227 PushOnScopeChains(NewDecl, S, true);
9228
9229 return NewDecl;
9230}
9231
9233 bool Found = false;
9234 LookupResult::Filter F = R.makeFilter();
9235 while (F.hasNext()) {
9236 NamedDecl *D = F.next();
9237 if (D == C) {
9238 F.erase();
9239 Found = true;
9240 break;
9241 }
9242 }
9243 F.done();
9244 return Found;
9245}
9246
9249 Expr *ConstraintExpr,
9250 const ParsedAttributesView &Attrs) {
9251 assert(!C->hasDefinition() && "Concept already defined");
9252 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9253 C->setInvalidDecl();
9254 return nullptr;
9255 }
9256 C->setDefinition(ConstraintExpr);
9257 ProcessDeclAttributeList(S, C, Attrs);
9258
9259 // Check for conflicting previous declaration.
9260 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9261 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9263 LookupName(Previous, S);
9264 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9265 /*AllowInlineNamespace*/ false);
9266 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9267 bool AddToScope = true;
9268 CheckConceptRedefinition(C, Previous, AddToScope);
9269
9271 if (!WasAlreadyAdded && AddToScope)
9272 PushOnScopeChains(C, S);
9273
9274 return C;
9275}
9276
9278 LookupResult &Previous, bool &AddToScope) {
9279 AddToScope = true;
9280
9281 if (Previous.empty())
9282 return;
9283
9284 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9285 if (!OldConcept) {
9286 auto *Old = Previous.getRepresentativeDecl();
9287 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9288 << NewDecl->getDeclName();
9289 notePreviousDefinition(Old, NewDecl->getLocation());
9290 AddToScope = false;
9291 return;
9292 }
9293 // Check if we can merge with a concept declaration.
9294 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9295 if (!IsSame) {
9296 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9297 << NewDecl->getDeclName();
9298 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9299 AddToScope = false;
9300 return;
9301 }
9302 if (hasReachableDefinition(OldConcept) &&
9303 IsRedefinitionInModule(NewDecl, OldConcept)) {
9304 Diag(NewDecl->getLocation(), diag::err_redefinition)
9305 << NewDecl->getDeclName();
9306 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9307 AddToScope = false;
9308 return;
9309 }
9310 if (!Previous.isSingleResult()) {
9311 // FIXME: we should produce an error in case of ambig and failed lookups.
9312 // Other decls (e.g. namespaces) also have this shortcoming.
9313 return;
9314 }
9315 // We unwrap canonical decl late to check for module visibility.
9316 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9317}
9318
9320 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9321 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9322 Diag(Loc, diag::err_recursive_concept) << CE;
9323 Diag(CE->getLocation(), diag::note_declared_at);
9324 CE->setInvalidDecl();
9325 return true;
9326 }
9327 // Concept template parameters don't have a definition and can't
9328 // be defined recursively.
9329 return false;
9330}
9331
9332/// \brief Strips various properties off an implicit instantiation
9333/// that has just been explicitly specialized.
9334static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9335 if (MinGW || (isa<FunctionDecl>(D) &&
9336 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9337 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9338
9339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9340 FD->setInlineSpecified(false);
9341}
9342
9343/// Create an ExplicitInstantiationDecl to record source-location info for an
9344/// explicit template instantiation statement, and add it to \p CurContext.
9345///
9346/// For class templates / nested classes, the caller should build a
9347/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9348/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9349///
9350/// For function / variable templates, the caller should pass TypeAsWritten for
9351/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9353 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9354 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9355 NestedNameSpecifierLoc QualifierLoc,
9356 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9357 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9359 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9360 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9361 Context.addExplicitInstantiationDecl(Spec, EID);
9362 CurContext->addDecl(EID);
9363}
9364
9365/// Compute the diagnostic location for an explicit instantiation
9366// declaration or definition.
9367static SourceLocation
9369 SourceLocation PointOfInstantiation) {
9370 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9371 if (EID->getTemplateSpecializationKind() ==
9373 return EID->getTemplateLoc();
9374
9375 // Explicit instantiations following a specialization have no effect and
9376 // hence no PointOfInstantiation. In that case, walk decl backwards
9377 // until a valid name loc is found.
9378 SourceLocation PrevDiagLoc = PointOfInstantiation;
9379 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9380 Prev = Prev->getPreviousDecl()) {
9381 PrevDiagLoc = Prev->getLocation();
9382 }
9383 assert(PrevDiagLoc.isValid() &&
9384 "Explicit instantiation without point of instantiation?");
9385 return PrevDiagLoc;
9386}
9387
9388bool
9391 NamedDecl *PrevDecl,
9393 SourceLocation PrevPointOfInstantiation,
9394 bool &HasNoEffect) {
9395 HasNoEffect = false;
9396
9397 switch (NewTSK) {
9398 case TSK_Undeclared:
9400 assert(
9401 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9402 "previous declaration must be implicit!");
9403 return false;
9404
9406 switch (PrevTSK) {
9407 case TSK_Undeclared:
9409 // Okay, we're just specializing something that is either already
9410 // explicitly specialized or has merely been mentioned without any
9411 // instantiation.
9412 return false;
9413
9415 if (PrevPointOfInstantiation.isInvalid()) {
9416 // The declaration itself has not actually been instantiated, so it is
9417 // still okay to specialize it.
9419 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9420 return false;
9421 }
9422 // Fall through
9423 [[fallthrough]];
9424
9427 assert((PrevTSK == TSK_ImplicitInstantiation ||
9428 PrevPointOfInstantiation.isValid()) &&
9429 "Explicit instantiation without point of instantiation?");
9430
9431 // C++ [temp.expl.spec]p6:
9432 // If a template, a member template or the member of a class template
9433 // is explicitly specialized then that specialization shall be declared
9434 // before the first use of that specialization that would cause an
9435 // implicit instantiation to take place, in every translation unit in
9436 // which such a use occurs; no diagnostic is required.
9437 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9438 // Is there any previous explicit specialization declaration?
9440 return false;
9441 }
9442
9443 Diag(NewLoc, diag::err_specialization_after_instantiation)
9444 << PrevDecl;
9445 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9446 << (PrevTSK != TSK_ImplicitInstantiation);
9447
9448 return true;
9449 }
9450 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9451
9453 switch (PrevTSK) {
9455 // This explicit instantiation declaration is redundant (that's okay).
9456 HasNoEffect = true;
9457 return false;
9458
9459 case TSK_Undeclared:
9461 // We're explicitly instantiating something that may have already been
9462 // implicitly instantiated; that's fine.
9463 return false;
9464
9466 // C++0x [temp.explicit]p4:
9467 // For a given set of template parameters, if an explicit instantiation
9468 // of a template appears after a declaration of an explicit
9469 // specialization for that template, the explicit instantiation has no
9470 // effect.
9471 HasNoEffect = true;
9472 return false;
9473
9475 // C++0x [temp.explicit]p10:
9476 // If an entity is the subject of both an explicit instantiation
9477 // declaration and an explicit instantiation definition in the same
9478 // translation unit, the definition shall follow the declaration.
9479 Diag(NewLoc,
9480 diag::err_explicit_instantiation_declaration_after_definition);
9481
9482 // Explicit instantiations following a specialization have no effect and
9483 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9484 // until a valid name loc is found.
9485 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9486 diag::note_explicit_instantiation_definition_here);
9487 HasNoEffect = true;
9488 return false;
9489 }
9490 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9491
9493 switch (PrevTSK) {
9494 case TSK_Undeclared:
9496 // We're explicitly instantiating something that may have already been
9497 // implicitly instantiated; that's fine.
9498 return false;
9499
9501 // C++ DR 259, C++0x [temp.explicit]p4:
9502 // For a given set of template parameters, if an explicit
9503 // instantiation of a template appears after a declaration of
9504 // an explicit specialization for that template, the explicit
9505 // instantiation has no effect.
9506 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9507 << PrevDecl;
9508 Diag(PrevDecl->getLocation(),
9509 diag::note_previous_template_specialization);
9510 HasNoEffect = true;
9511 return false;
9512
9514 // We're explicitly instantiating a definition for something for which we
9515 // were previously asked to suppress instantiations. That's fine.
9516
9517 // C++0x [temp.explicit]p4:
9518 // For a given set of template parameters, if an explicit instantiation
9519 // of a template appears after a declaration of an explicit
9520 // specialization for that template, the explicit instantiation has no
9521 // effect.
9522 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9523 // Is there any previous explicit specialization declaration?
9525 HasNoEffect = true;
9526 break;
9527 }
9528 }
9529
9530 return false;
9531
9533 // C++0x [temp.spec]p5:
9534 // For a given template and a given set of template-arguments,
9535 // - an explicit instantiation definition shall appear at most once
9536 // in a program,
9537
9538 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9539 Diag(NewLoc, (getLangOpts().MSVCCompat)
9540 ? diag::ext_explicit_instantiation_duplicate
9541 : diag::err_explicit_instantiation_duplicate)
9542 << PrevDecl;
9543 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9544 diag::note_previous_explicit_instantiation);
9545 HasNoEffect = true;
9546 return false;
9547 }
9548 }
9549
9550 llvm_unreachable("Missing specialization/instantiation case?");
9551}
9552
9554 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9556 // Remove anything from Previous that isn't a function template in
9557 // the correct context.
9558 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9559 LookupResult::Filter F = Previous.makeFilter();
9560 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9561 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9562 while (F.hasNext()) {
9563 NamedDecl *D = F.next()->getUnderlyingDecl();
9564 if (!isa<FunctionTemplateDecl>(D)) {
9565 F.erase();
9566 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9567 continue;
9568 }
9569
9570 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9572 F.erase();
9573 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9574 continue;
9575 }
9576 }
9577 F.done();
9578
9579 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9580 if (Previous.empty()) {
9581 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9582 << IsFriend;
9583 for (auto &P : DiscardedCandidates)
9584 Diag(P.second->getLocation(),
9585 diag::note_dependent_function_template_spec_discard_reason)
9586 << P.first << IsFriend;
9587 return true;
9588 }
9589
9591 ExplicitTemplateArgs);
9592 return false;
9593}
9594
9596 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9597 LookupResult &Previous, bool QualifiedFriend) {
9598 // The set of function template specializations that could match this
9599 // explicit function template specialization.
9600 UnresolvedSet<8> Candidates;
9601 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9602 /*ForTakingAddress=*/false);
9603
9604 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9605 ConvertedTemplateArgs;
9606
9607 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9608 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9609 I != E; ++I) {
9610 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9611 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9612 // Only consider templates found within the same semantic lookup scope as
9613 // FD.
9614 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9616 continue;
9617
9618 QualType FT = FD->getType();
9619 // C++11 [dcl.constexpr]p8:
9620 // A constexpr specifier for a non-static member function that is not
9621 // a constructor declares that member function to be const.
9622 //
9623 // When matching a constexpr member function template specialization
9624 // against the primary template, we don't yet know whether the
9625 // specialization has an implicit 'const' (because we don't know whether
9626 // it will be a static member function until we know which template it
9627 // specializes). This rule was removed in C++14.
9628 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9629 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9631 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9632 if (OldMD && OldMD->isConst()) {
9633 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9635 EPI.TypeQuals.addConst();
9636 FT = Context.getFunctionType(FPT->getReturnType(),
9637 FPT->getParamTypes(), EPI);
9638 }
9639 }
9640
9642 if (ExplicitTemplateArgs)
9643 Args = *ExplicitTemplateArgs;
9644
9645 // C++ [temp.expl.spec]p11:
9646 // A trailing template-argument can be left unspecified in the
9647 // template-id naming an explicit function template specialization
9648 // provided it can be deduced from the function argument type.
9649 // Perform template argument deduction to determine whether we may be
9650 // specializing this template.
9651 // FIXME: It is somewhat wasteful to build
9652 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9653 FunctionDecl *Specialization = nullptr;
9655 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9656 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9658 // Template argument deduction failed; record why it failed, so
9659 // that we can provide nifty diagnostics.
9660 FailedCandidates.addCandidate().set(
9661 I.getPair(), FunTmpl->getTemplatedDecl(),
9662 MakeDeductionFailureInfo(Context, TDK, Info));
9663 (void)TDK;
9664 continue;
9665 }
9666
9667 // Target attributes are part of the cuda function signature, so
9668 // the deduced template's cuda target must match that of the
9669 // specialization. Given that C++ template deduction does not
9670 // take target attributes into account, we reject candidates
9671 // here that have a different target.
9672 if (LangOpts.CUDA &&
9673 CUDA().IdentifyTarget(Specialization,
9674 /* IgnoreImplicitHDAttr = */ true) !=
9675 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9676 FailedCandidates.addCandidate().set(
9677 I.getPair(), FunTmpl->getTemplatedDecl(),
9680 continue;
9681 }
9682
9683 // Record this candidate.
9684 if (ExplicitTemplateArgs)
9685 ConvertedTemplateArgs[Specialization] = std::move(Args);
9686 Candidates.addDecl(Specialization, I.getAccess());
9687 }
9688 }
9689
9690 // For a qualified friend declaration (with no explicit marker to indicate
9691 // that a template specialization was intended), note all (template and
9692 // non-template) candidates.
9693 if (QualifiedFriend && Candidates.empty()) {
9694 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9695 << FD->getDeclName() << FDLookupContext;
9696 // FIXME: We should form a single candidate list and diagnose all
9697 // candidates at once, to get proper sorting and limiting.
9698 for (auto *OldND : Previous) {
9699 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9700 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9701 }
9702 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9703 return true;
9704 }
9705
9706 // Find the most specialized function template.
9708 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9709 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9710 PDiag(diag::err_function_template_spec_ambiguous)
9711 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9712 PDiag(diag::note_function_template_spec_matched));
9713
9714 if (Result == Candidates.end())
9715 return true;
9716
9717 // Ignore access information; it doesn't figure into redeclaration checking.
9719
9720 if (const auto *PT = Specialization->getPrimaryTemplate();
9721 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9722 auto Message = DSA->getMessage();
9723 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9724 << PT << !Message.empty() << Message;
9725 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9726 }
9727
9728 // C++23 [except.spec]p13:
9729 // An exception specification is considered to be needed when:
9730 // - [...]
9731 // - the exception specification is compared to that of another declaration
9732 // (e.g., an explicit specialization or an overriding virtual function);
9733 // - [...]
9734 //
9735 // The exception specification of a defaulted function is evaluated as
9736 // described above only when needed; similarly, the noexcept-specifier of a
9737 // specialization of a function template or member function of a class
9738 // template is instantiated only when needed.
9739 //
9740 // The standard doesn't specify what the "comparison with another declaration"
9741 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9742 // not state which properties of an explicit specialization must match the
9743 // primary template.
9744 //
9745 // We assume that an explicit specialization must correspond with (per
9746 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9747 // the declaration produced by substitution into the function template.
9748 //
9749 // Since the determination whether two function declarations correspond does
9750 // not consider exception specification, we only need to instantiate it once
9751 // we determine the primary template when comparing types per
9752 // [basic.link]p11.1.
9753 auto *SpecializationFPT =
9754 Specialization->getType()->castAs<FunctionProtoType>();
9755 // If the function has a dependent exception specification, resolve it after
9756 // we have selected the primary template so we can check whether it matches.
9757 if (getLangOpts().CPlusPlus17 &&
9758 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9759 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9760 return true;
9761
9763 = Specialization->getTemplateSpecializationInfo();
9764 assert(SpecInfo && "Function template specialization info missing?");
9765
9766 // Note: do not overwrite location info if previous template
9767 // specialization kind was explicit.
9769 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9770 Specialization->setLocation(FD->getLocation());
9771 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9772 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9773 // function can differ from the template declaration with respect to
9774 // the constexpr specifier.
9775 // FIXME: We need an update record for this AST mutation.
9776 // FIXME: What if there are multiple such prior declarations (for instance,
9777 // from different modules)?
9778 Specialization->setConstexprKind(FD->getConstexprKind());
9779 }
9780
9781 // FIXME: Check if the prior specialization has a point of instantiation.
9782 // If so, we have run afoul of .
9783
9784 // If this is a friend declaration, then we're not really declaring
9785 // an explicit specialization.
9786 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9787
9788 // Check the scope of this explicit specialization.
9789 if (!isFriend &&
9791 Specialization->getPrimaryTemplate(),
9793 false))
9794 return true;
9795
9796 // C++ [temp.expl.spec]p6:
9797 // If a template, a member template or the member of a class template is
9798 // explicitly specialized then that specialization shall be declared
9799 // before the first use of that specialization that would cause an implicit
9800 // instantiation to take place, in every translation unit in which such a
9801 // use occurs; no diagnostic is required.
9802 bool HasNoEffect = false;
9803 if (!isFriend &&
9808 SpecInfo->getPointOfInstantiation(),
9809 HasNoEffect))
9810 return true;
9811
9812 // Mark the prior declaration as an explicit specialization, so that later
9813 // clients know that this is an explicit specialization.
9814 // A dependent friend specialization which has a definition should be treated
9815 // as explicit specialization, despite being invalid.
9816 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9817 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9818 // Since explicit specializations do not inherit '=delete' from their
9819 // primary function template - check if the 'specialization' that was
9820 // implicitly generated (during template argument deduction for partial
9821 // ordering) from the most specialized of all the function templates that
9822 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9823 // first check that it was implicitly generated during template argument
9824 // deduction by making sure it wasn't referenced, and then reset the deleted
9825 // flag to not-deleted, so that we can inherit that information from 'FD'.
9826 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9827 !Specialization->getCanonicalDecl()->isReferenced()) {
9828 // FIXME: This assert will not hold in the presence of modules.
9829 assert(
9830 Specialization->getCanonicalDecl() == Specialization &&
9831 "This must be the only existing declaration of this specialization");
9832 // FIXME: We need an update record for this AST mutation.
9833 Specialization->setDeletedAsWritten(false);
9834 }
9835 // FIXME: We need an update record for this AST mutation.
9838 }
9839
9840 // Turn the given function declaration into a function template
9841 // specialization, with the template arguments from the previous
9842 // specialization.
9843 // Take copies of (semantic and syntactic) template argument lists.
9845 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9846 FD->setFunctionTemplateSpecialization(
9847 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9849 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9850
9851 // A function template specialization inherits the target attributes
9852 // of its template. (We require the attributes explicitly in the
9853 // code to match, but a template may have implicit attributes by
9854 // virtue e.g. of being constexpr, and it passes these implicit
9855 // attributes on to its specializations.)
9856 if (LangOpts.CUDA)
9857 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9858
9859 // The "previous declaration" for this function template specialization is
9860 // the prior function template specialization.
9861 Previous.clear();
9862 Previous.addDecl(Specialization);
9863 return false;
9864}
9865
9866bool
9868 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9869 "Only for non-template members");
9870
9871 // Try to find the member we are instantiating.
9872 NamedDecl *FoundInstantiation = nullptr;
9873 NamedDecl *Instantiation = nullptr;
9874 NamedDecl *InstantiatedFrom = nullptr;
9875 MemberSpecializationInfo *MSInfo = nullptr;
9876
9877 if (Previous.empty()) {
9878 // Nowhere to look anyway.
9879 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9880 UnresolvedSet<8> Candidates;
9881 for (NamedDecl *Candidate : Previous) {
9882 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9883 // Ignore any candidates that aren't member functions.
9884 if (!Method)
9885 continue;
9886
9887 QualType Adjusted = Function->getType();
9888 if (!hasExplicitCallingConv(Adjusted))
9889 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9890 // Ignore any candidates with the wrong type.
9891 // This doesn't handle deduced return types, but both function
9892 // declarations should be undeduced at this point.
9893 // FIXME: The exception specification should probably be ignored when
9894 // comparing the types.
9895 if (!Context.hasSameType(Adjusted, Method->getType()))
9896 continue;
9897
9898 // Ignore any candidates with unsatisfied constraints.
9899 if (ConstraintSatisfaction Satisfaction;
9900 Method->getTrailingRequiresClause() &&
9901 (CheckFunctionConstraints(Method, Satisfaction,
9902 /*UsageLoc=*/Member->getLocation(),
9903 /*ForOverloadResolution=*/true) ||
9904 !Satisfaction.IsSatisfied))
9905 continue;
9906
9907 Candidates.addDecl(Candidate);
9908 }
9909
9910 // If we have no viable candidates left after filtering, we are done.
9911 if (Candidates.empty())
9912 return false;
9913
9914 // Find the function that is more constrained than every other function it
9915 // has been compared to.
9916 UnresolvedSetIterator Best = Candidates.begin();
9917 CXXMethodDecl *BestMethod = nullptr;
9918 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9919 I != E; ++I) {
9920 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9921 if (I == Best ||
9922 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9923 Best = I;
9924 BestMethod = Method;
9925 }
9926 }
9927
9928 FoundInstantiation = *Best;
9929 Instantiation = BestMethod;
9930 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9931 MSInfo = BestMethod->getMemberSpecializationInfo();
9932
9933 // Make sure the best candidate is more constrained than all of the others.
9934 bool Ambiguous = false;
9935 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9936 I != E; ++I) {
9937 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9938 if (I != Best &&
9939 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9940 Ambiguous = true;
9941 break;
9942 }
9943 }
9944
9945 if (Ambiguous) {
9946 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9947 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9948 for (NamedDecl *Candidate : Candidates) {
9949 Candidate = Candidate->getUnderlyingDecl();
9950 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9951 << Candidate;
9952 }
9953 return true;
9954 }
9955 } else if (isa<VarDecl>(Member)) {
9956 VarDecl *PrevVar;
9957 if (Previous.isSingleResult() &&
9958 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9959 if (PrevVar->isStaticDataMember()) {
9960 FoundInstantiation = Previous.getRepresentativeDecl();
9961 Instantiation = PrevVar;
9962 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9963 MSInfo = PrevVar->getMemberSpecializationInfo();
9964 }
9965 } else if (isa<RecordDecl>(Member)) {
9966 CXXRecordDecl *PrevRecord;
9967 if (Previous.isSingleResult() &&
9968 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9969 FoundInstantiation = Previous.getRepresentativeDecl();
9970 Instantiation = PrevRecord;
9971 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9972 MSInfo = PrevRecord->getMemberSpecializationInfo();
9973 }
9974 } else if (isa<EnumDecl>(Member)) {
9975 EnumDecl *PrevEnum;
9976 if (Previous.isSingleResult() &&
9977 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9978 FoundInstantiation = Previous.getRepresentativeDecl();
9979 Instantiation = PrevEnum;
9980 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9981 MSInfo = PrevEnum->getMemberSpecializationInfo();
9982 }
9983 }
9984
9985 if (!Instantiation) {
9986 // There is no previous declaration that matches. Since member
9987 // specializations are always out-of-line, the caller will complain about
9988 // this mismatch later.
9989 return false;
9990 }
9991
9992 // A member specialization in a friend declaration isn't really declaring
9993 // an explicit specialization, just identifying a specific (possibly implicit)
9994 // specialization. Don't change the template specialization kind.
9995 //
9996 // FIXME: Is this really valid? Other compilers reject.
9997 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9998 // Preserve instantiation information.
9999 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10000 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10001 cast<CXXMethodDecl>(InstantiatedFrom),
10003 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10004 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10005 cast<CXXRecordDecl>(InstantiatedFrom),
10007 }
10008
10009 Previous.clear();
10010 Previous.addDecl(FoundInstantiation);
10011 return false;
10012 }
10013
10014 // Make sure that this is a specialization of a member.
10015 if (!InstantiatedFrom) {
10016 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10017 << Member;
10018 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10019 return true;
10020 }
10021
10022 // C++ [temp.expl.spec]p6:
10023 // If a template, a member template or the member of a class template is
10024 // explicitly specialized then that specialization shall be declared
10025 // before the first use of that specialization that would cause an implicit
10026 // instantiation to take place, in every translation unit in which such a
10027 // use occurs; no diagnostic is required.
10028 assert(MSInfo && "Member specialization info missing?");
10029
10030 bool HasNoEffect = false;
10033 Instantiation,
10035 MSInfo->getPointOfInstantiation(),
10036 HasNoEffect))
10037 return true;
10038
10039 // Check the scope of this explicit specialization.
10041 InstantiatedFrom,
10042 Instantiation, Member->getLocation(),
10043 false))
10044 return true;
10045
10046 // Note that this member specialization is an "instantiation of" the
10047 // corresponding member of the original template.
10048 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10049 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10050 if (InstantiationFunction->getTemplateSpecializationKind() ==
10052 // Explicit specializations of member functions of class templates do not
10053 // inherit '=delete' from the member function they are specializing.
10054 if (InstantiationFunction->isDeleted()) {
10055 // FIXME: This assert will not hold in the presence of modules.
10056 assert(InstantiationFunction->getCanonicalDecl() ==
10057 InstantiationFunction);
10058 // FIXME: We need an update record for this AST mutation.
10059 InstantiationFunction->setDeletedAsWritten(false);
10060 }
10061 }
10062
10063 MemberFunction->setInstantiationOfMemberFunction(
10065 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10066 MemberVar->setInstantiationOfStaticDataMember(
10067 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10068 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10069 MemberClass->setInstantiationOfMemberClass(
10071 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10072 MemberEnum->setInstantiationOfMemberEnum(
10073 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10074 } else {
10075 llvm_unreachable("unknown member specialization kind");
10076 }
10077
10078 // Save the caller the trouble of having to figure out which declaration
10079 // this specialization matches.
10080 Previous.clear();
10081 Previous.addDecl(FoundInstantiation);
10082 return false;
10083}
10084
10085/// Complete the explicit specialization of a member of a class template by
10086/// updating the instantiated member to be marked as an explicit specialization.
10087///
10088/// \param OrigD The member declaration instantiated from the template.
10089/// \param Loc The location of the explicit specialization of the member.
10090template<typename DeclT>
10091static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10092 SourceLocation Loc) {
10093 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10094 return;
10095
10096 // FIXME: Inform AST mutation listeners of this AST mutation.
10097 // FIXME: If there are multiple in-class declarations of the member (from
10098 // multiple modules, or a declaration and later definition of a member type),
10099 // should we update all of them?
10100 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10101 OrigD->setLocation(Loc);
10102}
10103
10106 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10107 if (Instantiation == Member)
10108 return;
10109
10110 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10111 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10112 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10113 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10114 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10115 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10116 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10117 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10118 else
10119 llvm_unreachable("unknown member specialization kind");
10120}
10121
10122/// Check the scope of an explicit instantiation.
10123///
10124/// \returns true if a serious error occurs, false otherwise.
10126 SourceLocation InstLoc,
10127 bool WasQualifiedName) {
10129 DeclContext *CurContext = S.CurContext->getRedeclContext();
10130
10131 if (CurContext->isRecord()) {
10132 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10133 << D;
10134 return true;
10135 }
10136
10137 // C++11 [temp.explicit]p3:
10138 // An explicit instantiation shall appear in an enclosing namespace of its
10139 // template. If the name declared in the explicit instantiation is an
10140 // unqualified name, the explicit instantiation shall appear in the
10141 // namespace where its template is declared or, if that namespace is inline
10142 // (7.3.1), any namespace from its enclosing namespace set.
10143 //
10144 // This is DR275, which we do not retroactively apply to C++98/03.
10145 if (WasQualifiedName) {
10146 if (CurContext->Encloses(OrigContext))
10147 return false;
10148 } else {
10149 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10150 return false;
10151 }
10152
10153 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10154 if (WasQualifiedName)
10155 S.Diag(InstLoc,
10156 S.getLangOpts().CPlusPlus11?
10157 diag::err_explicit_instantiation_out_of_scope :
10158 diag::warn_explicit_instantiation_out_of_scope_0x)
10159 << D << NS;
10160 else
10161 S.Diag(InstLoc,
10162 S.getLangOpts().CPlusPlus11?
10163 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10164 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10165 << D << NS;
10166 } else
10167 S.Diag(InstLoc,
10168 S.getLangOpts().CPlusPlus11?
10169 diag::err_explicit_instantiation_must_be_global :
10170 diag::warn_explicit_instantiation_must_be_global_0x)
10171 << D;
10172 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10173 return false;
10174}
10175
10176/// Common checks for whether an explicit instantiation of \p D is valid.
10178 SourceLocation InstLoc,
10179 bool WasQualifiedName,
10181 // C++ [temp.explicit]p13:
10182 // An explicit instantiation declaration shall not name a specialization of
10183 // a template with internal linkage.
10186 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10187 return true;
10188 }
10189
10190 // C++11 [temp.explicit]p3: [DR 275]
10191 // An explicit instantiation shall appear in an enclosing namespace of its
10192 // template.
10193 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10194 return true;
10195
10196 return false;
10197}
10198
10199/// Determine whether the given scope specifier has a template-id in it.
10201 // C++11 [temp.explicit]p3:
10202 // If the explicit instantiation is for a member function, a member class
10203 // or a static data member of a class template specialization, the name of
10204 // the class template specialization in the qualified-id for the member
10205 // name shall be a simple-template-id.
10206 //
10207 // C++98 has the same restriction, just worded differently.
10208 for (NestedNameSpecifier NNS = SS.getScopeRep();
10210 /**/) {
10211 const Type *T = NNS.getAsType();
10213 return true;
10214 NNS = T->getPrefix();
10215 }
10216 return false;
10217}
10218
10219/// Make a dllexport or dllimport attr on a class template specialization take
10220/// effect.
10223 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10224 assert(A && "dllExportImportClassTemplateSpecialization called "
10225 "on Def without dllexport or dllimport");
10226
10227 // We reject explicit instantiations in class scope, so there should
10228 // never be any delayed exported classes to worry about.
10229 assert(S.DelayedDllExportClasses.empty() &&
10230 "delayed exports present at explicit instantiation");
10232
10233 // Propagate attribute to base class templates.
10234 for (auto &B : Def->bases()) {
10235 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10236 B.getType()->getAsCXXRecordDecl()))
10238 }
10239
10241}
10242
10244 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10245 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10246 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10247 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10248 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10249 // Find the class template we're specializing
10250 TemplateName Name = TemplateD.get();
10251 TemplateDecl *TD = Name.getAsTemplateDecl();
10252 // Check that the specialization uses the same tag kind as the
10253 // original template.
10255 assert(Kind != TagTypeKind::Enum &&
10256 "Invalid enum tag in class template explicit instantiation!");
10257
10258 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10259
10260 if (!ClassTemplate) {
10261 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10262 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10263 Diag(TD->getLocation(), diag::note_previous_use);
10264 return true;
10265 }
10266
10267 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10268 Kind, /*isDefinition*/false, KWLoc,
10269 ClassTemplate->getIdentifier())) {
10270 Diag(KWLoc, diag::err_use_with_wrong_tag)
10271 << ClassTemplate
10273 ClassTemplate->getTemplatedDecl()->getKindName());
10274 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10275 diag::note_previous_use);
10276 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10277 }
10278
10279 // C++0x [temp.explicit]p2:
10280 // There are two forms of explicit instantiation: an explicit instantiation
10281 // definition and an explicit instantiation declaration. An explicit
10282 // instantiation declaration begins with the extern keyword. [...]
10283 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10286
10288 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10289 // Check for dllexport class template instantiation declarations,
10290 // except for MinGW mode.
10291 for (const ParsedAttr &AL : Attr) {
10292 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10293 Diag(ExternLoc,
10294 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10295 Diag(AL.getLoc(), diag::note_attribute);
10296 break;
10297 }
10298 }
10299
10300 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10301 Diag(ExternLoc,
10302 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10303 Diag(A->getLocation(), diag::note_attribute);
10304 }
10305 }
10306
10307 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10308 // instantiation declarations for most purposes.
10309 bool DLLImportExplicitInstantiationDef = false;
10311 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10312 // Check for dllimport class template instantiation definitions.
10313 bool DLLImport =
10314 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10315 for (const ParsedAttr &AL : Attr) {
10316 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10317 DLLImport = true;
10318 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10319 // dllexport trumps dllimport here.
10320 DLLImport = false;
10321 break;
10322 }
10323 }
10324 if (DLLImport) {
10326 DLLImportExplicitInstantiationDef = true;
10327 }
10328 }
10329
10330 // Translate the parser's template argument list in our AST format.
10331 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10332 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10333
10334 // Check that the template argument list is well-formed for this
10335 // template.
10337 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10338 /*DefaultArgs=*/{}, false, CTAI,
10339 /*UpdateArgsWithConversions=*/true,
10340 /*ConstraintsNotSatisfied=*/nullptr))
10341 return true;
10342
10343 // Find the class template specialization declaration that
10344 // corresponds to these arguments.
10345 void *InsertPos = nullptr;
10347 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10348
10349 TemplateSpecializationKind PrevDecl_TSK
10350 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10351
10352 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10353 Context.getTargetInfo().getTriple().isOSCygMing()) {
10354 // Check for dllexport class template instantiation definitions in MinGW
10355 // mode, if a previous declaration of the instantiation was seen.
10356 for (const ParsedAttr &AL : Attr) {
10357 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10358 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10359 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10360 } else {
10361 Diag(AL.getLoc(),
10362 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10363 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10364 }
10365 break;
10366 }
10367 }
10368 }
10369
10370 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10371 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10372 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10373 return AL.getKind() == ParsedAttr::AT_DLLExport;
10374 })) {
10375 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10376 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10377 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10378 }
10379 }
10380
10381 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10382 SS.isSet(), TSK))
10383 return true;
10384
10386
10387 bool HasNoEffect = false;
10388 if (PrevDecl) {
10389 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10390 PrevDecl, PrevDecl_TSK,
10391 PrevDecl->getPointOfInstantiation(),
10392 HasNoEffect))
10393 return PrevDecl;
10394
10395 // Even though HasNoEffect == true means that this explicit instantiation
10396 // has no effect on semantics, we go on to put its syntax in the AST.
10397
10398 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10399 PrevDecl_TSK == TSK_Undeclared) {
10400 // Since the only prior class template specialization with these
10401 // arguments was referenced but not declared, reuse that
10402 // declaration node as our own, updating the source location
10403 // for the template name to reflect our new declaration.
10404 // (Other source locations will be updated later.)
10405 Specialization = PrevDecl;
10406 Specialization->setLocation(TemplateNameLoc);
10407 PrevDecl = nullptr;
10408 }
10409
10410 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10411 DLLImportExplicitInstantiationDef) {
10412 // The new specialization might add a dllimport attribute.
10413 HasNoEffect = false;
10414 }
10415 }
10416
10417 if (!Specialization) {
10418 // Create a new class template specialization declaration node for
10419 // this explicit specialization.
10421 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10422 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10424
10425 // A MSInheritanceAttr attached to the previous declaration must be
10426 // propagated to the new node prior to instantiation.
10427 if (PrevDecl) {
10428 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10429 auto *Clone = A->clone(getASTContext());
10430 Clone->setInherited(true);
10431 Specialization->addAttr(Clone);
10432 Consumer.AssignInheritanceModel(Specialization);
10433 }
10434 }
10435
10436 if (!HasNoEffect && !PrevDecl) {
10437 // Insert the new specialization.
10438 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10439 }
10440 }
10441
10442 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10443
10444 // Set source locations for keywords.
10445 Specialization->setExternKeywordLoc(ExternLoc);
10446 Specialization->setTemplateKeywordLoc(TemplateLoc);
10447 Specialization->setBraceRange(SourceRange());
10448
10449 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10452
10453 // Add the explicit instantiation into its lexical context. However,
10454 // since explicit instantiations are never found by name lookup, we
10455 // just put it into the declaration context directly.
10456 Specialization->setLexicalDeclContext(CurContext);
10457 CurContext->addDecl(Specialization);
10458
10459 // Syntax is now OK, so return if it has no other effect on semantics.
10460 if (HasNoEffect) {
10461 // Set the template specialization kind.
10462 Specialization->setTemplateSpecializationKind(TSK);
10463
10465 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10466 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10467 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10468 Context.getCanonicalTagType(Specialization));
10470 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10471 TemplateNameLoc, TSI, TSK);
10472 return Specialization;
10473 }
10474
10475 // C++ [temp.explicit]p3:
10476 // A definition of a class template or class member template
10477 // shall be in scope at the point of the explicit instantiation of
10478 // the class template or class member template.
10479 //
10480 // This check comes when we actually try to perform the
10481 // instantiation.
10483 = cast_or_null<ClassTemplateSpecializationDecl>(
10484 Specialization->getDefinition());
10485 if (!Def)
10487 /*Complain=*/true,
10488 CTAI.StrictPackMatch);
10489 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10490 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10491 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10492 }
10493
10494 // Instantiate the members of this class template specialization.
10495 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10496 Specialization->getDefinition());
10497 if (Def) {
10499 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10500 // TSK_ExplicitInstantiationDefinition
10501 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10503 DLLImportExplicitInstantiationDef)) {
10504 // FIXME: Need to notify the ASTMutationListener that we did this.
10506
10507 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10508 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10509 // An explicit instantiation definition can add a dll attribute to a
10510 // template with a previous instantiation declaration. MinGW doesn't
10511 // allow this.
10512 auto *A = cast<InheritableAttr>(
10514 A->setInherited(true);
10515 Def->addAttr(A);
10517 }
10518 }
10519
10520 // Fix a TSK_ImplicitInstantiation followed by a
10521 // TSK_ExplicitInstantiationDefinition
10522 bool NewlyDLLExported =
10523 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10524 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10525 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10526 // An explicit instantiation definition can add a dll attribute to a
10527 // template with a previous implicit instantiation. MinGW doesn't allow
10528 // this. We limit clang to only adding dllexport, to avoid potentially
10529 // strange codegen behavior. For example, if we extend this conditional
10530 // to dllimport, and we have a source file calling a method on an
10531 // implicitly instantiated template class instance and then declaring a
10532 // dllimport explicit instantiation definition for the same template
10533 // class, the codegen for the method call will not respect the dllimport,
10534 // while it will with cl. The Def will already have the DLL attribute,
10535 // since the Def and Specialization will be the same in the case of
10536 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10537 // attribute to the Specialization; we just need to make it take effect.
10538 assert(Def == Specialization &&
10539 "Def and Specialization should match for implicit instantiation");
10541 }
10542
10543 // In MinGW mode, export the template instantiation if the declaration
10544 // was marked dllexport.
10545 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10546 Context.getTargetInfo().getTriple().isOSCygMing() &&
10547 PrevDecl->hasAttr<DLLExportAttr>()) {
10549 }
10550
10551 // Set the template specialization kind. Make sure it is set before
10552 // instantiating the members which will trigger ASTConsumer callbacks.
10553 Specialization->setTemplateSpecializationKind(TSK);
10554 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10555 } else {
10556
10557 // Set the template specialization kind.
10558 Specialization->setTemplateSpecializationKind(TSK);
10559 }
10560
10562 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10563 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10564 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10565 Context.getCanonicalTagType(Specialization));
10567 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10568 TemplateNameLoc, TSI, TSK);
10569 return Specialization;
10570}
10571
10574 SourceLocation TemplateLoc, unsigned TagSpec,
10575 SourceLocation KWLoc, CXXScopeSpec &SS,
10576 IdentifierInfo *Name, SourceLocation NameLoc,
10577 const ParsedAttributesView &Attr) {
10578
10579 bool Owned = false;
10580 bool IsDependent = false;
10581 Decl *TagD =
10582 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10583 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10584 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10585 false, TypeResult(), /*IsTypeSpecifier*/ false,
10586 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10587 .get();
10588 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10589
10590 if (!TagD)
10591 return true;
10592
10593 TagDecl *Tag = cast<TagDecl>(TagD);
10594 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10595
10596 if (Tag->isInvalidDecl())
10597 return true;
10598
10600 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10601 if (!Pattern) {
10602 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10603 << Context.getCanonicalTagType(Record);
10604 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10605 return true;
10606 }
10607
10608 // C++0x [temp.explicit]p2:
10609 // If the explicit instantiation is for a class or member class, the
10610 // elaborated-type-specifier in the declaration shall include a
10611 // simple-template-id.
10612 //
10613 // C++98 has the same restriction, just worded differently.
10615 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10616 << Record << SS.getRange();
10617
10618 // C++0x [temp.explicit]p2:
10619 // There are two forms of explicit instantiation: an explicit instantiation
10620 // definition and an explicit instantiation declaration. An explicit
10621 // instantiation declaration begins with the extern keyword. [...]
10625
10626 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10627
10628 // Verify that it is okay to explicitly instantiate here.
10629 CXXRecordDecl *PrevDecl
10630 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10631 if (!PrevDecl && Record->getDefinition())
10632 PrevDecl = Record;
10633 if (PrevDecl) {
10635 bool HasNoEffect = false;
10636 assert(MSInfo && "No member specialization information?");
10637 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10638 PrevDecl,
10640 MSInfo->getPointOfInstantiation(),
10641 HasNoEffect))
10642 return true;
10643 if (HasNoEffect) {
10647 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10648 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10649 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10650 TL.setElaboratedKeywordLoc(KWLoc);
10651 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10652 TL.setNameLoc(NameLoc);
10654 TemplateLoc, NestedNameSpecifierLoc(),
10655 nullptr, NameLoc, TSI, TSK);
10656 return TagD;
10657 }
10658 }
10659
10660 CXXRecordDecl *RecordDef
10661 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10662 if (!RecordDef) {
10663 // C++ [temp.explicit]p3:
10664 // A definition of a member class of a class template shall be in scope
10665 // at the point of an explicit instantiation of the member class.
10666 CXXRecordDecl *Def
10667 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10668 if (!Def) {
10669 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10670 << 0 << Record->getDeclName() << Record->getDeclContext();
10671 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10672 << Pattern;
10673 return true;
10674 } else {
10675 if (InstantiateClass(NameLoc, Record, Def,
10677 TSK))
10678 return true;
10679
10680 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10681 if (!RecordDef)
10682 return true;
10683 }
10684 }
10685
10686 // Instantiate all of the members of the class.
10687 InstantiateClassMembers(NameLoc, RecordDef,
10689
10691 MarkVTableUsed(NameLoc, RecordDef, true);
10692
10695 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10696 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10697 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10698 TL.setElaboratedKeywordLoc(KWLoc);
10699 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10700 TL.setNameLoc(NameLoc);
10702 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10703 NameLoc, TSI, TSK);
10704 return TagD;
10705}
10706
10708 SourceLocation ExternLoc,
10709 SourceLocation TemplateLoc,
10710 Declarator &D) {
10711 // Explicit instantiations always require a name.
10712 // TODO: check if/when DNInfo should replace Name.
10714 DeclarationName Name = NameInfo.getName();
10715 if (!Name) {
10716 if (!D.isInvalidType())
10718 diag::err_explicit_instantiation_requires_name)
10720
10721 return true;
10722 }
10723
10724 // Get the innermost enclosing declaration scope.
10725 S = S->getDeclParent();
10726
10727 // Determine the type of the declaration.
10729 QualType R = T->getType();
10730 if (R.isNull())
10731 return true;
10732
10733 // C++ [dcl.stc]p1:
10734 // A storage-class-specifier shall not be specified in [...] an explicit
10735 // instantiation (14.7.2) directive.
10737 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10738 << Name;
10739 return true;
10740 } else if (D.getDeclSpec().getStorageClassSpec()
10742 // Complain about then remove the storage class specifier.
10743 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10745
10747 }
10748
10749 // C++0x [temp.explicit]p1:
10750 // [...] An explicit instantiation of a function template shall not use the
10751 // inline or constexpr specifiers.
10752 // Presumably, this also applies to member functions of class templates as
10753 // well.
10757 diag::err_explicit_instantiation_inline :
10758 diag::warn_explicit_instantiation_inline_0x)
10760 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10761 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10762 // not already specified.
10764 diag::err_explicit_instantiation_constexpr);
10765
10766 // A deduction guide is not on the list of entities that can be explicitly
10767 // instantiated.
10769 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10770 << /*explicit instantiation*/ 0;
10771 return true;
10772 }
10773
10774 // C++0x [temp.explicit]p2:
10775 // There are two forms of explicit instantiation: an explicit instantiation
10776 // definition and an explicit instantiation declaration. An explicit
10777 // instantiation declaration begins with the extern keyword. [...]
10781
10782 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10784 /*ObjectType=*/QualType());
10785
10786 if (!R->isFunctionType()) {
10787 // C++ [temp.explicit]p1:
10788 // A [...] static data member of a class template can be explicitly
10789 // instantiated from the member definition associated with its class
10790 // template.
10791 // C++1y [temp.explicit]p1:
10792 // A [...] variable [...] template specialization can be explicitly
10793 // instantiated from its template.
10794 if (Previous.isAmbiguous())
10795 return true;
10796
10797 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10798 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10799 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10800
10801 if (!PrevTemplate) {
10802 if (!Prev || !Prev->isStaticDataMember()) {
10803 // We expect to see a static data member here.
10804 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10805 << Name;
10806 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10807 P != PEnd; ++P)
10808 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10809 return true;
10810 }
10811
10813 // FIXME: Check for explicit specialization?
10815 diag::err_explicit_instantiation_data_member_not_instantiated)
10816 << Prev;
10817 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10818 // FIXME: Can we provide a note showing where this was declared?
10819 return true;
10820 }
10821 } else {
10822 // Explicitly instantiate a variable template.
10823
10824 // C++1y [dcl.spec.auto]p6:
10825 // ... A program that uses auto or decltype(auto) in a context not
10826 // explicitly allowed in this section is ill-formed.
10827 //
10828 // This includes auto-typed variable template instantiations.
10829 if (R->isUndeducedType()) {
10830 Diag(T->getTypeLoc().getBeginLoc(),
10831 diag::err_auto_not_allowed_var_inst);
10832 return true;
10833 }
10834
10836 // C++1y [temp.explicit]p3:
10837 // If the explicit instantiation is for a variable, the unqualified-id
10838 // in the declaration shall be a template-id.
10840 diag::err_explicit_instantiation_without_template_id)
10841 << PrevTemplate;
10842 Diag(PrevTemplate->getLocation(),
10843 diag::note_explicit_instantiation_here);
10844 return true;
10845 }
10846
10847 // Translate the parser's template argument list into our AST format.
10848 TemplateArgumentListInfo TemplateArgs =
10850
10851 DeclResult Res =
10852 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10853 TemplateArgs, /*SetWrittenArgs=*/true);
10854 if (Res.isInvalid())
10855 return true;
10856
10857 if (!Res.isUsable()) {
10858 // We somehow specified dependent template arguments in an explicit
10859 // instantiation. This should probably only happen during error
10860 // recovery.
10861 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10862 return true;
10863 }
10864
10865 // Ignore access control bits, we don't need them for redeclaration
10866 // checking.
10867 Prev = cast<VarDecl>(Res.get());
10868 ArgsAsWritten =
10870 }
10871
10872 // C++0x [temp.explicit]p2:
10873 // If the explicit instantiation is for a member function, a member class
10874 // or a static data member of a class template specialization, the name of
10875 // the class template specialization in the qualified-id for the member
10876 // name shall be a simple-template-id.
10877 //
10878 // C++98 has the same restriction, just worded differently.
10879 //
10880 // This does not apply to variable template specializations, where the
10881 // template-id is in the unqualified-id instead.
10882 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10884 diag::ext_explicit_instantiation_without_qualified_id)
10885 << Prev << D.getCXXScopeSpec().getRange();
10886
10887 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10888
10889 // Verify that it is okay to explicitly instantiate here.
10892 bool HasNoEffect = false;
10894 PrevTSK, POI, HasNoEffect))
10895 return true;
10896
10897 if (!HasNoEffect) {
10898 // Instantiate static data member or variable template.
10900 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10901 VTSD->setExternKeywordLoc(ExternLoc);
10902 VTSD->setTemplateKeywordLoc(TemplateLoc);
10903 }
10904
10905 // Merge attributes.
10907 if (PrevTemplate)
10908 ProcessAPINotes(Prev);
10909
10912 }
10913
10914 // Check the new variable specialization against the parsed input.
10915 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10916 Diag(T->getTypeLoc().getBeginLoc(),
10917 diag::err_invalid_var_template_spec_type)
10918 << 0 << PrevTemplate << R << Prev->getType();
10919 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10920 << 2 << PrevTemplate->getDeclName();
10921 return true;
10922 }
10923
10925 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10926 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10927 D.getIdentifierLoc(), T, TSK);
10928 return (Decl *)nullptr;
10929 }
10930
10931 // If the declarator is a template-id, translate the parser's template
10932 // argument list into our AST format.
10933 bool HasExplicitTemplateArgs = false;
10934 TemplateArgumentListInfo TemplateArgs;
10936 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10937 HasExplicitTemplateArgs = true;
10938 }
10939
10940 // C++ [temp.explicit]p1:
10941 // A [...] function [...] can be explicitly instantiated from its template.
10942 // A member function [...] of a class template can be explicitly
10943 // instantiated from the member definition associated with its class
10944 // template.
10945 UnresolvedSet<8> TemplateMatches;
10946 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10948 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10949 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10950 P != PEnd; ++P) {
10951 NamedDecl *Prev = *P;
10952 if (!HasExplicitTemplateArgs) {
10953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10954 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10955 /*AdjustExceptionSpec*/true);
10956 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10957 if (Method->getPrimaryTemplate()) {
10958 TemplateMatches.addDecl(Method, P.getAccess());
10959 } else {
10960 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10961 C.FoundDecl = P.getPair();
10962 C.Function = Method;
10963 C.Viable = true;
10965 if (Method->getTrailingRequiresClause() &&
10967 /*ForOverloadResolution=*/true) ||
10968 !S.IsSatisfied)) {
10969 C.Viable = false;
10971 }
10972 }
10973 }
10974 }
10975 }
10976
10977 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10978 if (!FunTmpl)
10979 continue;
10980
10981 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10982 FunctionDecl *Specialization = nullptr;
10984 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10985 Specialization, Info);
10987 // Keep track of almost-matches.
10988 FailedTemplateCandidates.addCandidate().set(
10989 P.getPair(), FunTmpl->getTemplatedDecl(),
10990 MakeDeductionFailureInfo(Context, TDK, Info));
10991 (void)TDK;
10992 continue;
10993 }
10994
10995 // Target attributes are part of the cuda function signature, so
10996 // the cuda target of the instantiated function must match that of its
10997 // template. Given that C++ template deduction does not take
10998 // target attributes into account, we reject candidates here that
10999 // have a different target.
11000 if (LangOpts.CUDA &&
11001 CUDA().IdentifyTarget(Specialization,
11002 /* IgnoreImplicitHDAttr = */ true) !=
11003 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11004 FailedTemplateCandidates.addCandidate().set(
11005 P.getPair(), FunTmpl->getTemplatedDecl(),
11008 continue;
11009 }
11010
11011 TemplateMatches.addDecl(Specialization, P.getAccess());
11012 }
11013
11014 FunctionDecl *Specialization = nullptr;
11015 if (!NonTemplateMatches.empty()) {
11016 unsigned Msg = 0;
11017 OverloadCandidateDisplayKind DisplayKind;
11019 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11020 Best)) {
11021 case OR_Success:
11022 case OR_Deleted:
11023 Specialization = cast<FunctionDecl>(Best->Function);
11024 break;
11025 case OR_Ambiguous:
11026 Msg = diag::err_explicit_instantiation_ambiguous;
11027 DisplayKind = OCD_AmbiguousCandidates;
11028 break;
11030 Msg = diag::err_explicit_instantiation_no_candidate;
11031 DisplayKind = OCD_AllCandidates;
11032 break;
11033 }
11034 if (Msg) {
11035 PartialDiagnostic Diag = PDiag(Msg) << Name;
11036 NonTemplateMatches.NoteCandidates(
11037 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11038 {});
11039 return true;
11040 }
11041 }
11042
11043 if (!Specialization) {
11044 // Find the most specialized function template specialization.
11046 TemplateMatches.begin(), TemplateMatches.end(),
11047 FailedTemplateCandidates, D.getIdentifierLoc(),
11048 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11049 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11050 PDiag(diag::note_explicit_instantiation_candidate));
11051
11052 if (Result == TemplateMatches.end())
11053 return true;
11054
11055 // Ignore access control bits, we don't need them for redeclaration checking.
11057 }
11058
11059 // C++11 [except.spec]p4
11060 // In an explicit instantiation an exception-specification may be specified,
11061 // but is not required.
11062 // If an exception-specification is specified in an explicit instantiation
11063 // directive, it shall be compatible with the exception-specifications of
11064 // other declarations of that function.
11065 if (auto *FPT = R->getAs<FunctionProtoType>())
11066 if (FPT->hasExceptionSpec()) {
11067 unsigned DiagID =
11068 diag::err_mismatched_exception_spec_explicit_instantiation;
11069 if (getLangOpts().MicrosoftExt)
11070 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11072 PDiag(DiagID) << Specialization->getType(),
11073 PDiag(diag::note_explicit_instantiation_here),
11074 Specialization->getType()->getAs<FunctionProtoType>(),
11075 Specialization->getLocation(), FPT, D.getBeginLoc());
11076 // In Microsoft mode, mismatching exception specifications just cause a
11077 // warning.
11078 if (!getLangOpts().MicrosoftExt && Result)
11079 return true;
11080 }
11081
11082 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11084 diag::err_explicit_instantiation_member_function_not_instantiated)
11086 << (Specialization->getTemplateSpecializationKind() ==
11088 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11089 return true;
11090 }
11091
11092 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11093 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11094 PrevDecl = Specialization;
11095
11096 if (PrevDecl) {
11097 bool HasNoEffect = false;
11099 PrevDecl,
11101 PrevDecl->getPointOfInstantiation(),
11102 HasNoEffect))
11103 return true;
11104
11105 if (HasNoEffect) {
11106 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11107 if (HasExplicitTemplateArgs)
11108 ArgsAsWritten =
11111 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11112 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11113 D.getIdentifierLoc(), T, TSK);
11114 return (Decl *)nullptr;
11115 }
11116 }
11117
11118 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11119 // functions
11120 // valarray<size_t>::valarray(size_t) and
11121 // valarray<size_t>::~valarray()
11122 // that it declared to have internal linkage with the internal_linkage
11123 // attribute. Ignore the explicit instantiation declaration in this case.
11124 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11126 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11127 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11128 RD->isInStdNamespace())
11129 return (Decl*) nullptr;
11130 }
11131
11134
11135 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11136 // instantiation declarations.
11138 Specialization->hasAttr<DLLImportAttr>() &&
11139 Context.getTargetInfo().getCXXABI().isMicrosoft())
11141
11142 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11143 if (Specialization->isDefined()) {
11144 // Let the ASTConsumer know that this function has been explicitly
11145 // instantiated now, and its linkage might have changed.
11146 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11147 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11148 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11149 // be explicitly instantiated.
11150 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11151 RD && RD->isLambda()) {
11152 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11153 << /*instantiation*/ 1;
11154 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11155 return (Decl *)nullptr;
11156 }
11158 }
11159
11160 // C++0x [temp.explicit]p2:
11161 // If the explicit instantiation is for a member function, a member class
11162 // or a static data member of a class template specialization, the name of
11163 // the class template specialization in the qualified-id for the member
11164 // name shall be a simple-template-id.
11165 //
11166 // C++98 has the same restriction, just worded differently.
11167 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11168 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11169 D.getCXXScopeSpec().isSet() &&
11172 diag::ext_explicit_instantiation_without_qualified_id)
11174
11176 *this,
11177 FunTmpl ? (NamedDecl *)FunTmpl
11178 : Specialization->getInstantiatedFromMemberFunction(),
11179 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11180
11181 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11182 if (HasExplicitTemplateArgs)
11183 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11185 TemplateLoc,
11187 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11188 return (Decl *)nullptr;
11189}
11190
11192 const CXXScopeSpec &SS,
11193 const IdentifierInfo *Name,
11194 SourceLocation TagLoc,
11195 SourceLocation NameLoc) {
11196 // This has to hold, because SS is expected to be defined.
11197 assert(Name && "Expected a name in a dependent tag");
11198
11200 if (!NNS)
11201 return true;
11202
11204
11205 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11206 Diag(NameLoc, diag::err_dependent_tag_decl)
11207 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11208 return true;
11209 }
11210
11211 // Create the resulting type.
11213 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11214
11215 // Create type-source location information for this type.
11216 TypeLocBuilder TLB;
11218 TL.setElaboratedKeywordLoc(TagLoc);
11220 TL.setNameLoc(NameLoc);
11222}
11223
11225 const CXXScopeSpec &SS,
11226 const IdentifierInfo &II,
11227 SourceLocation IdLoc,
11228 ImplicitTypenameContext IsImplicitTypename) {
11229 if (SS.isInvalid())
11230 return true;
11231
11232 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11233 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11234 << FixItHint::CreateRemoval(TypenameLoc);
11235
11237 TypeSourceInfo *TSI = nullptr;
11238 QualType T =
11241 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11242 /*DeducedTSTContext=*/true);
11243 if (T.isNull())
11244 return true;
11245 return CreateParsedType(T, TSI);
11246}
11247
11250 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11251 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11252 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11253 ASTTemplateArgsPtr TemplateArgsIn,
11254 SourceLocation RAngleLoc) {
11255 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11256 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11257 ? diag::compat_cxx11_typename_outside_of_template
11258 : diag::compat_pre_cxx11_typename_outside_of_template)
11259 << FixItHint::CreateRemoval(TypenameLoc);
11260
11261 // Strangely, non-type results are not ignored by this lookup, so the
11262 // program is ill-formed if it finds an injected-class-name.
11263 if (TypenameLoc.isValid()) {
11264 auto *LookupRD =
11265 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11266 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11267 Diag(TemplateIILoc,
11268 diag::ext_out_of_line_qualified_id_type_names_constructor)
11269 << TemplateII << 0 /*injected-class-name used as template name*/
11270 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11271 }
11272 }
11273
11274 // Translate the parser's template argument list in our AST format.
11275 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11276 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11277
11281 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11282 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11283 if (T.isNull())
11284 return true;
11285
11286 // Provide source-location information for the template specialization type.
11287 TypeLocBuilder Builder;
11289 = Builder.push<TemplateSpecializationTypeLoc>(T);
11290 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11291 TemplateIILoc, TemplateArgs);
11292 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11293 return CreateParsedType(T, TSI);
11294}
11295
11296/// Determine whether this failed name lookup should be treated as being
11297/// disabled by a usage of std::enable_if.
11299 SourceRange &CondRange, Expr *&Cond) {
11300 // We must be looking for a ::type...
11301 if (!II.isStr("type"))
11302 return false;
11303
11304 // ... within an explicitly-written template specialization...
11306 return false;
11307
11308 // FIXME: Look through sugar.
11309 auto EnableIfTSTLoc =
11311 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11312 return false;
11313 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11314
11315 // ... which names a complete class template declaration...
11316 const TemplateDecl *EnableIfDecl =
11317 EnableIfTST->getTemplateName().getAsTemplateDecl();
11318 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11319 return false;
11320
11321 // ... called "enable_if".
11322 const IdentifierInfo *EnableIfII =
11323 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11324 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11325 return false;
11326
11327 // Assume the first template argument is the condition.
11328 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11329
11330 // Dig out the condition.
11331 Cond = nullptr;
11332 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11334 return true;
11335
11336 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11337
11338 // Ignore Boolean literals; they add no value.
11339 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11340 Cond = nullptr;
11341
11342 return true;
11343}
11344
11347 SourceLocation KeywordLoc,
11348 NestedNameSpecifierLoc QualifierLoc,
11349 const IdentifierInfo &II,
11350 SourceLocation IILoc,
11351 TypeSourceInfo **TSI,
11352 bool DeducedTSTContext) {
11353 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11354 DeducedTSTContext);
11355 if (T.isNull())
11356 return QualType();
11357
11358 TypeLocBuilder TLB;
11359 if (isa<DependentNameType>(T)) {
11360 auto TL = TLB.push<DependentNameTypeLoc>(T);
11361 TL.setElaboratedKeywordLoc(KeywordLoc);
11362 TL.setQualifierLoc(QualifierLoc);
11363 TL.setNameLoc(IILoc);
11366 TL.setElaboratedKeywordLoc(KeywordLoc);
11367 TL.setQualifierLoc(QualifierLoc);
11368 TL.setNameLoc(IILoc);
11369 } else if (isa<TemplateTypeParmType>(T)) {
11370 // FIXME: There might be a 'typename' keyword here, but we just drop it
11371 // as it can't be represented.
11372 assert(!QualifierLoc);
11373 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11374 } else if (isa<TagType>(T)) {
11375 auto TL = TLB.push<TagTypeLoc>(T);
11376 TL.setElaboratedKeywordLoc(KeywordLoc);
11377 TL.setQualifierLoc(QualifierLoc);
11378 TL.setNameLoc(IILoc);
11379 } else if (isa<TypedefType>(T)) {
11380 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11381 } else {
11382 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11383 }
11384 *TSI = TLB.getTypeSourceInfo(Context, T);
11385 return T;
11386}
11387
11388/// Build the type that describes a C++ typename specifier,
11389/// e.g., "typename T::type".
11392 SourceLocation KeywordLoc,
11393 NestedNameSpecifierLoc QualifierLoc,
11394 const IdentifierInfo &II,
11395 SourceLocation IILoc, bool DeducedTSTContext) {
11396 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11397
11398 CXXScopeSpec SS;
11399 SS.Adopt(QualifierLoc);
11400
11401 DeclContext *Ctx = nullptr;
11402 if (QualifierLoc) {
11403 Ctx = computeDeclContext(SS);
11404 if (!Ctx) {
11405 // If the nested-name-specifier is dependent and couldn't be
11406 // resolved to a type, build a typename type.
11407 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11408 return Context.getDependentNameType(Keyword,
11409 QualifierLoc.getNestedNameSpecifier(),
11410 &II);
11411 }
11412
11413 // If the nested-name-specifier refers to the current instantiation,
11414 // the "typename" keyword itself is superfluous. In C++03, the
11415 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11416 // allows such extraneous "typename" keywords, and we retroactively
11417 // apply this DR to C++03 code with only a warning. In any case we continue.
11418
11419 if (RequireCompleteDeclContext(SS, Ctx))
11420 return QualType();
11421 }
11422
11423 DeclarationName Name(&II);
11424 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11425 if (Ctx)
11426 LookupQualifiedName(Result, Ctx, SS);
11427 else
11428 LookupName(Result, CurScope);
11429 unsigned DiagID = 0;
11430 Decl *Referenced = nullptr;
11431 switch (Result.getResultKind()) {
11433 // If we're looking up 'type' within a template named 'enable_if', produce
11434 // a more specific diagnostic.
11435 SourceRange CondRange;
11436 Expr *Cond = nullptr;
11437 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11438 // If we have a condition, narrow it down to the specific failed
11439 // condition.
11440 if (Cond) {
11441 Expr *FailedCond;
11442 std::string FailedDescription;
11443 std::tie(FailedCond, FailedDescription) =
11445
11446 Diag(FailedCond->getExprLoc(),
11447 diag::err_typename_nested_not_found_requirement)
11448 << FailedDescription
11449 << FailedCond->getSourceRange();
11450 return QualType();
11451 }
11452
11453 Diag(CondRange.getBegin(),
11454 diag::err_typename_nested_not_found_enable_if)
11455 << Ctx << CondRange;
11456 return QualType();
11457 }
11458
11459 DiagID = Ctx ? diag::err_typename_nested_not_found
11460 : diag::err_unknown_typename;
11461 break;
11462 }
11463
11465 // We found a using declaration that is a value. Most likely, the using
11466 // declaration itself is meant to have the 'typename' keyword.
11467 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11468 IILoc);
11469 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11470 << Name << Ctx << FullRange;
11471 if (UnresolvedUsingValueDecl *Using
11472 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11473 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11474 Diag(Loc, diag::note_using_value_decl_missing_typename)
11475 << FixItHint::CreateInsertion(Loc, "typename ");
11476 }
11477 }
11478 // Fall through to create a dependent typename type, from which we can
11479 // recover better.
11480 [[fallthrough]];
11481
11483 // Okay, it's a member of an unknown instantiation.
11484 return Context.getDependentNameType(Keyword,
11485 QualifierLoc.getNestedNameSpecifier(),
11486 &II);
11487
11489 // FXIME: Missing support for UsingShadowDecl on this path?
11490 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11491 // C++ [class.qual]p2:
11492 // In a lookup in which function names are not ignored and the
11493 // nested-name-specifier nominates a class C, if the name specified
11494 // after the nested-name-specifier, when looked up in C, is the
11495 // injected-class-name of C [...] then the name is instead considered
11496 // to name the constructor of class C.
11497 //
11498 // Unlike in an elaborated-type-specifier, function names are not ignored
11499 // in typename-specifier lookup. However, they are ignored in all the
11500 // contexts where we form a typename type with no keyword (that is, in
11501 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11502 //
11503 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11504 // ignore functions, but that appears to be an oversight.
11509 Type, IILoc);
11510 // FIXME: This appears to be the only case where a template type parameter
11511 // can have an elaborated keyword. We should preserve it somehow.
11514 assert(!QualifierLoc);
11516 }
11517 return Context.getTypeDeclType(
11518 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11519 }
11520
11521 // C++ [dcl.type.simple]p2:
11522 // A type-specifier of the form
11523 // typename[opt] nested-name-specifier[opt] template-name
11524 // is a placeholder for a deduced class type [...].
11525 if (getLangOpts().CPlusPlus17) {
11526 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11527 if (!DeducedTSTContext) {
11528 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11529 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11530 Diag(IILoc, diag::err_dependent_deduced_tst)
11532 << QualType(Qualifier.getAsType(), 0);
11533 else
11534 Diag(IILoc, diag::err_deduced_tst)
11537 return QualType();
11538 }
11539 TemplateName Name = Context.getQualifiedTemplateName(
11540 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11541 TemplateName(TD));
11542 return Context.getDeducedTemplateSpecializationType(
11543 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11544 Name);
11545 }
11546 }
11547
11548 DiagID = Ctx ? diag::err_typename_nested_not_type
11549 : diag::err_typename_not_type;
11550 Referenced = Result.getFoundDecl();
11551 break;
11552
11554 DiagID = Ctx ? diag::err_typename_nested_not_type
11555 : diag::err_typename_not_type;
11556 Referenced = *Result.begin();
11557 break;
11558
11560 return QualType();
11561 }
11562
11563 // If we get here, it's because name lookup did not find a
11564 // type. Emit an appropriate diagnostic and return an error.
11565 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11566 IILoc);
11567 if (Ctx)
11568 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11569 else
11570 Diag(IILoc, DiagID) << FullRange << Name;
11571 if (Referenced)
11572 Diag(Referenced->getLocation(),
11573 Ctx ? diag::note_typename_member_refers_here
11574 : diag::note_typename_refers_here)
11575 << Name;
11576 return QualType();
11577}
11578
11579namespace {
11580 // See Sema::RebuildTypeInCurrentInstantiation
11581 class CurrentInstantiationRebuilder
11582 : public TreeTransform<CurrentInstantiationRebuilder> {
11583 SourceLocation Loc;
11584 DeclarationName Entity;
11585
11586 public:
11588
11589 CurrentInstantiationRebuilder(Sema &SemaRef,
11590 SourceLocation Loc,
11591 DeclarationName Entity)
11592 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11593 Loc(Loc), Entity(Entity) { }
11594
11595 /// Determine whether the given type \p T has already been
11596 /// transformed.
11597 ///
11598 /// For the purposes of type reconstruction, a type has already been
11599 /// transformed if it is NULL or if it is not dependent.
11600 bool AlreadyTransformed(QualType T) {
11601 return T.isNull() || !T->isInstantiationDependentType();
11602 }
11603
11604 /// Returns the location of the entity whose type is being
11605 /// rebuilt.
11606 SourceLocation getBaseLocation() { return Loc; }
11607
11608 /// Returns the name of the entity whose type is being rebuilt.
11609 DeclarationName getBaseEntity() { return Entity; }
11610
11611 /// Sets the "base" location and entity when that
11612 /// information is known based on another transformation.
11613 void setBase(SourceLocation Loc, DeclarationName Entity) {
11614 this->Loc = Loc;
11615 this->Entity = Entity;
11616 }
11617
11618 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11619 // Lambdas never need to be transformed.
11620 return E;
11621 }
11622 };
11623} // end anonymous namespace
11624
11626 SourceLocation Loc,
11627 DeclarationName Name) {
11628 if (!T || !T->getType()->isInstantiationDependentType())
11629 return T;
11630
11631 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11632 return Rebuilder.TransformType(T);
11633}
11634
11636 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11637 DeclarationName());
11638 return Rebuilder.TransformExpr(E);
11639}
11640
11642 if (SS.isInvalid())
11643 return true;
11644
11646 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11647 DeclarationName());
11649 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11650 if (!Rebuilt)
11651 return true;
11652
11653 SS.Adopt(Rebuilt);
11654 return false;
11655}
11656
11658 TemplateParameterList *Params) {
11659 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11660 Decl *Param = Params->getParam(I);
11661
11662 // There is nothing to rebuild in a type parameter.
11663 if (isa<TemplateTypeParmDecl>(Param))
11664 continue;
11665
11666 // Rebuild the template parameter list of a template template parameter.
11668 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11670 TTP->getTemplateParameters()))
11671 return true;
11672
11673 continue;
11674 }
11675
11676 // Rebuild the type of a non-type template parameter.
11678 TypeSourceInfo *NewTSI
11680 NTTP->getLocation(),
11681 NTTP->getDeclName());
11682 if (!NewTSI)
11683 return true;
11684
11685 if (NewTSI->getType()->isUndeducedType()) {
11686 // C++17 [temp.dep.expr]p3:
11687 // An id-expression is type-dependent if it contains
11688 // - an identifier associated by name lookup with a non-type
11689 // template-parameter declared with a type that contains a
11690 // placeholder type (7.1.7.4),
11691 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11692 }
11693
11694 if (NewTSI != NTTP->getTypeSourceInfo()) {
11695 NTTP->setTypeSourceInfo(NewTSI);
11696 NTTP->setType(NewTSI->getType());
11697 }
11698 }
11699
11700 return false;
11701}
11702
11703std::string
11705 const TemplateArgumentList &Args) {
11706 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11707}
11708
11709std::string
11711 const TemplateArgument *Args,
11712 unsigned NumArgs) {
11713 SmallString<128> Str;
11714 llvm::raw_svector_ostream Out(Str);
11715
11716 if (!Params || Params->size() == 0 || NumArgs == 0)
11717 return std::string();
11718
11719 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11720 if (I >= NumArgs)
11721 break;
11722
11723 if (I == 0)
11724 Out << "[with ";
11725 else
11726 Out << ", ";
11727
11728 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11729 Out << Id->getName();
11730 } else {
11731 Out << '$' << I;
11732 }
11733
11734 Out << " = ";
11735 Args[I].print(getPrintingPolicy(), Out,
11737 getPrintingPolicy(), Params, I));
11738 }
11739
11740 Out << ']';
11741 return std::string(Out.str());
11742}
11743
11745 CachedTokens &Toks) {
11746 if (!FD)
11747 return;
11748
11749 auto LPT = std::make_unique<LateParsedTemplate>();
11750
11751 // Take tokens to avoid allocations
11752 LPT->Toks.swap(Toks);
11753 LPT->D = FnD;
11754 LPT->FPO = getCurFPFeatures();
11755 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11756
11757 FD->setLateTemplateParsed(true);
11758}
11759
11761 if (!FD)
11762 return;
11763 FD->setLateTemplateParsed(false);
11764}
11765
11767 DeclContext *DC = CurContext;
11768
11769 while (DC) {
11770 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11771 const FunctionDecl *FD = RD->isLocalClass();
11772 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11773 } else if (DC->isTranslationUnit() || DC->isNamespace())
11774 return false;
11775
11776 DC = DC->getParent();
11777 }
11778 return false;
11779}
11780
11781namespace {
11782/// Walk the path from which a declaration was instantiated, and check
11783/// that every explicit specialization along that path is visible. This enforces
11784/// C++ [temp.expl.spec]/6:
11785///
11786/// If a template, a member template or a member of a class template is
11787/// explicitly specialized then that specialization shall be declared before
11788/// the first use of that specialization that would cause an implicit
11789/// instantiation to take place, in every translation unit in which such a
11790/// use occurs; no diagnostic is required.
11791///
11792/// and also C++ [temp.class.spec]/1:
11793///
11794/// A partial specialization shall be declared before the first use of a
11795/// class template specialization that would make use of the partial
11796/// specialization as the result of an implicit or explicit instantiation
11797/// in every translation unit in which such a use occurs; no diagnostic is
11798/// required.
11799class ExplicitSpecializationVisibilityChecker {
11800 Sema &S;
11801 SourceLocation Loc;
11804
11805public:
11806 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11808 : S(S), Loc(Loc), Kind(Kind) {}
11809
11810 void check(NamedDecl *ND) {
11811 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11812 return checkImpl(FD);
11813 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11814 return checkImpl(RD);
11815 if (auto *VD = dyn_cast<VarDecl>(ND))
11816 return checkImpl(VD);
11817 if (auto *ED = dyn_cast<EnumDecl>(ND))
11818 return checkImpl(ED);
11819 }
11820
11821private:
11822 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11823 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11824 : Sema::MissingImportKind::ExplicitSpecialization;
11825 const bool Recover = true;
11826
11827 // If we got a custom set of modules (because only a subset of the
11828 // declarations are interesting), use them, otherwise let
11829 // diagnoseMissingImport intelligently pick some.
11830 if (Modules.empty())
11831 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11832 else
11833 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11834 }
11835
11836 bool CheckMemberSpecialization(const NamedDecl *D) {
11837 return Kind == Sema::AcceptableKind::Visible
11840 }
11841
11842 bool CheckExplicitSpecialization(const NamedDecl *D) {
11843 return Kind == Sema::AcceptableKind::Visible
11846 }
11847
11848 bool CheckDeclaration(const NamedDecl *D) {
11849 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11851 }
11852
11853 // Check a specific declaration. There are three problematic cases:
11854 //
11855 // 1) The declaration is an explicit specialization of a template
11856 // specialization.
11857 // 2) The declaration is an explicit specialization of a member of an
11858 // templated class.
11859 // 3) The declaration is an instantiation of a template, and that template
11860 // is an explicit specialization of a member of a templated class.
11861 //
11862 // We don't need to go any deeper than that, as the instantiation of the
11863 // surrounding class / etc is not triggered by whatever triggered this
11864 // instantiation, and thus should be checked elsewhere.
11865 template<typename SpecDecl>
11866 void checkImpl(SpecDecl *Spec) {
11867 bool IsHiddenExplicitSpecialization = false;
11868 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11869 // Some invalid friend declarations are written as specializations but are
11870 // instantiated implicitly.
11871 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11872 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11873 if (SpecKind == TSK_ExplicitSpecialization) {
11874 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11875 ? !CheckMemberSpecialization(Spec)
11876 : !CheckExplicitSpecialization(Spec);
11877 } else {
11878 checkInstantiated(Spec);
11879 }
11880
11881 if (IsHiddenExplicitSpecialization)
11882 diagnose(Spec->getMostRecentDecl(), false);
11883 }
11884
11885 void checkInstantiated(FunctionDecl *FD) {
11886 if (auto *TD = FD->getPrimaryTemplate())
11887 checkTemplate(TD);
11888 }
11889
11890 void checkInstantiated(CXXRecordDecl *RD) {
11891 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11892 if (!SD)
11893 return;
11894
11895 auto From = SD->getSpecializedTemplateOrPartial();
11896 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11897 checkTemplate(TD);
11898 else if (auto *TD =
11899 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11900 if (!CheckDeclaration(TD))
11901 diagnose(TD, true);
11902 checkTemplate(TD);
11903 }
11904 }
11905
11906 void checkInstantiated(VarDecl *RD) {
11907 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11908 if (!SD)
11909 return;
11910
11911 auto From = SD->getSpecializedTemplateOrPartial();
11912 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11913 checkTemplate(TD);
11914 else if (auto *TD =
11915 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11916 if (!CheckDeclaration(TD))
11917 diagnose(TD, true);
11918 checkTemplate(TD);
11919 }
11920 }
11921
11922 void checkInstantiated(EnumDecl *FD) {}
11923
11924 template<typename TemplDecl>
11925 void checkTemplate(TemplDecl *TD) {
11926 if (TD->isMemberSpecialization()) {
11927 if (!CheckMemberSpecialization(TD))
11928 diagnose(TD->getMostRecentDecl(), false);
11929 }
11930 }
11931};
11932} // end anonymous namespace
11933
11935 if (!getLangOpts().Modules)
11936 return;
11937
11938 ExplicitSpecializationVisibilityChecker(*this, Loc,
11940 .check(Spec);
11941}
11942
11944 NamedDecl *Spec) {
11945 if (!getLangOpts().CPlusPlusModules)
11946 return checkSpecializationVisibility(Loc, Spec);
11947
11948 ExplicitSpecializationVisibilityChecker(*this, Loc,
11950 .check(Spec);
11951}
11952
11955 return N->getLocation();
11956 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11958 return FD->getLocation();
11961 return N->getLocation();
11962 }
11963 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11964 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11965 continue;
11966 return CSC.PointOfInstantiation;
11967 }
11968 return N->getLocation();
11969}
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.
Result
Implement __builtin_bit_cast and related operations.
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 void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
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, bool IsSpecified, 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:1001
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:1084
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:974
@ 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:1037
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:223
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:965
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
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:3956
QualType getElementType() const
Definition TypeBase.h:3798
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:8246
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:8299
Pointer to a block type.
Definition TypeBase.h:3606
QualType getPointeeType() const
Definition TypeBase.h:3618
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:3228
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:2111
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:739
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3870
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:1557
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
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:133
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:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
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:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
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:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
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:1072
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.
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:3339
QualType getElementType() const
Definition TypeBase.h:3349
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:3824
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
bool isFileContext() const
Definition DeclBase.h:2197
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:2219
bool isTranslationUnit() const
Definition DeclBase.h:2202
bool isRecord() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
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:1276
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1377
ValueDecl * getDecl()
Definition Expr.h:1344
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
bool isNoreturnSpecified() const
Definition DeclSpec.h:668
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:669
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
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:1078
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
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:1234
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:854
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:824
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:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2823
bool isInvalidDecl() const
Definition DeclBase.h:596
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
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:935
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
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:1952
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4125
QualType getPointeeType() const
Definition TypeBase.h:4137
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:3510
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:549
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4075
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4165
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4537
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4291
QualType getElementType() const
Definition TypeBase.h:4303
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:4055
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4327
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5152
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
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:3104
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:3099
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:833
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:3079
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:4078
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents a member of a struct/union/class.
Definition Decl.h:3204
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1003
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1082
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:2029
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2512
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4183
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4512
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4291
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4150
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3725
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2576
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4122
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:4356
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2398
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4395
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3147
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4143
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4949
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
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:4907
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:3859
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3973
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5314
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:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
Represents a linkage specification.
Definition DeclCXX.h:3036
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:4424
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3749
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5646
QualType getPointeeType() const
Definition TypeBase.h:3735
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:240
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:1681
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
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.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
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:8009
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
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:1184
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:3302
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3318
bool isConceptReference() const
Definition ExprCXX.h:3291
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3337
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:4363
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
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:8265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
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:8536
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3686
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
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:8447
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3679
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
bool ValidateCandidate(const TypoCorrection &Candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
QualifiedLookupValidatorCCC(bool HasQualifier)
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:3699
Represents a struct/union/class.
Definition Decl.h:4369
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4553
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5374
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
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:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
Scope * getDeclParent()
Definition Scope.h:321
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
Scope * getTemplateParamParent()
Definition Scope.h:318
@ 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:98
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:13796
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8530
A RAII object to temporarily push a declaration context.
Definition Sema.h:3532
Whether and why a template name is required in this lookup.
Definition Sema.h:11531
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11539
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12590
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12624
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7799
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
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:13735
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13186
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2664
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:9412
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9416
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9424
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9419
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:9728
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:1475
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 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:4206
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:2079
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:11502
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12101
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12104
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12108
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
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:1310
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:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:938
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:941
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:770
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:1214
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:12280
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12298
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12288
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12308
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:11552
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11559
@ None
This is not assumed to be a template name.
Definition Sema.h:11554
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11556
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:11488
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:936
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:14600
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14588
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14597
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14591
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14615
const LangOptions & getLangOpts() const
Definition Sema.h:934
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:1309
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:1308
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)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:645
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:1448
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,...
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
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:13834
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:15615
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:1311
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:4704
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:6819
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6798
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:14111
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:11529
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:521
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:11712
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11722
@ TPC_FriendFunctionTemplate
Definition Sema.h:11720
@ TPC_ClassTemplateMember
Definition Sema.h:11718
@ TPC_FunctionTemplate
Definition Sema.h:11717
@ TPC_FriendClassTemplate
Definition Sema.h:11719
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11721
friend class InitializationSequence
Definition Sema.h:1590
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)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
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:6369
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.
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, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
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...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6506
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1302
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
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:3525
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11494
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:9737
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13029
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:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8744
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13831
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:4664
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
StringRef getKindName() const
Definition Decl.h:3957
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4904
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5040
TagKind getTagKind() const
Definition Decl.h:3961
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)
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.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
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:3732
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:3557
const Type * getTypeForDecl() const
Definition Decl.h:3582
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3591
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:6282
A container of type source information.
Definition TypeBase.h:8418
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:8429
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:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBooleanType() const
Definition TypeBase.h:9187
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2359
bool isRValueReferenceType() const
Definition TypeBase.h:8716
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:749
bool isArrayType() const
Definition TypeBase.h:8783
bool isPointerType() const
Definition TypeBase.h:8684
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2160
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:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8871
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2963
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2854
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isBitIntType() const
Definition TypeBase.h:8959
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2113
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
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:5035
bool isPointerOrReferenceType() const
Definition TypeBase.h:8688
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isVectorType() const
Definition TypeBase.h:8823
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2471
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
QualType getUnderlyingType() const
Definition Decl.h:3661
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4177
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:2250
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1071
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1251
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1067
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
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:437
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:6087
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3961
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
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
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
TLSKind getTLSKind() const
Definition Decl.cpp:2147
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2733
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:2868
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:2761
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:2740
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2859
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)
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:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4239
QualType getElementType() const
Definition TypeBase.h:4253
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:56
ImplicitTypenameContext
Definition DeclSpec.h:1935
@ 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:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
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:1031
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
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:249
@ SC_Extern
Definition Specifiers.h:252
@ TSCS_unspecified
Definition Specifiers.h:237
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.
OptionalUnsigned< unsigned > UnsignedOrNone
@ 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:5995
@ Enum
The "enum" keyword.
Definition TypeBase.h:6009
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:1809
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:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
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:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
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:1256
@ 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
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
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:5970
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5988
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
CharacterLiteralKind
Definition Expr.h:1609
#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:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5456
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3389
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3406
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3371
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:12139
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12135
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12128
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12125
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12125
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13237
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13341
A stack object to be created when performing template instantiation.
Definition Sema.h:13431
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13584
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:1050