clang 24.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 NewConstrainedParm->setType(TL.getType());
1320 return true;
1321 }
1322 // FIXME: Concepts: This should be the type of the placeholder, but this is
1323 // unclear in the wording right now.
1324 DeclRefExpr *Ref =
1325 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1326 VK_PRValue, OrigConstrainedParm->getLocation());
1327 if (!Ref)
1328 return true;
1329 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1331 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1333 OrigConstrainedParm->getLocation(),
1334 [&](TemplateArgumentListInfo &ConstraintArgs) {
1335 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1336 ConstraintArgs.addArgument(TL.getArgLoc(I));
1337 },
1338 EllipsisLoc);
1339 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1340 !ImmediatelyDeclaredConstraint.isUsable())
1341 return true;
1342
1343 NewConstrainedParm->setPlaceholderTypeConstraint(
1344 ImmediatelyDeclaredConstraint.get());
1345 return false;
1346}
1347
1349 SourceLocation Loc) {
1350 if (TSI->getType()->isUndeducedType()) {
1351 // C++17 [temp.dep.expr]p3:
1352 // An id-expression is type-dependent if it contains
1353 // - an identifier associated by name lookup with a non-type
1354 // template-parameter declared with a type that contains a
1355 // placeholder type (7.1.7.4),
1357 if (!NewTSI)
1358 return QualType();
1359 TSI = NewTSI;
1360 }
1361
1362 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1363}
1364
1366 if (T->isDependentType())
1367 return false;
1368
1369 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1370 return true;
1371
1372 if (T->isStructuralType())
1373 return false;
1374
1375 // Structural types are required to be object types or lvalue references.
1376 if (T->isRValueReferenceType()) {
1377 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1378 return true;
1379 }
1380
1381 // Don't mention structural types in our diagnostic prior to C++20. Also,
1382 // there's not much more we can say about non-scalar non-class types --
1383 // because we can't see functions or arrays here, those can only be language
1384 // extensions.
1385 if (!getLangOpts().CPlusPlus20 ||
1386 (!T->isScalarType() && !T->isRecordType())) {
1387 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1388 return true;
1389 }
1390
1391 // Structural types are required to be literal types.
1392 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1393 return true;
1394
1395 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1396
1397 // Drill down into the reason why the class is non-structural.
1398 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1399 // All members are required to be public and non-mutable, and can't be of
1400 // rvalue reference type. Check these conditions first to prefer a "local"
1401 // reason over a more distant one.
1402 for (const FieldDecl *FD : RD->fields()) {
1403 if (FD->getAccess() != AS_public) {
1404 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1405 return true;
1406 }
1407 if (FD->isMutable()) {
1408 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1409 return true;
1410 }
1411 if (FD->getType()->isRValueReferenceType()) {
1412 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1413 << T;
1414 return true;
1415 }
1416 }
1417
1418 // All bases are required to be public.
1419 for (const auto &BaseSpec : RD->bases()) {
1420 if (BaseSpec.getAccessSpecifier() != AS_public) {
1421 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1422 << T << 1;
1423 return true;
1424 }
1425 }
1426
1427 // All subobjects are required to be of structural types.
1428 SourceLocation SubLoc;
1429 QualType SubType;
1430 int Kind = -1;
1431
1432 for (const FieldDecl *FD : RD->fields()) {
1433 QualType T = Context.getBaseElementType(FD->getType());
1434 if (!T->isStructuralType()) {
1435 SubLoc = FD->getLocation();
1436 SubType = T;
1437 Kind = 0;
1438 break;
1439 }
1440 }
1441
1442 if (Kind == -1) {
1443 for (const auto &BaseSpec : RD->bases()) {
1444 QualType T = BaseSpec.getType();
1445 if (!T->isStructuralType()) {
1446 SubLoc = BaseSpec.getBaseTypeLoc();
1447 SubType = T;
1448 Kind = 1;
1449 break;
1450 }
1451 }
1452 }
1453
1454 assert(Kind != -1 && "couldn't find reason why type is not structural");
1455 Diag(SubLoc, diag::note_not_structural_subobject)
1456 << T << Kind << SubType;
1457 T = SubType;
1458 RD = T->getAsCXXRecordDecl();
1459 }
1460
1461 return true;
1462}
1463
1465 SourceLocation Loc) {
1466 // We don't allow variably-modified types as the type of non-type template
1467 // parameters.
1468 if (T->isVariablyModifiedType()) {
1469 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1470 << T;
1471 return QualType();
1472 }
1473
1474 if (T->isBlockPointerType()) {
1475 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1476 return QualType();
1477 }
1478
1479 // C++ [temp.param]p4:
1480 //
1481 // A non-type template-parameter shall have one of the following
1482 // (optionally cv-qualified) types:
1483 //
1484 // -- integral or enumeration type,
1485 if (T->isIntegralOrEnumerationType() ||
1486 // -- pointer to object or pointer to function,
1487 T->isPointerType() ||
1488 // -- lvalue reference to object or lvalue reference to function,
1489 T->isLValueReferenceType() ||
1490 // -- pointer to member,
1491 T->isMemberPointerType() ||
1492 // -- std::nullptr_t, or
1493 T->isNullPtrType() ||
1494 // -- a type that contains a placeholder type.
1495 T->isUndeducedType()) {
1496 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1497 // are ignored when determining its type.
1498 return T.getUnqualifiedType();
1499 }
1500
1501 // C++ [temp.param]p8:
1502 //
1503 // A non-type template-parameter of type "array of T" or
1504 // "function returning T" is adjusted to be of type "pointer to
1505 // T" or "pointer to function returning T", respectively.
1506 if (T->isArrayType() || T->isFunctionType())
1507 return Context.getDecayedType(T);
1508
1509 // If T is a dependent type, we can't do the check now, so we
1510 // assume that it is well-formed. Note that stripping off the
1511 // qualifiers here is not really correct if T turns out to be
1512 // an array type, but we'll recompute the type everywhere it's
1513 // used during instantiation, so that should be OK. (Using the
1514 // qualified type is equally wrong.)
1515 if (T->isDependentType())
1516 return T.getUnqualifiedType();
1517
1518 // C++20 [temp.param]p6:
1519 // -- a structural type
1520 if (RequireStructuralType(T, Loc))
1521 return QualType();
1522
1523 if (!getLangOpts().CPlusPlus20) {
1524 // FIXME: Consider allowing structural types as an extension in C++17. (In
1525 // earlier language modes, the template argument evaluation rules are too
1526 // inflexible.)
1527 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1528 return QualType();
1529 }
1530
1531 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1532 return T.getUnqualifiedType();
1533}
1534
1536 unsigned Depth,
1537 unsigned Position,
1538 SourceLocation EqualLoc,
1539 Expr *Default) {
1541
1542 // Check that we have valid decl-specifiers specified.
1543 auto CheckValidDeclSpecifiers = [this, &D] {
1544 // C++ [temp.param]
1545 // p1
1546 // template-parameter:
1547 // ...
1548 // parameter-declaration
1549 // p2
1550 // ... A storage class shall not be specified in a template-parameter
1551 // declaration.
1552 // [dcl.typedef]p1:
1553 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1554 // of a parameter-declaration
1555 const DeclSpec &DS = D.getDeclSpec();
1556 auto EmitDiag = [this](SourceLocation Loc) {
1557 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1559 };
1561 EmitDiag(DS.getStorageClassSpecLoc());
1562
1564 EmitDiag(DS.getThreadStorageClassSpecLoc());
1565
1566 // [dcl.inline]p1:
1567 // The inline specifier can be applied only to the declaration or
1568 // definition of a variable or function.
1569
1570 if (DS.isInlineSpecified())
1571 EmitDiag(DS.getInlineSpecLoc());
1572
1573 // [dcl.constexpr]p1:
1574 // The constexpr specifier shall be applied only to the definition of a
1575 // variable or variable template or the declaration of a function or
1576 // function template.
1577
1578 if (DS.hasConstexprSpecifier())
1579 EmitDiag(DS.getConstexprSpecLoc());
1580
1581 // [dcl.fct.spec]p1:
1582 // Function-specifiers can be used only in function declarations.
1583
1584 if (DS.isVirtualSpecified())
1585 EmitDiag(DS.getVirtualSpecLoc());
1586
1587 if (DS.hasExplicitSpecifier())
1588 EmitDiag(DS.getExplicitSpecLoc());
1589
1590 if (DS.isNoreturnSpecified())
1591 EmitDiag(DS.getNoreturnSpecLoc());
1592 };
1593
1594 CheckValidDeclSpecifiers();
1595
1596 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1597 if (isa<AutoType>(T))
1599 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1600 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1601
1602 assert(S->isTemplateParamScope() &&
1603 "Non-type template parameter not in template parameter scope!");
1604 bool Invalid = false;
1605
1607 if (T.isNull()) {
1608 T = Context.IntTy; // Recover with an 'int' type.
1609 Invalid = true;
1610 }
1611
1613
1614 const IdentifierInfo *ParamName = D.getIdentifier();
1615 bool IsParameterPack = D.hasEllipsis();
1617 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1618 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1619 TInfo);
1620 Param->setAccess(AS_public);
1621
1623 if (TL.isConstrained()) {
1624 if (D.getEllipsisLoc().isInvalid() &&
1625 T->containsUnexpandedParameterPack()) {
1626 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1627 for (auto &Loc :
1628 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1631 }
1632 if (!Invalid &&
1633 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1634 Invalid = true;
1635 }
1636
1637 if (Invalid)
1638 Param->setInvalidDecl();
1639
1640 if (Param->isParameterPack())
1641 if (auto *CSI = getEnclosingLambdaOrBlock())
1642 CSI->LocalPacks.push_back(Param);
1643
1644 if (ParamName) {
1646 ParamName);
1647
1648 // Add the template parameter into the current scope.
1649 S->AddDecl(Param);
1650 IdResolver.AddDecl(Param);
1651 }
1652
1653 // C++0x [temp.param]p9:
1654 // A default template-argument may be specified for any kind of
1655 // template-parameter that is not a template parameter pack.
1656 if (Default && IsParameterPack) {
1657 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1658 Default = nullptr;
1659 }
1660
1661 // Check the well-formedness of the default template argument, if provided.
1662 if (Default) {
1663 // Check for unexpanded parameter packs.
1665 return Param;
1666
1667 Param->setDefaultArgument(
1669 TemplateArgument(Default, /*IsCanonical=*/false),
1670 QualType(), SourceLocation()));
1671 }
1672
1673 return Param;
1674}
1675
1676/// ActOnTemplateTemplateParameter - Called when a C++ template template
1677/// parameter (e.g. T in template <template <typename> class T> class array)
1678/// has been parsed. S is the current scope.
1680 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1681 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1682 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1683 unsigned Position, SourceLocation EqualLoc,
1685 assert(S->isTemplateParamScope() &&
1686 "Template template parameter not in template parameter scope!");
1687
1688 bool IsParameterPack = EllipsisLoc.isValid();
1689
1690 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1691 if (Params->size() == 0) {
1692 Diag(Loc, diag::err_template_template_parm_no_parms)
1693 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1694
1695 // Recover as if there was a type template parameter pack.
1696 SmallVector<NamedDecl *, 4> ParamDecls;
1697 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1698 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1699 Depth + 1, 0, /*Id=*/nullptr,
1700 /*Typename=*/false, /*ParameterPack=*/true));
1702 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1703 Params->getRAngleLoc(), Params->getRequiresClause());
1704 }
1705
1706 bool Invalid = false;
1708 Params,
1709 /*OldParams=*/nullptr,
1710 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1711 Invalid = true;
1712
1713 // Construct the parameter object.
1715 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1716 IsParameterPack, Name, Kind, Typename, Params);
1717 Param->setAccess(AS_public);
1718
1719 if (Param->isParameterPack())
1720 if (auto *LSI = getEnclosingLambdaOrBlock())
1721 LSI->LocalPacks.push_back(Param);
1722
1723 // If the template template parameter has a name, then link the identifier
1724 // into the scope and lookup mechanisms.
1725 if (Name) {
1726 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1727
1728 S->AddDecl(Param);
1729 IdResolver.AddDecl(Param);
1730 }
1731
1732 if (Invalid)
1733 Param->setInvalidDecl();
1734
1735 // C++0x [temp.param]p9:
1736 // A default template-argument may be specified for any kind of
1737 // template-parameter that is not a template parameter pack.
1738 if (IsParameterPack && !Default.isInvalid()) {
1739 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1741 }
1742
1743 if (!Default.isInvalid()) {
1744 // Check only that we have a template template argument. We don't want to
1745 // try to check well-formedness now, because our template template parameter
1746 // might have dependent types in its template parameters, which we wouldn't
1747 // be able to match now.
1748 //
1749 // If none of the template template parameter's template arguments mention
1750 // other template parameters, we could actually perform more checking here.
1751 // However, it isn't worth doing.
1753 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1754 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1755 << DefaultArg.getSourceRange();
1756 return Param;
1757 }
1758
1759 TemplateName Name =
1762 if (Template &&
1764 return Param;
1765 }
1766
1767 // Check for unexpanded parameter packs.
1769 DefaultArg.getArgument().getAsTemplate(),
1771 return Param;
1772
1773 Param->setDefaultArgument(Context, DefaultArg);
1774 }
1775
1776 return Param;
1777}
1778
1779namespace {
1780class ConstraintRefersToContainingTemplateChecker
1782 using inherited = ConstDynamicRecursiveASTVisitor;
1783 bool Result = false;
1784 const FunctionDecl *Friend = nullptr;
1785 unsigned TemplateDepth = 0;
1786
1787 // Check a record-decl that we've seen to see if it is a lexical parent of the
1788 // Friend, likely because it was referred to without its template arguments.
1789 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1790 CheckingRD = CheckingRD->getMostRecentDecl();
1791 if (!CheckingRD->isTemplated())
1792 return true;
1793
1794 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1795 DC && !DC->isFileContext(); DC = DC->getParent())
1796 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1797 if (CheckingRD == RD->getMostRecentDecl()) {
1798 Result = true;
1799 return false;
1800 }
1801
1802 return true;
1803 }
1804
1805 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1806 if (D->getDepth() < TemplateDepth)
1807 Result = true;
1808
1809 // Necessary because the type of the NTTP might be what refers to the parent
1810 // constriant.
1811 return TraverseType(D->getType());
1812 }
1813
1814public:
1815 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1816 unsigned TemplateDepth)
1817 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1818
1819 bool getResult() const { return Result; }
1820
1821 // This should be the only template parm type that we have to deal with.
1822 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1823 // FunctionParmPackExpr are all partially substituted, which cannot happen
1824 // with concepts at this point in translation.
1825 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1826 if (Type->getDecl()->getDepth() < TemplateDepth) {
1827 Result = true;
1828 return false;
1829 }
1830 return true;
1831 }
1832
1833 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1834 return TraverseDecl(E->getDecl());
1835 }
1836
1837 bool TraverseTypedefType(const TypedefType *TT,
1838 bool /*TraverseQualifier*/) override {
1839 return TraverseType(TT->desugar());
1840 }
1841
1842 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1843 // We don't care about TypeLocs. So traverse Types instead.
1844 return TraverseType(TL.getType(), TraverseQualifier);
1845 }
1846
1847 bool VisitTagType(const TagType *T) override {
1848 return TraverseDecl(T->getDecl());
1849 }
1850
1851 bool TraverseDecl(const Decl *D) override {
1852 assert(D);
1853 // FIXME : This is possibly an incomplete list, but it is unclear what other
1854 // Decl kinds could be used to refer to the template parameters. This is a
1855 // best guess so far based on examples currently available, but the
1856 // unreachable should catch future instances/cases.
1857 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1858 return TraverseType(TD->getUnderlyingType());
1859 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1860 return CheckNonTypeTemplateParmDecl(NTTPD);
1861 if (auto *VD = dyn_cast<ValueDecl>(D))
1862 return TraverseType(VD->getType());
1863 if (isa<TemplateDecl>(D))
1864 return true;
1865 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1866 return CheckIfContainingRecord(RD);
1867
1869 // No direct types to visit here I believe.
1870 } else
1871 llvm_unreachable("Don't know how to handle this declaration type yet");
1872 return true;
1873 }
1874};
1875} // namespace
1876
1878 const FunctionDecl *Friend, unsigned TemplateDepth,
1879 const Expr *Constraint) {
1880 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1881 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1882 Checker.TraverseStmt(Constraint);
1883 return Checker.getResult();
1884}
1885
1888 SourceLocation ExportLoc,
1889 SourceLocation TemplateLoc,
1890 SourceLocation LAngleLoc,
1891 ArrayRef<NamedDecl *> Params,
1892 SourceLocation RAngleLoc,
1893 Expr *RequiresClause) {
1894 if (ExportLoc.isValid())
1895 Diag(ExportLoc, diag::warn_template_export_unsupported);
1896
1897 for (NamedDecl *P : Params)
1899
1900 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1901 llvm::ArrayRef(Params), RAngleLoc,
1902 RequiresClause);
1903}
1904
1906 const CXXScopeSpec &SS) {
1907 if (SS.isSet())
1908 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1909}
1910
1911// Returns the template parameter list with all default template argument
1912// information.
1914 // Make sure we get the template parameter list from the most
1915 // recent declaration, since that is the only one that is guaranteed to
1916 // have all the default template argument information.
1917 Decl *D = TD->getMostRecentDecl();
1918 // C++11 N3337 [temp.param]p12:
1919 // A default template argument shall not be specified in a friend class
1920 // template declaration.
1921 //
1922 // Skip past friend *declarations* because they are not supposed to contain
1923 // default template arguments. Moreover, these declarations may introduce
1924 // template parameters living in different template depths than the
1925 // corresponding template parameters in TD, causing unmatched constraint
1926 // substitution.
1927 //
1928 // FIXME: Diagnose such cases within a class template:
1929 // template <class T>
1930 // struct S {
1931 // template <class = void> friend struct C;
1932 // };
1933 // template struct S<int>;
1935 D->getPreviousDecl())
1936 D = D->getPreviousDecl();
1937 return cast<TemplateDecl>(D)->getTemplateParameters();
1938}
1939
1941 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1942 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1943 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1944 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1945 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1946 TemplateParameterList **OuterTemplateParamLists,
1947 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1948 assert(TemplateParams && TemplateParams->size() > 0 &&
1949 "No template parameters");
1950 assert(TUK != TagUseKind::Reference &&
1951 "Can only declare or define class templates");
1952 bool Invalid = false;
1953
1954 // Check that we can declare a template here.
1955 if (CheckTemplateDeclScope(S, TemplateParams))
1956 return true;
1957
1959 assert(Kind != TagTypeKind::Enum &&
1960 "can't build template of enumerated type");
1961
1962 // There is no such thing as an unnamed class template.
1963 if (!Name) {
1964 Diag(KWLoc, diag::err_template_unnamed_class);
1965 return true;
1966 }
1967
1968 // Find any previous declaration with this name. For a friend with no
1969 // scope explicitly specified, we only look for tag declarations (per
1970 // C++11 [basic.lookup.elab]p2).
1971 DeclContext *SemanticContext;
1972 LookupResult Previous(*this, Name, NameLoc,
1973 (SS.isEmpty() && TUK == TagUseKind::Friend)
1977 if (SS.isNotEmpty() && !SS.isInvalid()) {
1978 SemanticContext = computeDeclContext(SS, true);
1979 if (!SemanticContext) {
1980 // FIXME: Horrible, horrible hack! We can't currently represent this
1981 // in the AST, and historically we have just ignored such friend
1982 // class templates, so don't complain here.
1983 Diag(NameLoc, TUK == TagUseKind::Friend
1984 ? diag::warn_template_qualified_friend_ignored
1985 : diag::err_template_qualified_declarator_no_match)
1986 << SS.getScopeRep() << SS.getRange();
1987 return TUK != TagUseKind::Friend;
1988 }
1989
1990 if (RequireCompleteDeclContext(SS, SemanticContext))
1991 return true;
1992
1993 // If we're adding a template to a dependent context, we may need to
1994 // rebuilding some of the types used within the template parameter list,
1995 // now that we know what the current instantiation is.
1996 if (SemanticContext->isDependentContext()) {
1997 ContextRAII SavedContext(*this, SemanticContext);
1999 Invalid = true;
2000 }
2001
2002 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2003 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2004 /*TemplateId=*/nullptr,
2005 IsMemberSpecialization))
2006 return true;
2007
2008 LookupQualifiedName(Previous, SemanticContext);
2009 } else {
2010 SemanticContext = CurContext;
2011
2012 // C++14 [class.mem]p14:
2013 // If T is the name of a class, then each of the following shall have a
2014 // name different from T:
2015 // -- every member template of class T
2016 if (TUK != TagUseKind::Friend &&
2017 DiagnoseClassNameShadow(SemanticContext,
2018 DeclarationNameInfo(Name, NameLoc)))
2019 return true;
2020
2021 LookupName(Previous, S);
2022 }
2023
2024 if (Previous.isAmbiguous())
2025 return true;
2026
2027 // Let the template parameter scope enter the lookup chain of the current
2028 // class template. For example, given
2029 //
2030 // namespace ns {
2031 // template <class> bool Param = false;
2032 // template <class T> struct N;
2033 // }
2034 //
2035 // template <class Param> struct ns::N { void foo(Param); };
2036 //
2037 // When we reference Param inside the function parameter list, our name lookup
2038 // chain for it should be like:
2039 // FunctionScope foo
2040 // -> RecordScope N
2041 // -> TemplateParamScope (where we will find Param)
2042 // -> NamespaceScope ns
2043 //
2044 // See also CppLookupName().
2045 if (S->isTemplateParamScope())
2046 EnterTemplatedContext(S, SemanticContext);
2047
2048 NamedDecl *PrevDecl = nullptr;
2049 if (Previous.begin() != Previous.end())
2050 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2051
2052 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2053 // Maybe we will complain about the shadowed template parameter.
2054 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2055 // Just pretend that we didn't see the previous declaration.
2056 PrevDecl = nullptr;
2057 }
2058
2059 // If there is a previous declaration with the same name, check
2060 // whether this is a valid redeclaration.
2061 ClassTemplateDecl *PrevClassTemplate =
2062 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2063
2064 // We may have found the injected-class-name of a class template,
2065 // class template partial specialization, or class template specialization.
2066 // In these cases, grab the template that is being defined or specialized.
2067 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2068 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2069 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2070 PrevClassTemplate
2071 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2072 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2073 PrevClassTemplate
2075 ->getSpecializedTemplate();
2076 }
2077 }
2078
2079 if (TUK == TagUseKind::Friend) {
2080 // C++ [namespace.memdef]p3:
2081 // [...] When looking for a prior declaration of a class or a function
2082 // declared as a friend, and when the name of the friend class or
2083 // function is neither a qualified name nor a template-id, scopes outside
2084 // the innermost enclosing namespace scope are not considered.
2085 if (!SS.isSet()) {
2086 DeclContext *OutermostContext = CurContext;
2087 while (!OutermostContext->isFileContext())
2088 OutermostContext = OutermostContext->getLookupParent();
2089
2090 if (PrevDecl &&
2091 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2092 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2093 SemanticContext = PrevDecl->getDeclContext();
2094 } else {
2095 // Declarations in outer scopes don't matter. However, the outermost
2096 // context we computed is the semantic context for our new
2097 // declaration.
2098 PrevDecl = PrevClassTemplate = nullptr;
2099 SemanticContext = OutermostContext;
2100
2101 // Check that the chosen semantic context doesn't already contain a
2102 // declaration of this name as a non-tag type.
2104 DeclContext *LookupContext = SemanticContext;
2105 while (LookupContext->isTransparentContext())
2106 LookupContext = LookupContext->getLookupParent();
2107 LookupQualifiedName(Previous, LookupContext);
2108
2109 if (Previous.isAmbiguous())
2110 return true;
2111
2112 if (Previous.begin() != Previous.end())
2113 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2114 }
2115 }
2116 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2117 SemanticContext, S, SS.isValid()))
2118 PrevDecl = PrevClassTemplate = nullptr;
2119
2120 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2121 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2122 if (SS.isEmpty() &&
2123 !(PrevClassTemplate &&
2124 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2125 SemanticContext->getRedeclContext()))) {
2126 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2127 Diag(Shadow->getTargetDecl()->getLocation(),
2128 diag::note_using_decl_target);
2129 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2130 // Recover by ignoring the old declaration.
2131 PrevDecl = PrevClassTemplate = nullptr;
2132 }
2133 }
2134
2135 if (PrevClassTemplate) {
2136 // Ensure that the template parameter lists are compatible. Skip this check
2137 // for a friend in a dependent context: the template parameter list itself
2138 // could be dependent.
2139 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2141 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2142 : CurContext,
2143 CurContext, KWLoc),
2144 TemplateParams, PrevClassTemplate,
2145 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2147 return true;
2148
2149 // C++ [temp.class]p4:
2150 // In a redeclaration, partial specialization, explicit
2151 // specialization or explicit instantiation of a class template,
2152 // the class-key shall agree in kind with the original class
2153 // template declaration (7.1.5.3).
2154 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2156 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2157 Diag(KWLoc, diag::err_use_with_wrong_tag)
2158 << Name
2159 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2160 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2161 Kind = PrevRecordDecl->getTagKind();
2162 }
2163
2164 // Check for redefinition of this class template.
2165 if (TUK == TagUseKind::Definition) {
2166 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2167 // If we have a prior definition that is not visible, treat this as
2168 // simply making that previous definition visible.
2169 NamedDecl *Hidden = nullptr;
2170 bool HiddenDefVisible = false;
2171 if (SkipBody &&
2172 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2173 SkipBody->ShouldSkip = true;
2174 SkipBody->Previous = Def;
2175 if (!HiddenDefVisible && Hidden) {
2176 auto *Tmpl =
2177 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2178 assert(Tmpl && "original definition of a class template is not a "
2179 "class template?");
2182 }
2183 } else {
2184 Diag(NameLoc, diag::err_redefinition) << Name;
2185 Diag(Def->getLocation(), diag::note_previous_definition);
2186 // FIXME: Would it make sense to try to "forget" the previous
2187 // definition, as part of error recovery?
2188 return true;
2189 }
2190 }
2191 }
2192 } else if (PrevDecl) {
2193 // C++ [temp]p5:
2194 // A class template shall not have the same name as any other
2195 // template, class, function, object, enumeration, enumerator,
2196 // namespace, or type in the same scope (3.3), except as specified
2197 // in (14.5.4).
2198 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2199 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2200 return true;
2201 }
2202
2203 // Check the template parameter list of this declaration, possibly
2204 // merging in the template parameter list from the previous class
2205 // template declaration. Skip this check for a friend in a dependent
2206 // context, because the template parameter list might be dependent.
2207 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2209 TemplateParams,
2210 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2211 : nullptr,
2212 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2213 SemanticContext->isDependentContext())
2216 : TPC_Other,
2217 SkipBody))
2218 Invalid = true;
2219
2220 if (SS.isSet()) {
2221 // If the name of the template was qualified, we must be defining the
2222 // template out-of-line.
2223 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2224 return Diag(NameLoc, TUK == TagUseKind::Friend
2225 ? diag::err_friend_decl_does_not_match
2226 : diag::err_member_decl_does_not_match)
2227 << Name << SemanticContext << /*IsDefinition*/ true
2228 << SS.getRange();
2229 }
2230
2231 // If this is a templated friend in a dependent context we should not put it
2232 // on the redecl chain. In some cases, the templated friend can be the most
2233 // recent declaration tricking the template instantiator to make substitutions
2234 // there.
2235 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2236 bool ShouldAddRedecl =
2237 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2238
2240 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2241 PrevClassTemplate && ShouldAddRedecl
2242 ? PrevClassTemplate->getTemplatedDecl()
2243 : nullptr);
2244 SetNestedNameSpecifier(*this, NewClass, SS);
2245 if (NumOuterTemplateParamLists > 0)
2247 Context,
2248 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2249
2250 // Add alignment attributes if necessary; these attributes are checked when
2251 // the ASTContext lays out the structure.
2252 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2253 if (LangOpts.HLSL)
2254 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2257 }
2258
2259 ClassTemplateDecl *NewTemplate
2260 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2261 DeclarationName(Name), TemplateParams,
2262 NewClass);
2263
2264 if (ShouldAddRedecl)
2265 NewTemplate->setPreviousDecl(PrevClassTemplate);
2266
2267 NewClass->setDescribedClassTemplate(NewTemplate);
2268
2269 if (ModulePrivateLoc.isValid())
2270 NewTemplate->setModulePrivate();
2271
2272 if (IsMemberSpecialization) {
2273 assert(PrevClassTemplate &&
2274 "Member specialization without a primary template?");
2275 NewTemplate->setMemberSpecialization();
2276 }
2277
2278 // Set the access specifier.
2279 if (!Invalid && TUK != TagUseKind::Friend &&
2280 NewTemplate->getDeclContext()->isRecord())
2281 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2282
2283 // Set the lexical context of these templates
2285 NewTemplate->setLexicalDeclContext(CurContext);
2286
2287 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2288 NewClass->startDefinition();
2289
2290 ProcessDeclAttributeList(S, NewClass, Attr);
2291
2292 if (PrevClassTemplate)
2293 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2294
2298
2299 if (TUK != TagUseKind::Friend) {
2300 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2301 Scope *Outer = S;
2302 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2303 Outer = Outer->getParent();
2304 PushOnScopeChains(NewTemplate, Outer);
2305 } else {
2306 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2307 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2308 NewClass->setAccess(PrevClassTemplate->getAccess());
2309 }
2310
2311 NewTemplate->setObjectOfFriendDecl();
2312
2313 // Friend templates are visible in fairly strange ways.
2314 if (!CurContext->isDependentContext()) {
2315 DeclContext *DC = SemanticContext->getRedeclContext();
2316 DC->makeDeclVisibleInContext(NewTemplate);
2317 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2318 PushOnScopeChains(NewTemplate, EnclosingScope,
2319 /* AddToContext = */ false);
2320 }
2321
2323 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2324 Friend->setAccess(AS_public);
2325 CurContext->addDecl(Friend);
2326 }
2327
2328 if (PrevClassTemplate)
2329 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2330
2331 if (Invalid) {
2332 NewTemplate->setInvalidDecl();
2333 NewClass->setInvalidDecl();
2334 }
2335
2336 ActOnDocumentableDecl(NewTemplate);
2337
2338 if (SkipBody && SkipBody->ShouldSkip)
2339 return SkipBody->Previous;
2340
2341 return NewTemplate;
2342}
2343
2344/// Diagnose the presence of a default template argument on a
2345/// template parameter, which is ill-formed in certain contexts.
2346///
2347/// \returns true if the default template argument should be dropped.
2350 SourceLocation ParamLoc,
2351 SourceRange DefArgRange) {
2352 switch (TPC) {
2353 case Sema::TPC_Other:
2355 return false;
2356
2359 // C++ [temp.param]p9:
2360 // A default template-argument shall not be specified in a
2361 // function template declaration or a function template
2362 // definition [...]
2363 // If a friend function template declaration specifies a default
2364 // template-argument, that declaration shall be a definition and shall be
2365 // the only declaration of the function template in the translation unit.
2366 // (C++98/03 doesn't have this wording; see DR226).
2367 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2368 << DefArgRange;
2369 return false;
2370
2372 // C++0x [temp.param]p9:
2373 // A default template-argument shall not be specified in the
2374 // template-parameter-lists of the definition of a member of a
2375 // class template that appears outside of the member's class.
2376 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2377 << DefArgRange;
2378 return true;
2379
2382 // C++ [temp.param]p9:
2383 // A default template-argument shall not be specified in a
2384 // friend template declaration.
2385 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2386 << DefArgRange;
2387 return true;
2388
2389 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2390 // for friend function templates if there is only a single
2391 // declaration (and it is a definition). Strange!
2392 }
2393
2394 llvm_unreachable("Invalid TemplateParamListContext!");
2395}
2396
2397/// Check for unexpanded parameter packs within the template parameters
2398/// of a template template parameter, recursively.
2401 // A template template parameter which is a parameter pack is also a pack
2402 // expansion.
2403 if (TTP->isParameterPack())
2404 return false;
2405
2407 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2408 NamedDecl *P = Params->getParam(I);
2409 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2410 if (!TTP->isParameterPack())
2411 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2412 if (TC->hasExplicitTemplateArgs())
2413 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2416 return true;
2417 continue;
2418 }
2419
2420 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2421 if (!NTTP->isParameterPack() &&
2422 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2423 NTTP->getTypeSourceInfo(),
2425 return true;
2426
2427 continue;
2428 }
2429
2430 if (TemplateTemplateParmDecl *InnerTTP
2431 = dyn_cast<TemplateTemplateParmDecl>(P))
2432 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2433 return true;
2434 }
2435
2436 return false;
2437}
2438
2440 TemplateParameterList *OldParams,
2442 SkipBodyInfo *SkipBody) {
2443 bool Invalid = false;
2444
2445 // C++ [temp.param]p10:
2446 // The set of default template-arguments available for use with a
2447 // template declaration or definition is obtained by merging the
2448 // default arguments from the definition (if in scope) and all
2449 // declarations in scope in the same way default function
2450 // arguments are (8.3.6).
2451 bool SawDefaultArgument = false;
2452 SourceLocation PreviousDefaultArgLoc;
2453
2454 // Dummy initialization to avoid warnings.
2455 TemplateParameterList::iterator OldParam = NewParams->end();
2456 if (OldParams)
2457 OldParam = OldParams->begin();
2458
2459 bool RemoveDefaultArguments = false;
2460 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2461 NewParamEnd = NewParams->end();
2462 NewParam != NewParamEnd; ++NewParam) {
2463 // Whether we've seen a duplicate default argument in the same translation
2464 // unit.
2465 bool RedundantDefaultArg = false;
2466 // Whether we've found inconsis inconsitent default arguments in different
2467 // translation unit.
2468 bool InconsistentDefaultArg = false;
2469 // The name of the module which contains the inconsistent default argument.
2470 std::string PrevModuleName;
2471
2472 SourceLocation OldDefaultLoc;
2473 SourceLocation NewDefaultLoc;
2474
2475 // Variable used to diagnose missing default arguments
2476 bool MissingDefaultArg = false;
2477
2478 // Variable used to diagnose non-final parameter packs
2479 bool SawParameterPack = false;
2480
2481 if (TemplateTypeParmDecl *NewTypeParm
2482 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2483 // Check the presence of a default argument here.
2484 if (NewTypeParm->hasDefaultArgument() &&
2486 *this, TPC, NewTypeParm->getLocation(),
2487 NewTypeParm->getDefaultArgument().getSourceRange()))
2488 NewTypeParm->removeDefaultArgument();
2489
2490 // Merge default arguments for template type parameters.
2491 TemplateTypeParmDecl *OldTypeParm
2492 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2493 if (NewTypeParm->isParameterPack()) {
2494 assert(!NewTypeParm->hasDefaultArgument() &&
2495 "Parameter packs can't have a default argument!");
2496 SawParameterPack = true;
2497 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2498 NewTypeParm->hasDefaultArgument() &&
2499 (!SkipBody || !SkipBody->ShouldSkip)) {
2500 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2501 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2502 SawDefaultArgument = true;
2503
2504 if (!OldTypeParm->getOwningModule())
2505 RedundantDefaultArg = true;
2506 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2507 NewTypeParm)) {
2508 InconsistentDefaultArg = true;
2509 PrevModuleName =
2511 }
2512 PreviousDefaultArgLoc = NewDefaultLoc;
2513 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2514 // Merge the default argument from the old declaration to the
2515 // new declaration.
2516 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2517 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2518 } else if (NewTypeParm->hasDefaultArgument()) {
2519 SawDefaultArgument = true;
2520 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2521 } else if (SawDefaultArgument)
2522 MissingDefaultArg = true;
2523 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2524 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2525 // Check for unexpanded parameter packs, except in a template template
2526 // parameter pack, as in those any unexpanded packs should be expanded
2527 // along with the parameter itself.
2529 !NewNonTypeParm->isParameterPack() &&
2530 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2531 NewNonTypeParm->getTypeSourceInfo(),
2533 Invalid = true;
2534 continue;
2535 }
2536
2537 // Check the presence of a default argument here.
2538 if (NewNonTypeParm->hasDefaultArgument() &&
2540 *this, TPC, NewNonTypeParm->getLocation(),
2541 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2542 NewNonTypeParm->removeDefaultArgument();
2543 }
2544
2545 // Merge default arguments for non-type template parameters
2546 NonTypeTemplateParmDecl *OldNonTypeParm
2547 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2548 if (NewNonTypeParm->isParameterPack()) {
2549 assert(!NewNonTypeParm->hasDefaultArgument() &&
2550 "Parameter packs can't have a default argument!");
2551 if (!NewNonTypeParm->isPackExpansion())
2552 SawParameterPack = true;
2553 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2554 NewNonTypeParm->hasDefaultArgument() &&
2555 (!SkipBody || !SkipBody->ShouldSkip)) {
2556 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2557 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2558 SawDefaultArgument = true;
2559 if (!OldNonTypeParm->getOwningModule())
2560 RedundantDefaultArg = true;
2561 else if (!getASTContext().isSameDefaultTemplateArgument(
2562 OldNonTypeParm, NewNonTypeParm)) {
2563 InconsistentDefaultArg = true;
2564 PrevModuleName =
2565 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2566 }
2567 PreviousDefaultArgLoc = NewDefaultLoc;
2568 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2569 // Merge the default argument from the old declaration to the
2570 // new declaration.
2571 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2572 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2573 } else if (NewNonTypeParm->hasDefaultArgument()) {
2574 SawDefaultArgument = true;
2575 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2576 } else if (SawDefaultArgument)
2577 MissingDefaultArg = true;
2578 } else {
2579 TemplateTemplateParmDecl *NewTemplateParm
2580 = cast<TemplateTemplateParmDecl>(*NewParam);
2581
2582 // Check for unexpanded parameter packs, recursively.
2583 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2584 Invalid = true;
2585 continue;
2586 }
2587
2588 // Check the presence of a default argument here.
2589 if (NewTemplateParm->hasDefaultArgument() &&
2591 NewTemplateParm->getLocation(),
2592 NewTemplateParm->getDefaultArgument().getSourceRange()))
2593 NewTemplateParm->removeDefaultArgument();
2594
2595 // Merge default arguments for template template parameters
2596 TemplateTemplateParmDecl *OldTemplateParm
2597 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2598 if (NewTemplateParm->isParameterPack()) {
2599 assert(!NewTemplateParm->hasDefaultArgument() &&
2600 "Parameter packs can't have a default argument!");
2601 if (!NewTemplateParm->isPackExpansion())
2602 SawParameterPack = true;
2603 } else if (OldTemplateParm &&
2604 hasVisibleDefaultArgument(OldTemplateParm) &&
2605 NewTemplateParm->hasDefaultArgument() &&
2606 (!SkipBody || !SkipBody->ShouldSkip)) {
2607 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2608 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2609 SawDefaultArgument = true;
2610 if (!OldTemplateParm->getOwningModule())
2611 RedundantDefaultArg = true;
2612 else if (!getASTContext().isSameDefaultTemplateArgument(
2613 OldTemplateParm, NewTemplateParm)) {
2614 InconsistentDefaultArg = true;
2615 PrevModuleName =
2616 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2617 }
2618 PreviousDefaultArgLoc = NewDefaultLoc;
2619 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2620 // Merge the default argument from the old declaration to the
2621 // new declaration.
2622 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2623 PreviousDefaultArgLoc
2624 = OldTemplateParm->getDefaultArgument().getLocation();
2625 } else if (NewTemplateParm->hasDefaultArgument()) {
2626 SawDefaultArgument = true;
2627 PreviousDefaultArgLoc
2628 = NewTemplateParm->getDefaultArgument().getLocation();
2629 } else if (SawDefaultArgument)
2630 MissingDefaultArg = true;
2631 }
2632
2633 // C++11 [temp.param]p11:
2634 // If a template parameter of a primary class template or alias template
2635 // is a template parameter pack, it shall be the last template parameter.
2636 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2637 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2638 Diag((*NewParam)->getLocation(),
2639 diag::err_template_param_pack_must_be_last_template_parameter);
2640 Invalid = true;
2641 }
2642
2643 // [basic.def.odr]/13:
2644 // There can be more than one definition of a
2645 // ...
2646 // default template argument
2647 // ...
2648 // in a program provided that each definition appears in a different
2649 // translation unit and the definitions satisfy the [same-meaning
2650 // criteria of the ODR].
2651 //
2652 // Simply, the design of modules allows the definition of template default
2653 // argument to be repeated across translation unit. Note that the ODR is
2654 // checked elsewhere. But it is still not allowed to repeat template default
2655 // argument in the same translation unit.
2656 if (RedundantDefaultArg) {
2657 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2658 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2659 Invalid = true;
2660 } else if (InconsistentDefaultArg) {
2661 // We could only diagnose about the case that the OldParam is imported.
2662 // The case NewParam is imported should be handled in ASTReader.
2663 Diag(NewDefaultLoc,
2664 diag::err_template_param_default_arg_inconsistent_redefinition);
2665 Diag(OldDefaultLoc,
2666 diag::note_template_param_prev_default_arg_in_other_module)
2667 << PrevModuleName;
2668 Invalid = true;
2669 } else if (MissingDefaultArg &&
2670 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2671 TPC == TPC_FriendClassTemplate)) {
2672 // C++ 23[temp.param]p14:
2673 // If a template-parameter of a class template, variable template, or
2674 // alias template has a default template argument, each subsequent
2675 // template-parameter shall either have a default template argument
2676 // supplied or be a template parameter pack.
2677 Diag((*NewParam)->getLocation(),
2678 diag::err_template_param_default_arg_missing);
2679 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2680 Invalid = true;
2681 RemoveDefaultArguments = true;
2682 }
2683
2684 // If we have an old template parameter list that we're merging
2685 // in, move on to the next parameter.
2686 if (OldParams)
2687 ++OldParam;
2688 }
2689
2690 // We were missing some default arguments at the end of the list, so remove
2691 // all of the default arguments.
2692 if (RemoveDefaultArguments) {
2693 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2694 NewParamEnd = NewParams->end();
2695 NewParam != NewParamEnd; ++NewParam) {
2696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2697 TTP->removeDefaultArgument();
2698 else if (NonTypeTemplateParmDecl *NTTP
2699 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2700 NTTP->removeDefaultArgument();
2701 else
2702 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2703 }
2704 }
2705
2706 return Invalid;
2707}
2708
2709namespace {
2710
2711/// A class which looks for a use of a certain level of template
2712/// parameter.
2713struct DependencyChecker : DynamicRecursiveASTVisitor {
2714 unsigned Depth;
2715
2716 // Whether we're looking for a use of a template parameter that makes the
2717 // overall construct type-dependent / a dependent type. This is strictly
2718 // best-effort for now; we may fail to match at all for a dependent type
2719 // in some cases if this is set.
2720 bool IgnoreNonTypeDependent;
2721
2722 bool Match;
2723 SourceLocation MatchLoc;
2724
2725 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2726 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2727 Match(false) {}
2728
2729 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2730 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2731 NamedDecl *ND = Params->getParam(0);
2732 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2733 Depth = PD->getDepth();
2734 } else if (NonTypeTemplateParmDecl *PD =
2735 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2736 Depth = PD->getDepth();
2737 } else {
2738 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2739 }
2740 }
2741
2742 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2743 if (ParmDepth >= Depth) {
2744 Match = true;
2745 MatchLoc = Loc;
2746 return true;
2747 }
2748 return false;
2749 }
2750
2751 bool TraverseStmt(Stmt *S) override {
2752 // Prune out non-type-dependent expressions if requested. This can
2753 // sometimes result in us failing to find a template parameter reference
2754 // (if a value-dependent expression creates a dependent type), but this
2755 // mode is best-effort only.
2756 if (auto *E = dyn_cast_or_null<Expr>(S))
2757 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2758 return true;
2760 }
2761
2762 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2763 if (IgnoreNonTypeDependent && !TL.isNull() &&
2764 !TL.getType()->isDependentType())
2765 return true;
2766 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2767 }
2768
2769 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2770 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2771 }
2772
2773 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2774 // For a best-effort search, keep looking until we find a location.
2775 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2776 }
2777
2778 bool TraverseTemplateName(TemplateName N) override {
2779 if (TemplateTemplateParmDecl *PD =
2780 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2781 if (Matches(PD->getDepth()))
2782 return false;
2784 }
2785
2786 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2787 if (NonTypeTemplateParmDecl *PD =
2788 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2789 if (Matches(PD->getDepth(), E->getExprLoc()))
2790 return false;
2791 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2792 }
2793
2794 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2795 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2796 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2797 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2798 return false;
2799 }
2800 for (auto &TLoc : ULE->template_arguments())
2802 }
2803 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2804 }
2805
2806 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2807 return TraverseType(T->getReplacementType());
2808 }
2809
2810 bool VisitSubstTemplateTypeParmPackType(
2811 SubstTemplateTypeParmPackType *T) override {
2812 return TraverseTemplateArgument(T->getArgumentPack());
2813 }
2814
2815 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2816 bool TraverseQualifier) override {
2817 // An InjectedClassNameType will never have a dependent template name,
2818 // so no need to traverse it.
2819 return TraverseTemplateArguments(
2820 T->getTemplateArgs(T->getDecl()->getASTContext()));
2821 }
2822};
2823} // end anonymous namespace
2824
2825/// Determines whether a given type depends on the given parameter
2826/// list.
2827static bool
2829 if (!Params->size())
2830 return false;
2831
2832 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2833 Checker.TraverseType(T);
2834 return Checker.Match;
2835}
2836
2837// Find the source range corresponding to the named type in the given
2838// nested-name-specifier, if any.
2840 QualType T,
2841 const CXXScopeSpec &SS) {
2843 for (;;) {
2846 break;
2847 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2848 return NNSLoc.castAsTypeLoc().getSourceRange();
2849 // FIXME: This will always be empty.
2850 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2851 }
2852
2853 return SourceRange();
2854}
2855
2857 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2858 TemplateIdAnnotation *TemplateId,
2859 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2860 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2861 IsMemberSpecialization = false;
2862 Invalid = false;
2863
2864 // The sequence of nested types to which we will match up the template
2865 // parameter lists. We first build this list by starting with the type named
2866 // by the nested-name-specifier and walking out until we run out of types.
2867 SmallVector<QualType, 4> NestedTypes;
2868 QualType T;
2869 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2870 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2871 if (CXXRecordDecl *Record =
2872 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2873 T = Context.getCanonicalTagType(Record);
2874 else
2875 T = QualType(Qualifier.getAsType(), 0);
2876 }
2877
2878 // If we found an explicit specialization that prevents us from needing
2879 // 'template<>' headers, this will be set to the location of that
2880 // explicit specialization.
2881 SourceLocation ExplicitSpecLoc;
2882
2883 while (!T.isNull()) {
2884 NestedTypes.push_back(T);
2885
2886 // Retrieve the parent of a record type.
2887 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2888 // If this type is an explicit specialization, we're done.
2890 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2892 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2893 ExplicitSpecLoc = Spec->getLocation();
2894 break;
2895 }
2896 } else if (Record->getTemplateSpecializationKind()
2898 ExplicitSpecLoc = Record->getLocation();
2899 break;
2900 }
2901
2902 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2903 T = Context.getTypeDeclType(Parent);
2904 else
2905 T = QualType();
2906 continue;
2907 }
2908
2909 if (const TemplateSpecializationType *TST
2910 = T->getAs<TemplateSpecializationType>()) {
2911 TemplateName Name = TST->getTemplateName();
2912 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2913 // Look one step prior in a dependent template specialization type.
2914 if (NestedNameSpecifier NNS = DTS->getQualifier();
2916 T = QualType(NNS.getAsType(), 0);
2917 else
2918 T = QualType();
2919 continue;
2920 }
2921 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2922 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2923 T = Context.getTypeDeclType(Parent);
2924 else
2925 T = QualType();
2926 continue;
2927 }
2928 }
2929
2930 // Look one step prior in a dependent name type.
2931 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2932 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2934 T = QualType(NNS.getAsType(), 0);
2935 else
2936 T = QualType();
2937 continue;
2938 }
2939
2940 // Retrieve the parent of an enumeration type.
2941 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2942 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2943 // check here.
2944 EnumDecl *Enum = EnumT->getDecl();
2945
2946 // Get to the parent type.
2947 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2948 T = Context.getCanonicalTypeDeclType(Parent);
2949 else
2950 T = QualType();
2951 continue;
2952 }
2953
2954 T = QualType();
2955 }
2956 // Reverse the nested types list, since we want to traverse from the outermost
2957 // to the innermost while checking template-parameter-lists.
2958 std::reverse(NestedTypes.begin(), NestedTypes.end());
2959
2960 // C++0x [temp.expl.spec]p17:
2961 // A member or a member template may be nested within many
2962 // enclosing class templates. In an explicit specialization for
2963 // such a member, the member declaration shall be preceded by a
2964 // template<> for each enclosing class template that is
2965 // explicitly specialized.
2966 bool SawNonEmptyTemplateParameterList = false;
2967
2968 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2969 if (SawNonEmptyTemplateParameterList) {
2970 if (!SuppressDiagnostic)
2971 Diag(DeclLoc, diag::err_specialize_member_of_template)
2972 << !Recovery << Range;
2973 Invalid = true;
2974 IsMemberSpecialization = false;
2975 return true;
2976 }
2977
2978 return false;
2979 };
2980
2981 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2982 // Check that we can have an explicit specialization here.
2983 if (CheckExplicitSpecialization(Range, true))
2984 return true;
2985
2986 // We don't have a template header, but we should.
2987 SourceLocation ExpectedTemplateLoc;
2988 if (!ParamLists.empty())
2989 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2990 else
2991 ExpectedTemplateLoc = DeclStartLoc;
2992
2993 if (!SuppressDiagnostic)
2994 Diag(DeclLoc, diag::err_template_spec_needs_header)
2995 << Range
2996 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2997 return false;
2998 };
2999
3000 unsigned ParamIdx = 0;
3001 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3002 ++TypeIdx) {
3003 T = NestedTypes[TypeIdx];
3004
3005 // Whether we expect a 'template<>' header.
3006 bool NeedEmptyTemplateHeader = false;
3007
3008 // Whether we expect a template header with parameters.
3009 bool NeedNonemptyTemplateHeader = false;
3010
3011 // For a dependent type, the set of template parameters that we
3012 // expect to see.
3013 TemplateParameterList *ExpectedTemplateParams = nullptr;
3014
3015 // C++0x [temp.expl.spec]p15:
3016 // A member or a member template may be nested within many enclosing
3017 // class templates. In an explicit specialization for such a member, the
3018 // member declaration shall be preceded by a template<> for each
3019 // enclosing class template that is explicitly specialized.
3020 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3022 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3023 ExpectedTemplateParams = Partial->getTemplateParameters();
3024 NeedNonemptyTemplateHeader = true;
3025 } else if (Record->isDependentType()) {
3026 if (Record->getDescribedClassTemplate()) {
3027 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3028 ->getTemplateParameters();
3029 NeedNonemptyTemplateHeader = true;
3030 }
3031 } else if (ClassTemplateSpecializationDecl *Spec
3032 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3033 // C++0x [temp.expl.spec]p4:
3034 // Members of an explicitly specialized class template are defined
3035 // in the same manner as members of normal classes, and not using
3036 // the template<> syntax.
3037 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3038 NeedEmptyTemplateHeader = true;
3039 else
3040 continue;
3041 } else if (Record->getTemplateSpecializationKind()) {
3042 if (Record->getTemplateSpecializationKind()
3044 TypeIdx == NumTypes - 1)
3045 IsMemberSpecialization = true;
3046
3047 continue;
3048 }
3049 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3050 TemplateName Name = TST->getTemplateName();
3051 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3052 ExpectedTemplateParams = Template->getTemplateParameters();
3053 NeedNonemptyTemplateHeader = true;
3054 } else if (Name.getAsDeducedTemplateName()) {
3055 // FIXME: We actually could/should check the template arguments here
3056 // against the corresponding template parameter list.
3057 NeedNonemptyTemplateHeader = false;
3058 }
3059 }
3060
3061 // C++ [temp.expl.spec]p16:
3062 // In an explicit specialization declaration for a member of a class
3063 // template or a member template that appears in namespace scope, the
3064 // member template and some of its enclosing class templates may remain
3065 // unspecialized, except that the declaration shall not explicitly
3066 // specialize a class member template if its enclosing class templates
3067 // are not explicitly specialized as well.
3068 if (ParamIdx < ParamLists.size()) {
3069 if (ParamLists[ParamIdx]->size() == 0) {
3070 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3071 false))
3072 return nullptr;
3073 } else
3074 SawNonEmptyTemplateParameterList = true;
3075 }
3076
3077 if (NeedEmptyTemplateHeader) {
3078 // If we're on the last of the types, and we need a 'template<>' header
3079 // here, then it's a member specialization.
3080 if (TypeIdx == NumTypes - 1)
3081 IsMemberSpecialization = true;
3082
3083 if (ParamIdx < ParamLists.size()) {
3084 if (ParamLists[ParamIdx]->size() > 0) {
3085 // The header has template parameters when it shouldn't. Complain.
3086 if (!SuppressDiagnostic)
3087 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3088 diag::err_template_param_list_matches_nontemplate)
3089 << T
3090 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3091 ParamLists[ParamIdx]->getRAngleLoc())
3093 Invalid = true;
3094 return nullptr;
3095 }
3096
3097 // Consume this template header.
3098 ++ParamIdx;
3099 continue;
3100 }
3101
3102 if (!IsFriend)
3103 if (DiagnoseMissingExplicitSpecialization(
3105 return nullptr;
3106
3107 continue;
3108 }
3109
3110 if (NeedNonemptyTemplateHeader) {
3111 // In friend declarations we can have template-ids which don't
3112 // depend on the corresponding template parameter lists. But
3113 // assume that empty parameter lists are supposed to match this
3114 // template-id.
3115 if (IsFriend && T->isDependentType()) {
3116 if (ParamIdx < ParamLists.size() &&
3117 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3118 ExpectedTemplateParams = nullptr;
3119 else
3120 continue;
3121 }
3122
3123 if (ParamIdx < ParamLists.size()) {
3124 // Check the template parameter list, if we can.
3125 if (ExpectedTemplateParams &&
3127 ExpectedTemplateParams,
3128 !SuppressDiagnostic, TPL_TemplateMatch))
3129 Invalid = true;
3130
3131 if (!Invalid &&
3132 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3134 Invalid = true;
3135
3136 ++ParamIdx;
3137 continue;
3138 }
3139
3140 if (!SuppressDiagnostic)
3141 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3142 << T
3144 Invalid = true;
3145 continue;
3146 }
3147 }
3148
3149 // If there were at least as many template-ids as there were template
3150 // parameter lists, then there are no template parameter lists remaining for
3151 // the declaration itself.
3152 if (ParamIdx >= ParamLists.size()) {
3153 if (TemplateId && !IsFriend) {
3154 // We don't have a template header for the declaration itself, but we
3155 // should.
3156 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3157 TemplateId->RAngleLoc));
3158
3159 // Fabricate an empty template parameter list for the invented header.
3161 SourceLocation(), {},
3162 SourceLocation(), nullptr);
3163 }
3164
3165 return nullptr;
3166 }
3167
3168 // If there were too many template parameter lists, complain about that now.
3169 if (ParamIdx < ParamLists.size() - 1) {
3170 bool HasAnyExplicitSpecHeader = false;
3171 bool AllExplicitSpecHeaders = true;
3172 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3173 if (ParamLists[I]->size() == 0)
3174 HasAnyExplicitSpecHeader = true;
3175 else
3176 AllExplicitSpecHeaders = false;
3177 }
3178
3179 if (!SuppressDiagnostic)
3180 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3181 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3182 : diag::err_template_spec_extra_headers)
3183 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3184 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3185
3186 // If there was a specialization somewhere, such that 'template<>' is
3187 // not required, and there were any 'template<>' headers, note where the
3188 // specialization occurred.
3189 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3190 !SuppressDiagnostic)
3191 Diag(ExplicitSpecLoc,
3192 diag::note_explicit_template_spec_does_not_need_header)
3193 << NestedTypes.back();
3194
3195 // We have a template parameter list with no corresponding scope, which
3196 // means that the resulting template declaration can't be instantiated
3197 // properly (we'll end up with dependent nodes when we shouldn't).
3198 if (!AllExplicitSpecHeaders)
3199 Invalid = true;
3200 }
3201
3202 // C++ [temp.expl.spec]p16:
3203 // In an explicit specialization declaration for a member of a class
3204 // template or a member template that ap- pears in namespace scope, the
3205 // member template and some of its enclosing class templates may remain
3206 // unspecialized, except that the declaration shall not explicitly
3207 // specialize a class member template if its en- closing class templates
3208 // are not explicitly specialized as well.
3209 if (ParamLists.back()->size() == 0 &&
3210 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3211 false))
3212 return nullptr;
3213
3214 // Return the last template parameter list, which corresponds to the
3215 // entity being declared.
3216 return ParamLists.back();
3217}
3218
3220 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3221 Diag(Template->getLocation(), diag::note_template_declared_here)
3223 ? 0
3225 ? 1
3227 ? 2
3229 << Template->getDeclName();
3230 return;
3231 }
3232
3234 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3235 IEnd = OST->end();
3236 I != IEnd; ++I)
3237 Diag((*I)->getLocation(), diag::note_template_declared_here)
3238 << 0 << (*I)->getDeclName();
3239
3240 return;
3241 }
3242}
3243
3245 TemplateName BaseTemplate,
3246 SourceLocation TemplateLoc,
3248 auto lookUpCommonType = [&](TemplateArgument T1,
3249 TemplateArgument T2) -> QualType {
3250 // Don't bother looking for other specializations if both types are
3251 // builtins - users aren't allowed to specialize for them
3252 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3253 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3254 {T1, T2});
3255
3259 Args.addArgument(TemplateArgumentLoc(
3260 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3261
3262 EnterExpressionEvaluationContext UnevaluatedContext(
3264 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3266
3267 QualType BaseTemplateInst = S.CheckTemplateIdType(
3268 Keyword, BaseTemplate, TemplateLoc, Args,
3269 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3270
3271 if (SFINAE.hasErrorOccurred())
3272 return QualType();
3273
3274 return BaseTemplateInst;
3275 };
3276
3277 // Note A: For the common_type trait applied to a template parameter pack T of
3278 // types, the member type shall be either defined or not present as follows:
3279 switch (Ts.size()) {
3280
3281 // If sizeof...(T) is zero, there shall be no member type.
3282 case 0:
3283 return QualType();
3284
3285 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3286 // pack T. The member typedef-name type shall denote the same type, if any, as
3287 // common_type_t<T0, T0>; otherwise there shall be no member type.
3288 case 1:
3289 return lookUpCommonType(Ts[0], Ts[0]);
3290
3291 // If sizeof...(T) is two, let the first and second types constituting T be
3292 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3293 // as decay_t<T1> and decay_t<T2>, respectively.
3294 case 2: {
3295 QualType T1 = Ts[0].getAsType();
3296 QualType T2 = Ts[1].getAsType();
3297 QualType D1 = S.BuiltinDecay(T1, {});
3298 QualType D2 = S.BuiltinDecay(T2, {});
3299
3300 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3301 // the same type, if any, as common_type_t<D1, D2>.
3302 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3303 return lookUpCommonType(D1, D2);
3304
3305 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3306 // denotes a valid type, let C denote that type.
3307 {
3308 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3309 EnterExpressionEvaluationContext UnevaluatedContext(
3311 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3313
3314 // false
3316 VK_PRValue);
3317 ExprResult Cond = &CondExpr;
3318
3319 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3320 if (ConstRefQual) {
3321 D1.addConst();
3322 D2.addConst();
3323 }
3324
3325 // declval<D1>()
3326 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3327 ExprResult LHS = &LHSExpr;
3328
3329 // declval<D2>()
3330 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3331 ExprResult RHS = &RHSExpr;
3332
3335
3336 // decltype(false ? declval<D1>() : declval<D2>())
3338 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3339
3340 if (Result.isNull() || SFINAE.hasErrorOccurred())
3341 return QualType();
3342
3343 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3344 return S.BuiltinDecay(Result, TemplateLoc);
3345 };
3346
3347 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3348 return Res;
3349
3350 // Let:
3351 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3352 // COND-RES(X, Y) be
3353 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3354
3355 // C++20 only
3356 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3357 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3358 if (!S.Context.getLangOpts().CPlusPlus20)
3359 return QualType();
3360 return CheckConditionalOperands(true);
3361 }
3362 }
3363
3364 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3365 // denote the first, second, and (pack of) remaining types constituting T. Let
3366 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3367 // a type C, the member typedef-name type shall denote the same type, if any,
3368 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3369 default: {
3370 QualType Result = Ts.front().getAsType();
3371 for (auto T : llvm::drop_begin(Ts)) {
3372 Result = lookUpCommonType(Result, T.getAsType());
3373 if (Result.isNull())
3374 return QualType();
3375 }
3376 return Result;
3377 }
3378 }
3379}
3380
3381static bool isInVkNamespace(const RecordType *RT) {
3382 DeclContext *DC = RT->getDecl()->getDeclContext();
3383 if (!DC)
3384 return false;
3385
3386 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3387 if (!ND)
3388 return false;
3389
3390 return ND->getQualifiedNameAsString() == "hlsl::vk";
3391}
3392
3393static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3394 QualType OperandArg,
3395 SourceLocation Loc) {
3396 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3397 bool Literal = false;
3398 SourceLocation LiteralLoc;
3399 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3400 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3401 assert(SpecDecl);
3402
3403 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3404 QualType ConstantType = LiteralArgs[0].getAsType();
3405 RT = ConstantType->getAsCanonical<RecordType>();
3406 Literal = true;
3407 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3408 }
3409
3410 if (RT && isInVkNamespace(RT) &&
3411 RT->getDecl()->getName() == "integral_constant") {
3412 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3413 assert(SpecDecl);
3414
3415 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3416
3417 QualType ConstantType = ConstantArgs[0].getAsType();
3418 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3419
3420 if (Literal)
3421 return SpirvOperand::createLiteral(Value);
3422 return SpirvOperand::createConstant(ConstantType, Value);
3423 } else if (Literal) {
3424 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3425 return SpirvOperand();
3426 }
3427 }
3428 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3429 diag::err_call_incomplete_argument))
3430 return SpirvOperand();
3431 return SpirvOperand::createType(OperandArg);
3432}
3433
3436 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3437 TemplateArgumentListInfo &TemplateArgs) {
3438 ASTContext &Context = SemaRef.getASTContext();
3439
3440 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3441 "Builtin template arguments do not match its parameters");
3442
3443 switch (BTD->getBuiltinTemplateKind()) {
3444 case BTK__make_integer_seq: {
3445 // Specializations of __make_integer_seq<S, T, N> are treated like
3446 // S<T, 0, ..., N-1>.
3447
3448 QualType OrigType = Converted[1].getAsType();
3449 // C++14 [inteseq.intseq]p1:
3450 // T shall be an integer type.
3451 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3452 SemaRef.Diag(TemplateArgs[1].getLocation(),
3453 diag::err_integer_sequence_integral_element_type);
3454 return QualType();
3455 }
3456
3457 TemplateArgument NumArgsArg = Converted[2];
3458 if (NumArgsArg.isDependent())
3459 return QualType();
3460
3461 TemplateArgumentListInfo SyntheticTemplateArgs;
3462 // The type argument, wrapped in substitution sugar, gets reused as the
3463 // first template argument in the synthetic template argument list.
3464 SyntheticTemplateArgs.addArgument(
3467 OrigType, TemplateArgs[1].getLocation())));
3468
3469 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3470 // Expand N into 0 ... N-1.
3471 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3472 I < NumArgs; ++I) {
3473 TemplateArgument TA(Context, I, OrigType);
3474 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3475 TA, OrigType, TemplateArgs[2].getLocation()));
3476 }
3477 } else {
3478 // C++14 [inteseq.make]p1:
3479 // If N is negative the program is ill-formed.
3480 SemaRef.Diag(TemplateArgs[2].getLocation(),
3481 diag::err_integer_sequence_negative_length);
3482 return QualType();
3483 }
3484
3485 // The first template argument will be reused as the template decl that
3486 // our synthetic template arguments will be applied to.
3487 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3488 TemplateLoc, SyntheticTemplateArgs,
3489 /*Scope=*/nullptr,
3490 /*ForNestedNameSpecifier=*/false);
3491 }
3492
3493 case BTK__type_pack_element: {
3494 // Specializations of
3495 // __type_pack_element<Index, T_1, ..., T_N>
3496 // are treated like T_Index.
3497 assert(Converted.size() == 2 &&
3498 "__type_pack_element should be given an index and a parameter pack");
3499
3500 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3501 if (IndexArg.isDependent() || Ts.isDependent())
3502 return QualType();
3503
3504 llvm::APSInt Index = IndexArg.getAsIntegral();
3505 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3506 "type std::size_t, and hence be non-negative");
3507 // If the Index is out of bounds, the program is ill-formed.
3508 if (Index >= Ts.pack_size()) {
3509 SemaRef.Diag(TemplateArgs[0].getLocation(),
3510 diag::err_type_pack_element_out_of_bounds);
3511 return QualType();
3512 }
3513
3514 // We simply return the type at index `Index`.
3515 int64_t N = Index.getExtValue();
3516 return Ts.getPackAsArray()[N].getAsType();
3517 }
3518
3519 case BTK__builtin_common_type: {
3520 assert(Converted.size() == 4);
3521 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3522 return QualType();
3523
3524 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3525 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3526 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3527 TemplateLoc, Ts);
3528 !CT.isNull()) {
3532 CT, TemplateArgs[1].getLocation())));
3533 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3534 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3535 TAs, /*Scope=*/nullptr,
3536 /*ForNestedNameSpecifier=*/false);
3537 }
3538 QualType HasNoTypeMember = Converted[2].getAsType();
3539 return HasNoTypeMember;
3540 }
3541
3542 case BTK__hlsl_spirv_type: {
3543 assert(Converted.size() == 4);
3544
3545 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3546 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3547 }
3548
3549 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3550 return QualType();
3551
3552 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3553 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3554 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3555
3556 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3557
3559
3560 for (auto &OperandTA : OperandArgs) {
3561 QualType OperandArg = OperandTA.getAsType();
3562 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3563 TemplateArgs[3].getLocation());
3564 if (!Operand.isValid())
3565 return QualType();
3566 Operands.push_back(Operand);
3567 }
3568
3569 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3570 }
3571 case BTK__builtin_dedup_pack: {
3572 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3573 "a parameter pack");
3574 TemplateArgument Ts = Converted[0];
3575 // Delay the computation until we can compute the final result. We choose
3576 // not to remove the duplicates upfront before substitution to keep the code
3577 // simple.
3578 if (Ts.isDependent())
3579 return QualType();
3580 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3582 llvm::SmallDenseSet<QualType> Seen;
3583 // Synthesize a new template argument list, removing duplicates.
3584 for (auto T : Ts.getPackAsArray()) {
3585 assert(T.getKind() == clang::TemplateArgument::Type);
3586 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3587 continue;
3588 OutArgs.push_back(T);
3589 }
3590 return Context.getSubstBuiltinTemplatePack(
3591 TemplateArgument::CreatePackCopy(Context, OutArgs));
3592 }
3593 }
3594 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3595}
3596
3597/// Determine whether this alias template is "enable_if_t".
3598/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3600 return AliasTemplate->getName() == "enable_if_t" ||
3601 AliasTemplate->getName() == "__enable_if_t";
3602}
3603
3604/// Collect all of the separable terms in the given condition, which
3605/// might be a conjunction.
3606///
3607/// FIXME: The right answer is to convert the logical expression into
3608/// disjunctive normal form, so we can find the first failed term
3609/// within each possible clause.
3610static void collectConjunctionTerms(Expr *Clause,
3611 SmallVectorImpl<Expr *> &Terms) {
3612 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3613 if (BinOp->getOpcode() == BO_LAnd) {
3614 collectConjunctionTerms(BinOp->getLHS(), Terms);
3615 collectConjunctionTerms(BinOp->getRHS(), Terms);
3616 return;
3617 }
3618 }
3619
3620 Terms.push_back(Clause);
3621}
3622
3623// The ranges-v3 library uses an odd pattern of a top-level "||" with
3624// a left-hand side that is value-dependent but never true. Identify
3625// the idiom and ignore that term.
3627 // Top-level '||'.
3628 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3629 if (!BinOp) return Cond;
3630
3631 if (BinOp->getOpcode() != BO_LOr) return Cond;
3632
3633 // With an inner '==' that has a literal on the right-hand side.
3634 Expr *LHS = BinOp->getLHS();
3635 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3636 if (!InnerBinOp) return Cond;
3637
3638 if (InnerBinOp->getOpcode() != BO_EQ ||
3639 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3640 return Cond;
3641
3642 // If the inner binary operation came from a macro expansion named
3643 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3644 // of the '||', which is the real, user-provided condition.
3645 SourceLocation Loc = InnerBinOp->getExprLoc();
3646 if (!Loc.isMacroID()) return Cond;
3647
3648 StringRef MacroName = PP.getImmediateMacroName(Loc);
3649 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3650 return BinOp->getRHS();
3651
3652 return Cond;
3653}
3654
3655namespace {
3656
3657// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3658// within failing boolean expression, such as substituting template parameters
3659// for actual types.
3660class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3661public:
3662 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3663 : Policy(P) {}
3664
3665 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3666 const auto *DR = dyn_cast<DeclRefExpr>(E);
3667 if (DR && DR->getQualifier()) {
3668 // If this is a qualified name, expand the template arguments in nested
3669 // qualifiers.
3670 DR->getQualifier().print(OS, Policy, true);
3671 // Then print the decl itself.
3672 const ValueDecl *VD = DR->getDecl();
3673 OS << *VD;
3674 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3675 // This is a template variable, print the expanded template arguments.
3676 printTemplateArgumentList(
3677 OS, IV->getTemplateArgs().asArray(), Policy,
3678 IV->getSpecializedTemplate()->getTemplateParameters());
3679 }
3680 return true;
3681 }
3682 return false;
3683 }
3684
3685private:
3686 const PrintingPolicy Policy;
3687};
3688
3689} // end anonymous namespace
3690
3691std::pair<Expr *, std::string>
3694
3695 // Separate out all of the terms in a conjunction.
3698
3699 // Determine which term failed.
3700 Expr *FailedCond = nullptr;
3701 for (Expr *Term : Terms) {
3702 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3703
3704 // Literals are uninteresting.
3705 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3706 isa<IntegerLiteral>(TermAsWritten))
3707 continue;
3708
3709 // The initialization of the parameter from the argument is
3710 // a constant-evaluated context.
3713
3714 bool Succeeded;
3715 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3716 !Succeeded) {
3717 FailedCond = TermAsWritten;
3718 break;
3719 }
3720 }
3721 if (!FailedCond)
3722 FailedCond = Cond->IgnoreParenImpCasts();
3723
3724 std::string Description;
3725 {
3726 llvm::raw_string_ostream Out(Description);
3728 Policy.PrintAsCanonical = true;
3729 FailedBooleanConditionPrinterHelper Helper(Policy);
3730 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3731 }
3732 return { FailedCond, Description };
3733}
3734
3735static TemplateName
3737 const AssumedTemplateStorage *ATN,
3738 SourceLocation NameLoc) {
3739 // We assumed this undeclared identifier to be an (ADL-only) function
3740 // template name, but it was used in a context where a type was required.
3741 // Try to typo-correct it now.
3742 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3743 struct CandidateCallback : CorrectionCandidateCallback {
3744 bool ValidateCandidate(const TypoCorrection &TC) override {
3745 return TC.getCorrectionDecl() &&
3747 }
3748 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3749 return std::make_unique<CandidateCallback>(*this);
3750 }
3751 } FilterCCC;
3752
3753 TypoCorrection Corrected =
3754 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3755 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3756 if (Corrected && Corrected.getFoundDecl()) {
3757 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3758 << ATN->getDeclName());
3760 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3762 }
3763
3764 return TemplateName();
3765}
3766
3768 TemplateName Name,
3769 SourceLocation TemplateLoc,
3770 TemplateArgumentListInfo &TemplateArgs,
3771 Scope *Scope, bool ForNestedNameSpecifier) {
3772 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3773
3774 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3775 if (!Template) {
3776 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3777 Template = S->getParameterPack();
3778 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3779 if (DTN->getName().getIdentifier())
3780 // When building a template-id where the template-name is dependent,
3781 // assume the template is a type template. Either our assumption is
3782 // correct, or the code is ill-formed and will be diagnosed when the
3783 // dependent name is substituted.
3784 return Context.getTemplateSpecializationType(Keyword, Name,
3785 TemplateArgs.arguments(),
3786 /*CanonicalArgs=*/{});
3787 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3789 *this, Scope, ATN, TemplateLoc);
3790 CorrectedName.isNull()) {
3791 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3792 return QualType();
3793 } else {
3794 Name = CorrectedName;
3795 Template = Name.getAsTemplateDecl();
3796 }
3797 }
3798 }
3799 if (!Template ||
3801 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3802 if (ForNestedNameSpecifier)
3803 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3804 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3805 else
3806 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3808 return QualType();
3809 }
3810
3811 // Check that the template argument list is well-formed for this
3812 // template.
3814 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3815 DefaultArgs, /*PartialTemplateArgs=*/false,
3816 CTAI,
3817 /*UpdateArgsWithConversions=*/true))
3818 return QualType();
3819
3820 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3821 // and there are no diagnsotics currently implemented for TemplateDecls,
3822 // so avoid doing it for now.
3823 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3824
3825 QualType CanonType;
3826
3828 // We might have a substituted template template parameter pack. If so,
3829 // build a template specialization type for it.
3831 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3832
3833 // C++0x [dcl.type.elab]p2:
3834 // If the identifier resolves to a typedef-name or the simple-template-id
3835 // resolves to an alias template specialization, the
3836 // elaborated-type-specifier is ill-formed.
3839 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3842 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3843 }
3844
3845 // Find the canonical type for this type alias template specialization.
3846 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3847
3848 // Diagnose uses of the pattern of this template.
3849 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3850 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3851
3852 if (Pattern->isInvalidDecl())
3853 return QualType();
3854
3855 // Only substitute for the innermost template argument list.
3856 MultiLevelTemplateArgumentList TemplateArgLists;
3858 /*Final=*/true);
3859 TemplateArgLists.addOuterRetainedLevels(
3860 AliasTemplate->getTemplateParameters()->getDepth());
3861
3863
3864 // FIXME: The TemplateArgs passed here are not used for the context note,
3865 // nor they should, because this note will be pointing to the specialization
3866 // anyway. These arguments are needed for a hack for instantiating lambdas
3867 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3868 // arguments will be used for collating the template arguments needed to
3869 // instantiate the lambda.
3870 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3871 /*Entity=*/AliasTemplate,
3872 /*TemplateArgs=*/CTAI.SugaredConverted);
3873 if (Inst.isInvalid())
3874 return QualType();
3875
3876 std::optional<ContextRAII> SavedContext;
3877 if (!AliasTemplate->getDeclContext()->isFileContext())
3878 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3879
3880 CanonType =
3881 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3882 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3883 if (CanonType.isNull()) {
3884 // If this was enable_if and we failed to find the nested type
3885 // within enable_if in a SFINAE context, dig out the specific
3886 // enable_if condition that failed and present that instead.
3888 if (SFINAETrap *Trap = getSFINAEContext();
3889 TemplateDeductionInfo *DeductionInfo =
3890 Trap ? Trap->getDeductionInfo() : nullptr) {
3891 if (DeductionInfo->hasSFINAEDiagnostic() &&
3892 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3893 diag::err_typename_nested_not_found_enable_if &&
3894 TemplateArgs[0].getArgument().getKind() ==
3896 Expr *FailedCond;
3897 std::string FailedDescription;
3898 std::tie(FailedCond, FailedDescription) =
3899 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3900
3901 // Remove the old SFINAE diagnostic.
3902 PartialDiagnosticAt OldDiag =
3904 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3905
3906 // Add a new SFINAE diagnostic specifying which condition
3907 // failed.
3908 DeductionInfo->addSFINAEDiagnostic(
3909 OldDiag.first,
3910 PDiag(diag::err_typename_nested_not_found_requirement)
3911 << FailedDescription << FailedCond->getSourceRange());
3912 }
3913 }
3914 }
3915
3916 return QualType();
3917 }
3918 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3919 CanonType = checkBuiltinTemplateIdType(
3920 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3921 } else if (Name.isDependent() ||
3922 TemplateSpecializationType::anyDependentTemplateArguments(
3923 TemplateArgs, CTAI.CanonicalConverted)) {
3924 // This class template specialization is a dependent
3925 // type. Therefore, its canonical type is another class template
3926 // specialization type that contains all of the converted
3927 // arguments in canonical form. This ensures that, e.g., A<T> and
3928 // A<T, T> have identical types when A is declared as:
3929 //
3930 // template<typename T, typename U = T> struct A;
3931 CanonType = Context.getCanonicalTemplateSpecializationType(
3933 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3934 CTAI.CanonicalConverted);
3935 assert(CanonType->isCanonicalUnqualified());
3936
3937 // This might work out to be a current instantiation, in which
3938 // case the canonical type needs to be the InjectedClassNameType.
3939 //
3940 // TODO: in theory this could be a simple hashtable lookup; most
3941 // changes to CurContext don't change the set of current
3942 // instantiations.
3944 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3945 // If we get out to a namespace, we're done.
3946 if (Ctx->isFileContext()) break;
3947
3948 // If this isn't a record, keep looking.
3949 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3950 if (!Record) continue;
3951
3952 // Look for one of the two cases with InjectedClassNameTypes
3953 // and check whether it's the same template.
3955 !Record->getDescribedClassTemplate())
3956 continue;
3957
3958 // Fetch the injected class name type and check whether its
3959 // injected type is equal to the type we just built.
3960 CanQualType ICNT = Context.getCanonicalTagType(Record);
3961 CanQualType Injected =
3962 Record->getCanonicalTemplateSpecializationType(Context);
3963
3964 if (CanonType != Injected)
3965 continue;
3966
3967 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3968 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3969
3970 // If so, the canonical type of this TST is the injected
3971 // class name type of the record we just found.
3972 CanonType = ICNT;
3973 break;
3974 }
3975 }
3976 } else if (ClassTemplateDecl *ClassTemplate =
3977 dyn_cast<ClassTemplateDecl>(Template)) {
3978 // Find the class template specialization declaration that
3979 // corresponds to these arguments.
3980 void *InsertPos = nullptr;
3982 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3983 if (!Decl) {
3984 // This is the first time we have referenced this class template
3985 // specialization. Create the canonical declaration and add it to
3986 // the set of specializations.
3988 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3989 ClassTemplate->getDeclContext(),
3990 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3991 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3992 CTAI.StrictPackMatch, nullptr);
3993 ClassTemplate->AddSpecialization(Decl, InsertPos);
3994 if (ClassTemplate->isOutOfLine())
3995 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3996 }
3997
3998 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3999 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4000 NonSFINAEContext _(*this);
4001 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4002 if (!Inst.isInvalid()) {
4004 CTAI.CanonicalConverted,
4005 /*Final=*/false);
4006 InstantiateAttrsForDecl(TemplateArgLists,
4007 ClassTemplate->getTemplatedDecl(), Decl);
4008 }
4009 }
4010
4011 // Diagnose uses of this specialization.
4012 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4013 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4014
4015 CanonType = Context.getCanonicalTagType(Decl);
4016 assert(isa<RecordType>(CanonType) &&
4017 "type of non-dependent specialization is not a RecordType");
4018 } else {
4019 llvm_unreachable("Unhandled template kind");
4020 }
4021
4022 // Build the fully-sugared type for this class template
4023 // specialization, which refers back to the class template
4024 // specialization we created or found.
4025 return Context.getTemplateSpecializationType(
4026 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4027 CanonType);
4028}
4029
4031 TemplateNameKind &TNK,
4032 SourceLocation NameLoc,
4033 IdentifierInfo *&II) {
4034 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4035
4036 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4037 assert(ATN && "not an assumed template name");
4038 II = ATN->getDeclName().getAsIdentifierInfo();
4039
4040 if (TemplateName Name =
4041 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4042 !Name.isNull()) {
4043 // Resolved to a type template name.
4044 ParsedName = TemplateTy::make(Name);
4045 TNK = TNK_Type_template;
4046 }
4047}
4048
4050 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4051 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4052 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4053 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4054 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4055 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4056 ImplicitTypenameContext AllowImplicitTypename) {
4057 if (SS.isInvalid())
4058 return true;
4059
4060 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4061 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4062
4063 // C++ [temp.res]p3:
4064 // A qualified-id that refers to a type and in which the
4065 // nested-name-specifier depends on a template-parameter (14.6.2)
4066 // shall be prefixed by the keyword typename to indicate that the
4067 // qualified-id denotes a type, forming an
4068 // elaborated-type-specifier (7.1.5.3).
4069 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4070 // C++2a relaxes some of those restrictions in [temp.res]p5.
4071 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4072 SS.getScopeRep(), TemplateII);
4074 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4075 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4076 << NNS;
4077 if (!getLangOpts().CPlusPlus20)
4078 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4079 } else
4080 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4081
4082 // FIXME: This is not quite correct recovery as we don't transform SS
4083 // into the corresponding dependent form (and we don't diagnose missing
4084 // 'template' keywords within SS as a result).
4085 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4086 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4087 TemplateArgsIn, RAngleLoc);
4088 }
4089
4090 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4091 // it's not actually allowed to be used as a type in most cases. Because
4092 // we annotate it before we know whether it's valid, we have to check for
4093 // this case here.
4094 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4095 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4096 Diag(TemplateIILoc,
4097 TemplateKWLoc.isInvalid()
4098 ? diag::err_out_of_line_qualified_id_type_names_constructor
4099 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4100 << TemplateII << 0 /*injected-class-name used as template name*/
4101 << 1 /*if any keyword was present, it was 'template'*/;
4102 }
4103 }
4104
4105 // Translate the parser's template argument list in our AST format.
4106 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4107 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4108
4110 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4111 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4112 if (SpecTy.isNull())
4113 return true;
4114
4115 // Build type-source information.
4116 TypeLocBuilder TLB;
4117 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4118 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4119 TemplateIILoc, TemplateArgs);
4120 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4121}
4122
4124 TypeSpecifierType TagSpec,
4125 SourceLocation TagLoc,
4126 CXXScopeSpec &SS,
4127 SourceLocation TemplateKWLoc,
4128 TemplateTy TemplateD,
4129 SourceLocation TemplateLoc,
4130 SourceLocation LAngleLoc,
4131 ASTTemplateArgsPtr TemplateArgsIn,
4132 SourceLocation RAngleLoc) {
4133 if (SS.isInvalid())
4134 return TypeResult(true);
4135
4136 // Translate the parser's template argument list in our AST format.
4137 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4138 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4139
4140 // Determine the tag kind
4144
4146 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4147 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4148 if (Result.isNull())
4149 return TypeResult(true);
4150
4151 // Check the tag kind
4152 if (const RecordType *RT = Result->getAs<RecordType>()) {
4153 RecordDecl *D = RT->getDecl();
4154
4155 IdentifierInfo *Id = D->getIdentifier();
4156 assert(Id && "templated class must have an identifier");
4157
4159 TagLoc, Id)) {
4160 Diag(TagLoc, diag::err_use_with_wrong_tag)
4161 << Result
4163 Diag(D->getLocation(), diag::note_previous_use);
4164 }
4165 }
4166
4167 // Provide source-location information for the template specialization.
4168 TypeLocBuilder TLB;
4170 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4171 TemplateArgs);
4173}
4174
4175static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4176 NamedDecl *PrevDecl,
4177 SourceLocation Loc,
4179
4181
4183 unsigned Depth,
4184 unsigned Index) {
4185 switch (Arg.getKind()) {
4193 return false;
4194
4196 QualType Type = Arg.getAsType();
4197 const TemplateTypeParmType *TPT =
4198 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4199 return TPT && !Type.hasQualifiers() &&
4200 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4201 }
4202
4204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4205 if (!DRE || !DRE->getDecl())
4206 return false;
4207 const NonTypeTemplateParmDecl *NTTP =
4208 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4209 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4210 }
4211
4213 const TemplateTemplateParmDecl *TTP =
4214 dyn_cast_or_null<TemplateTemplateParmDecl>(
4216 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4217 }
4218 llvm_unreachable("unexpected kind of template argument");
4219}
4220
4222 TemplateParameterList *SpecParams,
4224 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4225 return false;
4226
4227 unsigned Depth = Params->getDepth();
4228
4229 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4230 TemplateArgument Arg = Args[I];
4231
4232 // If the parameter is a pack expansion, the argument must be a pack
4233 // whose only element is a pack expansion.
4234 if (Params->getParam(I)->isParameterPack()) {
4235 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4236 !Arg.pack_begin()->isPackExpansion())
4237 return false;
4238 Arg = Arg.pack_begin()->getPackExpansionPattern();
4239 }
4240
4241 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4242 return false;
4243
4244 // For NTTPs further specialization is allowed via deduced types, so
4245 // we need to make sure to only reject here if primary template and
4246 // specialization use the same type for the NTTP.
4247 if (auto *SpecNTTP =
4248 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4249 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4250 if (!NTTP || NTTP->getType().getCanonicalType() !=
4251 SpecNTTP->getType().getCanonicalType())
4252 return false;
4253 }
4254 }
4255
4256 return true;
4257}
4258
4259template<typename PartialSpecDecl>
4260static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4261 if (Partial->getDeclContext()->isDependentContext())
4262 return;
4263
4264 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4265 // for non-substitution-failure issues?
4266 TemplateDeductionInfo Info(Partial->getLocation());
4267 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4268 return;
4269
4270 auto *Template = Partial->getSpecializedTemplate();
4271 S.Diag(Partial->getLocation(),
4272 diag::ext_partial_spec_not_more_specialized_than_primary)
4274
4275 if (Info.hasSFINAEDiagnostic()) {
4279 SmallString<128> SFINAEArgString;
4280 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4281 S.Diag(Diag.first,
4282 diag::note_partial_spec_not_more_specialized_than_primary)
4283 << SFINAEArgString;
4284 }
4285
4287 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4288 Template->getAssociatedConstraints(TemplateAC);
4289 Partial->getAssociatedConstraints(PartialAC);
4291 TemplateAC);
4292}
4293
4294static void
4296 const llvm::SmallBitVector &DeducibleParams) {
4297 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4298 if (!DeducibleParams[I]) {
4299 NamedDecl *Param = TemplateParams->getParam(I);
4300 if (Param->getDeclName())
4301 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4302 << Param->getDeclName();
4303 else
4304 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4305 << "(anonymous)";
4306 }
4307 }
4308}
4309
4310
4311template<typename PartialSpecDecl>
4313 PartialSpecDecl *Partial) {
4314 // C++1z [temp.class.spec]p8: (DR1495)
4315 // - The specialization shall be more specialized than the primary
4316 // template (14.5.5.2).
4318
4319 // C++ [temp.class.spec]p8: (DR1315)
4320 // - Each template-parameter shall appear at least once in the
4321 // template-id outside a non-deduced context.
4322 // C++1z [temp.class.spec.match]p3 (P0127R2)
4323 // If the template arguments of a partial specialization cannot be
4324 // deduced because of the structure of its template-parameter-list
4325 // and the template-id, the program is ill-formed.
4326 auto *TemplateParams = Partial->getTemplateParameters();
4327 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4328 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4329 TemplateParams->getDepth(), DeducibleParams);
4330
4331 if (!DeducibleParams.all()) {
4332 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4333 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4335 << (NumNonDeducible > 1)
4336 << SourceRange(Partial->getLocation(),
4337 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4338 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4339 }
4340}
4341
4346
4351
4353 // C++1z [temp.param]p11:
4354 // A template parameter of a deduction guide template that does not have a
4355 // default-argument shall be deducible from the parameter-type-list of the
4356 // deduction guide template.
4357 auto *TemplateParams = TD->getTemplateParameters();
4358 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4359 MarkDeducedTemplateParameters(TD, DeducibleParams);
4360 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4361 // A parameter pack is deducible (to an empty pack).
4362 auto *Param = TemplateParams->getParam(I);
4363 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4364 DeducibleParams[I] = true;
4365 }
4366
4367 if (!DeducibleParams.all()) {
4368 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4369 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4370 << (NumNonDeducible > 1);
4371 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4372 }
4373}
4374
4377 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4379 // D must be variable template id.
4381 "Variable template specialization is declared with a template id.");
4382
4383 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4384 TemplateArgumentListInfo TemplateArgs =
4385 makeTemplateArgumentListInfo(*this, *TemplateId);
4386 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4387 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4388 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4389
4390 TemplateName Name = TemplateId->Template.get();
4391
4392 // The template-id must name a variable template.
4394 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4395 if (!VarTemplate) {
4396 NamedDecl *FnTemplate;
4397 if (auto *OTS = Name.getAsOverloadedTemplate())
4398 FnTemplate = *OTS->begin();
4399 else
4400 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4401 if (FnTemplate)
4402 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4403 << FnTemplate->getDeclName();
4404 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4406 }
4407
4408 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4409 auto Message = DSA->getMessage();
4410 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4411 << VarTemplate << !Message.empty() << Message;
4412 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4413 }
4414
4415 // Check for unexpanded parameter packs in any of the template arguments.
4416 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4417 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4421 return true;
4422
4423 // Check that the template argument list is well-formed for this
4424 // template.
4426 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4427 /*DefaultArgs=*/{},
4428 /*PartialTemplateArgs=*/false, CTAI,
4429 /*UpdateArgsWithConversions=*/true))
4430 return true;
4431
4432 // Find the variable template (partial) specialization declaration that
4433 // corresponds to these arguments.
4436 TemplateArgs.size(),
4437 CTAI.CanonicalConverted))
4438 return true;
4439
4440 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4441 // we also do them during instantiation.
4442 if (!Name.isDependent() &&
4443 !TemplateSpecializationType::anyDependentTemplateArguments(
4444 TemplateArgs, CTAI.CanonicalConverted)) {
4445 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4446 << VarTemplate->getDeclName();
4448 }
4449
4450 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4451 TemplateParams, CTAI.CanonicalConverted) &&
4452 (!Context.getLangOpts().CPlusPlus20 ||
4453 !TemplateParams->hasAssociatedConstraints())) {
4454 // C++ [temp.class.spec]p9b3:
4455 //
4456 // -- The argument list of the specialization shall not be identical
4457 // to the implicit argument list of the primary template.
4458 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4459 << /*variable template*/ 1
4460 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4461 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4462 // FIXME: Recover from this by treating the declaration as a
4463 // redeclaration of the primary template.
4464 return true;
4465 }
4466 }
4467
4468 void *InsertPos = nullptr;
4469 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4470
4472 PrevDecl = VarTemplate->findPartialSpecialization(
4473 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4474 else
4475 PrevDecl =
4476 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4477
4479
4480 // Check whether we can declare a variable template specialization in
4481 // the current scope.
4482 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4483 TemplateNameLoc,
4485 return true;
4486
4487 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4488 // Since the only prior variable template specialization with these
4489 // arguments was referenced but not declared, reuse that
4490 // declaration node as our own, updating its source location and
4491 // the list of outer template parameters to reflect our new declaration.
4492 Specialization = PrevDecl;
4493 Specialization->setLocation(TemplateNameLoc);
4494 PrevDecl = nullptr;
4495 } else if (IsPartialSpecialization) {
4496 // Create a new class template partial specialization declaration node.
4498 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4501 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4502 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4503 SC, CTAI.CanonicalConverted);
4504 Partial->setTemplateArgsAsWritten(TemplateArgs);
4505
4506 if (!PrevPartial)
4507 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4508 Specialization = Partial;
4509
4511 } else {
4512 // Create a new class template specialization declaration node for
4513 // this explicit specialization or friend declaration.
4515 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4516 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4517 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4518
4519 if (!PrevDecl)
4520 VarTemplate->AddSpecialization(Specialization, InsertPos);
4521 }
4522
4523 // C++ [temp.expl.spec]p6:
4524 // If a template, a member template or the member of a class template is
4525 // explicitly specialized then that specialization shall be declared
4526 // before the first use of that specialization that would cause an implicit
4527 // instantiation to take place, in every translation unit in which such a
4528 // use occurs; no diagnostic is required.
4529 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4530 bool Okay = false;
4531 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4532 // Is there any previous explicit specialization declaration?
4534 Okay = true;
4535 break;
4536 }
4537 }
4538
4539 if (!Okay) {
4540 SourceRange Range(TemplateNameLoc, RAngleLoc);
4541 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4542 << Name << Range;
4543
4544 Diag(PrevDecl->getPointOfInstantiation(),
4545 diag::note_instantiation_required_here)
4546 << (PrevDecl->getTemplateSpecializationKind() !=
4548 return true;
4549 }
4550 }
4551
4552 Specialization->setLexicalDeclContext(CurContext);
4553
4554 // Add the specialization into its lexical context, so that it can
4555 // be seen when iterating through the list of declarations in that
4556 // context. However, specializations are not found by name lookup.
4557 CurContext->addDecl(Specialization);
4558
4559 // Note that this is an explicit specialization.
4560 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4561
4562 Previous.clear();
4563 if (PrevDecl)
4564 Previous.addDecl(PrevDecl);
4565 else if (Specialization->isStaticDataMember() &&
4566 Specialization->isOutOfLine())
4567 Specialization->setAccess(VarTemplate->getAccess());
4568
4569 return Specialization;
4570}
4571
4572namespace {
4573/// A partial specialization whose template arguments have matched
4574/// a given template-id.
4575struct PartialSpecMatchResult {
4578};
4579
4580// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4581// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4582static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4583 if (Var->getName() != "format_kind" ||
4584 !Var->getDeclContext()->isStdNamespace())
4585 return false;
4586
4587 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4588 // release in which users can access std::format_kind.
4589 // We can use 20250520 as the final date, see the following commits.
4590 // GCC releases/gcc-15 branch:
4591 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4592 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4593 // GCC master branch:
4594 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4595 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4596 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4597}
4598} // end anonymous namespace
4599
4602 SourceLocation TemplateNameLoc,
4603 const TemplateArgumentListInfo &TemplateArgs,
4604 bool SetWrittenArgs) {
4605 assert(Template && "A variable template id without template?");
4606
4607 // Check that the template argument list is well-formed for this template.
4610 Template, TemplateNameLoc,
4611 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4612 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4613 /*UpdateArgsWithConversions=*/true))
4614 return true;
4615
4616 // Produce a placeholder value if the specialization is dependent.
4617 if (Template->getDeclContext()->isDependentContext() ||
4618 TemplateSpecializationType::anyDependentTemplateArguments(
4619 TemplateArgs, CTAI.CanonicalConverted)) {
4620 if (ParsingInitForAutoVars.empty())
4621 return DeclResult();
4622
4623 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4624 const TemplateArgument &Arg2) {
4625 return Context.isSameTemplateArgument(Arg1, Arg2);
4626 };
4627
4628 if (VarDecl *Var = Template->getTemplatedDecl();
4629 ParsingInitForAutoVars.count(Var) &&
4630 // See comments on this function definition
4631 !IsLibstdcxxStdFormatKind(PP, Var) &&
4632 llvm::equal(
4633 CTAI.CanonicalConverted,
4634 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4635 IsSameTemplateArg)) {
4636 Diag(TemplateNameLoc,
4637 diag::err_auto_variable_cannot_appear_in_own_initializer)
4638 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4639 return true;
4640 }
4641
4643 Template->getPartialSpecializations(PartialSpecs);
4644 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4645 if (ParsingInitForAutoVars.count(Partial) &&
4646 llvm::equal(CTAI.CanonicalConverted,
4647 Partial->getTemplateArgs().asArray(),
4648 IsSameTemplateArg)) {
4649 Diag(TemplateNameLoc,
4650 diag::err_auto_variable_cannot_appear_in_own_initializer)
4651 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4652 << Partial->getType();
4653 return true;
4654 }
4655
4656 return DeclResult();
4657 }
4658
4659 // Find the variable template specialization declaration that
4660 // corresponds to these arguments.
4661 void *InsertPos = nullptr;
4663 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4664 checkSpecializationReachability(TemplateNameLoc, Spec);
4665 if (Spec->getType()->isUndeducedType()) {
4666 if (ParsingInitForAutoVars.count(Spec))
4667 Diag(TemplateNameLoc,
4668 diag::err_auto_variable_cannot_appear_in_own_initializer)
4669 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4670 << Spec->getType();
4671 else
4672 // We are substituting the initializer of this variable template
4673 // specialization.
4674 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4675 << Spec << Spec->getType();
4676
4677 return true;
4678 }
4679 // If we already have a variable template specialization, return it.
4680 return Spec;
4681 }
4682
4683 // This is the first time we have referenced this variable template
4684 // specialization. Create the canonical declaration and add it to
4685 // the set of specializations, based on the closest partial specialization
4686 // that it represents. That is,
4687 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4688 const TemplateArgumentList *PartialSpecArgs = nullptr;
4689 bool AmbiguousPartialSpec = false;
4690 typedef PartialSpecMatchResult MatchResult;
4692 SourceLocation PointOfInstantiation = TemplateNameLoc;
4693 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4694 /*ForTakingAddress=*/false);
4695
4696 // 1. Attempt to find the closest partial specialization that this
4697 // specializes, if any.
4698 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4699 // Perhaps better after unification of DeduceTemplateArguments() and
4700 // getMoreSpecializedPartialSpecialization().
4702 Template->getPartialSpecializations(PartialSpecs);
4703
4704 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4705 // C++ [temp.spec.partial.member]p2:
4706 // If the primary member template is explicitly specialized for a given
4707 // (implicit) specialization of the enclosing class template, the partial
4708 // specializations of the member template are ignored for this
4709 // specialization of the enclosing class template. If a partial
4710 // specialization of the member template is explicitly specialized for a
4711 // given (implicit) specialization of the enclosing class template, the
4712 // primary member template and its other partial specializations are still
4713 // considered for this specialization of the enclosing class template.
4714 if (Template->isMemberSpecialization() &&
4715 !Partial->isMemberSpecialization())
4716 continue;
4717
4718 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4719
4721 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4723 // Store the failed-deduction information for use in diagnostics, later.
4724 // TODO: Actually use the failed-deduction info?
4725 FailedCandidates.addCandidate().set(
4728 (void)Result;
4729 } else {
4730 Matched.push_back(PartialSpecMatchResult());
4731 Matched.back().Partial = Partial;
4732 Matched.back().Args = Info.takeSugared();
4733 }
4734 }
4735
4736 if (Matched.size() >= 1) {
4737 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4738 if (Matched.size() == 1) {
4739 // -- If exactly one matching specialization is found, the
4740 // instantiation is generated from that specialization.
4741 // We don't need to do anything for this.
4742 } else {
4743 // -- If more than one matching specialization is found, the
4744 // partial order rules (14.5.4.2) are used to determine
4745 // whether one of the specializations is more specialized
4746 // than the others. If none of the specializations is more
4747 // specialized than all of the other matching
4748 // specializations, then the use of the variable template is
4749 // ambiguous and the program is ill-formed.
4750 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4751 PEnd = Matched.end();
4752 P != PEnd; ++P) {
4753 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4754 PointOfInstantiation) ==
4755 P->Partial)
4756 Best = P;
4757 }
4758
4759 // Determine if the best partial specialization is more specialized than
4760 // the others.
4761 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4762 PEnd = Matched.end();
4763 P != PEnd; ++P) {
4765 P->Partial, Best->Partial,
4766 PointOfInstantiation) != Best->Partial) {
4767 AmbiguousPartialSpec = true;
4768 break;
4769 }
4770 }
4771 }
4772
4773 // Instantiate using the best variable template partial specialization.
4774 InstantiationPattern = Best->Partial;
4775 PartialSpecArgs = Best->Args;
4776 } else {
4777 // -- If no match is found, the instantiation is generated
4778 // from the primary template.
4779 // InstantiationPattern = Template->getTemplatedDecl();
4780 }
4781
4782 // 2. Create the canonical declaration.
4783 // Note that we do not instantiate a definition until we see an odr-use
4784 // in DoMarkVarDeclReferenced().
4785 // FIXME: LateAttrs et al.?
4786 if (AmbiguousPartialSpec) {
4787 // Partial ordering did not produce a clear winner. Complain.
4788 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4789 << Template;
4790 // Print the matching partial specializations.
4791 for (MatchResult P : Matched)
4792 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4793 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4794 *P.Args);
4795 return true;
4796 }
4797
4799 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4800 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4801 if (!Decl)
4802 return true;
4803 if (SetWrittenArgs)
4804 Decl->setTemplateArgsAsWritten(TemplateArgs);
4805
4807 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4808 Decl->setInstantiationOf(D, PartialSpecArgs);
4809
4810 checkSpecializationReachability(TemplateNameLoc, Decl);
4811
4812 assert(Decl && "No variable template specialization?");
4813 return Decl;
4814}
4815
4817 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4818 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4819 const TemplateArgumentListInfo *TemplateArgs) {
4820
4821 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4822 *TemplateArgs, /*SetWrittenArgs=*/false);
4823 if (Decl.isInvalid())
4824 return ExprError();
4825
4826 if (!Decl.get())
4827 return ExprResult();
4828
4829 VarDecl *Var = cast<VarDecl>(Decl.get());
4832 NameInfo.getLoc());
4833
4834 // Build an ordinary singleton decl ref.
4835 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4836}
4837
4839 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4841 const TemplateArgumentListInfo *TemplateArgs) {
4842 assert(Template && "A variable template id without template?");
4843
4844 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4845 Template->templateParameterKind() !=
4847 return ExprResult();
4848
4849 // Check that the template argument list is well-formed for this template.
4852 Template, TemplateLoc,
4853 // FIXME: TemplateArgs will not be modified because
4854 // UpdateArgsWithConversions is false, however, we should
4855 // CheckTemplateArgumentList to be const-correct.
4856 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4857 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4858 /*UpdateArgsWithConversions=*/false))
4859 return true;
4860
4862 R.addDecl(Template);
4863
4864 // FIXME: We model references to variable template and concept parameters
4865 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4866 // data, can generally be used in the same places and work the same way.
4867 // However, it might be cleaner to use a dedicated AST node in the long run.
4870 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4871 /*KnownDependent=*/false,
4872 /*KnownInstantiationDependent=*/false);
4873}
4874
4876 SourceLocation Loc) {
4877 Diag(Loc, diag::err_template_missing_args)
4878 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4879 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4880 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4881 }
4882}
4883
4885 bool TemplateKeyword,
4886 TemplateDecl *TD,
4887 SourceLocation Loc) {
4888 TemplateName Name = Context.getQualifiedTemplateName(
4889 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4891}
4892
4894 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4895 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4896 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4897 bool DoCheckConstraintSatisfaction) {
4898 assert(NamedConcept && "A concept template id without a template?");
4899
4900 if (NamedConcept->isInvalidDecl())
4901 return ExprError();
4902
4905 NamedConcept, ConceptNameInfo.getLoc(),
4906 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4907 /*DefaultArgs=*/{},
4908 /*PartialTemplateArgs=*/false, CTAI,
4909 /*UpdateArgsWithConversions=*/false))
4910 return ExprError();
4911
4912 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4913
4914 // There's a bug with CTAI.CanonicalConverted.
4915 // If the template argument contains a DependentDecltypeType that includes a
4916 // TypeAliasType, and the same written type had occurred previously in the
4917 // source, then the DependentDecltypeType would be canonicalized to that
4918 // previous type which would mess up the substitution.
4919 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4921 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4922 CTAI.SugaredConverted);
4923 ConstraintSatisfaction Satisfaction;
4924 bool AreArgsDependent =
4925 TemplateSpecializationType::anyDependentTemplateArguments(
4926 *TemplateArgs, CTAI.SugaredConverted);
4927 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4928 /*Final=*/false);
4930 Context,
4932 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4934
4935 bool Error = false;
4936 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4937 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4938 DoCheckConstraintSatisfaction) {
4939
4941
4944
4946 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4947 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4948 TemplateArgs->getRAngleLoc()),
4949 Satisfaction, CL);
4950 Satisfaction.ContainsErrors = Error;
4951 }
4952
4953 if (Error)
4954 return ExprError();
4955
4957 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4958}
4959
4961 SourceLocation TemplateKWLoc,
4962 LookupResult &R,
4963 bool RequiresADL,
4964 const TemplateArgumentListInfo *TemplateArgs) {
4965 // FIXME: Can we do any checking at this point? I guess we could check the
4966 // template arguments that we have against the template name, if the template
4967 // name refers to a single template. That's not a terribly common case,
4968 // though.
4969 // foo<int> could identify a single function unambiguously
4970 // This approach does NOT work, since f<int>(1);
4971 // gets resolved prior to resorting to overload resolution
4972 // i.e., template<class T> void f(double);
4973 // vs template<class T, class U> void f(U);
4974
4975 // These should be filtered out by our callers.
4976 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4977
4978 // Non-function templates require a template argument list.
4979 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4980 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4982 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4983 return ExprError();
4984 }
4985 }
4986 bool KnownDependent = false;
4987 // In C++1y, check variable template ids.
4988 if (R.getAsSingle<VarTemplateDecl>()) {
4990 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4991 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4992 if (Res.isInvalid() || Res.isUsable())
4993 return Res;
4994 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4995 KnownDependent = true;
4996 }
4997
4998 // We don't want lookup warnings at this point.
4999 R.suppressDiagnostics();
5000
5001 if (R.getAsSingle<ConceptDecl>()) {
5002 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5003 R.getRepresentativeDecl(),
5004 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5005 }
5006
5007 // Check variable template ids (C++17) and concept template parameters
5008 // (C++26).
5010 if (R.getAsSingle<TemplateTemplateParmDecl>())
5012 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
5013 TemplateKWLoc, TemplateArgs);
5014
5015 // Function templates
5017 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5018 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5019 R.begin(), R.end(), KnownDependent,
5020 /*KnownInstantiationDependent=*/false);
5021 // Model the templates with UnresolvedTemplateTy. The expression should then
5022 // either be transformed in an instantiation or be diagnosed in
5023 // CheckPlaceholderExpr.
5024 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5025 !R.getFoundDecl()->getAsFunction())
5026 ULE->setType(Context.UnresolvedTemplateTy);
5027
5028 return ULE;
5029}
5030
5032 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5033 const DeclarationNameInfo &NameInfo,
5034 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5035 assert(TemplateArgs || TemplateKWLoc.isValid());
5036
5037 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5038 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5039 /*EnteringContext=*/false, TemplateKWLoc))
5040 return ExprError();
5041
5042 if (R.isAmbiguous())
5043 return ExprError();
5044
5045 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5046 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5047
5048 if (R.empty()) {
5050 Diag(NameInfo.getLoc(), diag::err_no_member)
5051 << NameInfo.getName() << DC << SS.getRange();
5052 return ExprError();
5053 }
5054
5055 // If necessary, build an implicit class member access.
5056 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5057 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5058 /*S=*/nullptr);
5059
5060 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5061}
5062
5064 CXXScopeSpec &SS,
5065 SourceLocation TemplateKWLoc,
5066 const UnqualifiedId &Name,
5067 ParsedType ObjectType,
5068 bool EnteringContext,
5070 bool AllowInjectedClassName) {
5071 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5072 Diag(TemplateKWLoc,
5074 diag::warn_cxx98_compat_template_outside_of_template :
5075 diag::ext_template_outside_of_template)
5076 << FixItHint::CreateRemoval(TemplateKWLoc);
5077
5078 if (SS.isInvalid())
5079 return TNK_Non_template;
5080
5081 // Figure out where isTemplateName is going to look.
5082 DeclContext *LookupCtx = nullptr;
5083 if (SS.isNotEmpty())
5084 LookupCtx = computeDeclContext(SS, EnteringContext);
5085 else if (ObjectType)
5086 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5087
5088 // C++0x [temp.names]p5:
5089 // If a name prefixed by the keyword template is not the name of
5090 // a template, the program is ill-formed. [Note: the keyword
5091 // template may not be applied to non-template members of class
5092 // templates. -end note ] [ Note: as is the case with the
5093 // typename prefix, the template prefix is allowed in cases
5094 // where it is not strictly necessary; i.e., when the
5095 // nested-name-specifier or the expression on the left of the ->
5096 // or . is not dependent on a template-parameter, or the use
5097 // does not appear in the scope of a template. -end note]
5098 //
5099 // Note: C++03 was more strict here, because it banned the use of
5100 // the "template" keyword prior to a template-name that was not a
5101 // dependent name. C++ DR468 relaxed this requirement (the
5102 // "template" keyword is now permitted). We follow the C++0x
5103 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5104 bool MemberOfUnknownSpecialization;
5105 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5106 ObjectType, EnteringContext, Result,
5107 MemberOfUnknownSpecialization);
5108 if (TNK != TNK_Non_template) {
5109 // We resolved this to a (non-dependent) template name. Return it.
5110 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5111 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5113 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5114 // C++14 [class.qual]p2:
5115 // In a lookup in which function names are not ignored and the
5116 // nested-name-specifier nominates a class C, if the name specified
5117 // [...] is the injected-class-name of C, [...] the name is instead
5118 // considered to name the constructor
5119 //
5120 // We don't get here if naming the constructor would be valid, so we
5121 // just reject immediately and recover by treating the
5122 // injected-class-name as naming the template.
5123 Diag(Name.getBeginLoc(),
5124 diag::ext_out_of_line_qualified_id_type_names_constructor)
5125 << Name.Identifier
5126 << 0 /*injected-class-name used as template name*/
5127 << TemplateKWLoc.isValid();
5128 }
5129 return TNK;
5130 }
5131
5132 if (!MemberOfUnknownSpecialization) {
5133 // Didn't find a template name, and the lookup wasn't dependent.
5134 // Do the lookup again to determine if this is a "nothing found" case or
5135 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5136 // need to do this.
5138 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5140 // Tell LookupTemplateName that we require a template so that it diagnoses
5141 // cases where it finds a non-template.
5142 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5143 ? RequiredTemplateKind(TemplateKWLoc)
5145 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5146 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5147 !R.isAmbiguous()) {
5148 if (LookupCtx)
5149 Diag(Name.getBeginLoc(), diag::err_no_member)
5150 << DNI.getName() << LookupCtx << SS.getRange();
5151 else
5152 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5153 << DNI.getName() << SS.getRange();
5154 }
5155 return TNK_Non_template;
5156 }
5157
5158 NestedNameSpecifier Qualifier = SS.getScopeRep();
5159
5160 switch (Name.getKind()) {
5162 Result = TemplateTy::make(Context.getDependentTemplateName(
5163 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5165
5167 Result = TemplateTy::make(Context.getDependentTemplateName(
5168 {Qualifier, Name.OperatorFunctionId.Operator,
5169 TemplateKWLoc.isValid()}));
5170 return TNK_Function_template;
5171
5173 // This is a kind of template name, but can never occur in a dependent
5174 // scope (literal operators can only be declared at namespace scope).
5175 break;
5176
5177 default:
5178 break;
5179 }
5180
5181 // This name cannot possibly name a dependent template. Diagnose this now
5182 // rather than building a dependent template name that can never be valid.
5183 Diag(Name.getBeginLoc(),
5184 diag::err_template_kw_refers_to_dependent_non_template)
5186 << TemplateKWLoc.isValid() << TemplateKWLoc;
5187 return TNK_Non_template;
5188}
5189
5192 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5193 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5194 const TemplateArgument &Arg = AL.getArgument();
5196 TypeSourceInfo *TSI = nullptr;
5197
5198 // Check template type parameter.
5199 switch(Arg.getKind()) {
5201 // C++ [temp.arg.type]p1:
5202 // A template-argument for a template-parameter which is a
5203 // type shall be a type-id.
5204 ArgType = Arg.getAsType();
5205 TSI = AL.getTypeSourceInfo();
5206 break;
5209 // We have a template type parameter but the template argument
5210 // is a template without any arguments.
5211 SourceRange SR = AL.getSourceRange();
5214 return true;
5215 }
5217 // We have a template type parameter but the template argument is an
5218 // expression; see if maybe it is missing the "typename" keyword.
5219 CXXScopeSpec SS;
5220 DeclarationNameInfo NameInfo;
5221
5222 if (DependentScopeDeclRefExpr *ArgExpr =
5223 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5224 SS.Adopt(ArgExpr->getQualifierLoc());
5225 NameInfo = ArgExpr->getNameInfo();
5226 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5227 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5228 if (ArgExpr->isImplicitAccess()) {
5229 SS.Adopt(ArgExpr->getQualifierLoc());
5230 NameInfo = ArgExpr->getMemberNameInfo();
5231 }
5232 }
5233
5234 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5235 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5236 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5237
5238 if (Result.getAsSingle<TypeDecl>() ||
5239 Result.wasNotFoundInCurrentInstantiation()) {
5240 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5241 // Suggest that the user add 'typename' before the NNS.
5243 Diag(Loc, getLangOpts().MSVCCompat
5244 ? diag::ext_ms_template_type_arg_missing_typename
5245 : diag::err_template_arg_must_be_type_suggest)
5246 << FixItHint::CreateInsertion(Loc, "typename ");
5248
5249 // Recover by synthesizing a type using the location information that we
5250 // already have.
5251 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5252 SS.getScopeRep(), II);
5253 TypeLocBuilder TLB;
5255 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5257 TL.setNameLoc(NameInfo.getLoc());
5258 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5259
5260 // Overwrite our input TemplateArgumentLoc so that we can recover
5261 // properly.
5264
5265 break;
5266 }
5267 }
5268 // fallthrough
5269 [[fallthrough]];
5270 }
5271 default: {
5272 // We allow instantiating a template with template argument packs when
5273 // building deduction guides or mapping constraint template parameters.
5274 if (Arg.getKind() == TemplateArgument::Pack &&
5275 (CodeSynthesisContexts.back().Kind ==
5278 SugaredConverted.push_back(Arg);
5279 CanonicalConverted.push_back(Arg);
5280 return false;
5281 }
5282 // We have a template type parameter but the template argument
5283 // is not a type.
5284 SourceRange SR = AL.getSourceRange();
5285 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5287
5288 return true;
5289 }
5290 }
5291
5292 if (CheckTemplateArgument(TSI))
5293 return true;
5294
5295 // Objective-C ARC:
5296 // If an explicitly-specified template argument type is a lifetime type
5297 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5298 if (getLangOpts().ObjCAutoRefCount &&
5299 ArgType->isObjCLifetimeType() &&
5300 !ArgType.getObjCLifetime()) {
5301 Qualifiers Qs;
5303 ArgType = Context.getQualifiedType(ArgType, Qs);
5304 }
5305
5306 SugaredConverted.push_back(TemplateArgument(ArgType));
5307 CanonicalConverted.push_back(
5308 TemplateArgument(Context.getCanonicalType(ArgType)));
5309 return false;
5310}
5311
5312/// Substitute template arguments into the default template argument for
5313/// the given template type parameter.
5314///
5315/// \param SemaRef the semantic analysis object for which we are performing
5316/// the substitution.
5317///
5318/// \param Template the template that we are synthesizing template arguments
5319/// for.
5320///
5321/// \param TemplateLoc the location of the template name that started the
5322/// template-id we are checking.
5323///
5324/// \param RAngleLoc the location of the right angle bracket ('>') that
5325/// terminates the template-id.
5326///
5327/// \param Param the template template parameter whose default we are
5328/// substituting into.
5329///
5330/// \param Converted the list of template arguments provided for template
5331/// parameters that precede \p Param in the template parameter list.
5332///
5333/// \param Output the resulting substituted template argument.
5334///
5335/// \returns true if an error occurred.
5337 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5338 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5339 ArrayRef<TemplateArgument> SugaredConverted,
5340 ArrayRef<TemplateArgument> CanonicalConverted,
5341 TemplateArgumentLoc &Output) {
5342 Output = Param->getDefaultArgument();
5343
5344 // If the argument type is dependent, instantiate it now based
5345 // on the previously-computed template arguments.
5346 if (Output.getArgument().isInstantiationDependent()) {
5347 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5348 SugaredConverted,
5349 SourceRange(TemplateLoc, RAngleLoc));
5350 if (Inst.isInvalid())
5351 return true;
5352
5353 // Only substitute for the innermost template argument list.
5354 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5355 /*Final=*/true);
5356 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5357 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5358
5359 bool ForLambdaCallOperator = false;
5360 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5361 ForLambdaCallOperator = Rec->isLambda();
5362 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5363 !ForLambdaCallOperator);
5364
5365 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5366 Param->getDefaultArgumentLoc(),
5367 Param->getDeclName()))
5368 return true;
5369 }
5370
5371 return false;
5372}
5373
5374/// Substitute template arguments into the default template argument for
5375/// the given non-type template parameter.
5376///
5377/// \param SemaRef the semantic analysis object for which we are performing
5378/// the substitution.
5379///
5380/// \param Template the template that we are synthesizing template arguments
5381/// for.
5382///
5383/// \param TemplateLoc the location of the template name that started the
5384/// template-id we are checking.
5385///
5386/// \param RAngleLoc the location of the right angle bracket ('>') that
5387/// terminates the template-id.
5388///
5389/// \param Param the non-type template parameter whose default we are
5390/// substituting into.
5391///
5392/// \param Converted the list of template arguments provided for template
5393/// parameters that precede \p Param in the template parameter list.
5394///
5395/// \returns the substituted template argument, or NULL if an error occurred.
5397 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5398 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5399 ArrayRef<TemplateArgument> SugaredConverted,
5400 ArrayRef<TemplateArgument> CanonicalConverted,
5401 TemplateArgumentLoc &Output) {
5402 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5403 SugaredConverted,
5404 SourceRange(TemplateLoc, RAngleLoc));
5405 if (Inst.isInvalid())
5406 return true;
5407
5408 // Only substitute for the innermost template argument list.
5409 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5410 /*Final=*/true);
5411 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5412 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5413
5414 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5415 EnterExpressionEvaluationContext ConstantEvaluated(
5417 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5418 TemplateArgLists, Output);
5419}
5420
5421/// Substitute template arguments into the default template argument for
5422/// the given template template parameter.
5423///
5424/// \param SemaRef the semantic analysis object for which we are performing
5425/// the substitution.
5426///
5427/// \param Template the template that we are synthesizing template arguments
5428/// for.
5429///
5430/// \param TemplateLoc the location of the template name that started the
5431/// template-id we are checking.
5432///
5433/// \param RAngleLoc the location of the right angle bracket ('>') that
5434/// terminates the template-id.
5435///
5436/// \param Param the template template parameter whose default we are
5437/// substituting into.
5438///
5439/// \param Converted the list of template arguments provided for template
5440/// parameters that precede \p Param in the template parameter list.
5441///
5442/// \param QualifierLoc Will be set to the nested-name-specifier (with
5443/// source-location information) that precedes the template name.
5444///
5445/// \returns the substituted template argument, or NULL if an error occurred.
5447 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5448 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5450 ArrayRef<TemplateArgument> SugaredConverted,
5451 ArrayRef<TemplateArgument> CanonicalConverted,
5452 NestedNameSpecifierLoc &QualifierLoc) {
5454 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5455 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5456 if (Inst.isInvalid())
5457 return TemplateName();
5458
5459 // Only substitute for the innermost template argument list.
5460 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5461 /*Final=*/true);
5462 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5463 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5464
5465 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5466
5467 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5468 QualifierLoc = A.getTemplateQualifierLoc();
5469 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5471 A.getTemplateNameLoc(), TemplateArgLists);
5472}
5473
5475 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5476 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5477 ArrayRef<TemplateArgument> SugaredConverted,
5478 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5479 HasDefaultArg = false;
5480
5481 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5482 if (!hasReachableDefaultArgument(TypeParm))
5483 return TemplateArgumentLoc();
5484
5485 HasDefaultArg = true;
5486 TemplateArgumentLoc Output;
5487 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5488 RAngleLoc, TypeParm, SugaredConverted,
5489 CanonicalConverted, Output))
5490 return TemplateArgumentLoc();
5491 return Output;
5492 }
5493
5494 if (NonTypeTemplateParmDecl *NonTypeParm
5495 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5496 if (!hasReachableDefaultArgument(NonTypeParm))
5497 return TemplateArgumentLoc();
5498
5499 HasDefaultArg = true;
5500 TemplateArgumentLoc Output;
5501 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5502 RAngleLoc, NonTypeParm, SugaredConverted,
5503 CanonicalConverted, Output))
5504 return TemplateArgumentLoc();
5505 return Output;
5506 }
5507
5508 TemplateTemplateParmDecl *TempTempParm
5510 if (!hasReachableDefaultArgument(TempTempParm))
5511 return TemplateArgumentLoc();
5512
5513 HasDefaultArg = true;
5514 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5515 NestedNameSpecifierLoc QualifierLoc;
5517 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5518 SugaredConverted, CanonicalConverted, QualifierLoc);
5519 if (TName.isNull())
5520 return TemplateArgumentLoc();
5521
5522 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5523 QualifierLoc, A.getTemplateNameLoc());
5524}
5525
5526/// Convert a template-argument that we parsed as a type into a template, if
5527/// possible. C++ permits injected-class-names to perform dual service as
5528/// template template arguments and as template type arguments.
5531 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5532 if (!TagLoc)
5533 return TemplateArgumentLoc();
5534
5535 // If this type was written as an injected-class-name, it can be used as a
5536 // template template argument.
5537 // If this type was written as an injected-class-name, it may have been
5538 // converted to a RecordType during instantiation. If the RecordType is
5539 // *not* wrapped in a TemplateSpecializationType and denotes a class
5540 // template specialization, it must have come from an injected-class-name.
5541
5542 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5543 if (Name.isNull())
5544 return TemplateArgumentLoc();
5545
5546 return TemplateArgumentLoc(Context, Name,
5547 /*TemplateKWLoc=*/SourceLocation(),
5548 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5549}
5550
5553 SourceLocation TemplateLoc,
5554 SourceLocation RAngleLoc,
5555 unsigned ArgumentPackIndex,
5558 // Check template type parameters.
5559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5560 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5561 CTAI.CanonicalConverted);
5562
5563 const TemplateArgument &Arg = ArgLoc.getArgument();
5564 // Check non-type template parameters.
5565 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5566 // Do substitution on the type of the non-type template parameter
5567 // with the template arguments we've seen thus far. But if the
5568 // template has a dependent context then we cannot substitute yet.
5569 QualType NTTPType = NTTP->getType();
5570 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5571 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5572
5573 if (NTTPType->isInstantiationDependentType()) {
5574 // Do substitution on the type of the non-type template parameter.
5575 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5576 CTAI.SugaredConverted,
5577 SourceRange(TemplateLoc, RAngleLoc));
5578 if (Inst.isInvalid())
5579 return true;
5580
5582 /*Final=*/true);
5583 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5584 // If the parameter is a pack expansion, expand this slice of the pack.
5585 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5586 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5587 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5588 NTTP->getDeclName());
5589 } else {
5590 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5591 NTTP->getDeclName());
5592 }
5593
5594 // If that worked, check the non-type template parameter type
5595 // for validity.
5596 if (!NTTPType.isNull())
5597 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5598 NTTP->getLocation());
5599 if (NTTPType.isNull())
5600 return true;
5601 }
5602
5603 auto checkExpr = [&](Expr *E) -> Expr * {
5604 TemplateArgument SugaredResult, CanonicalResult;
5606 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5607 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5608 // If the current template argument causes an error, give up now.
5609 if (Res.isInvalid())
5610 return nullptr;
5611 CTAI.SugaredConverted.push_back(SugaredResult);
5612 CTAI.CanonicalConverted.push_back(CanonicalResult);
5613 return Res.get();
5614 };
5615
5616 switch (Arg.getKind()) {
5618 llvm_unreachable("Should never see a NULL template argument here");
5619
5621 Expr *E = Arg.getAsExpr();
5622 Expr *R = checkExpr(E);
5623 if (!R)
5624 return true;
5625 // If the resulting expression is new, then use it in place of the
5626 // old expression in the template argument.
5627 if (R != E) {
5628 TemplateArgument TA(R, /*IsCanonical=*/false);
5629 ArgLoc = TemplateArgumentLoc(TA, R);
5630 }
5631 break;
5632 }
5633
5634 // As for the converted NTTP kinds, they still might need another
5635 // conversion, as the new corresponding parameter might be different.
5636 // Ideally, we would always perform substitution starting with sugared types
5637 // and never need these, as we would still have expressions. Since these are
5638 // needed so rarely, it's probably a better tradeoff to just convert them
5639 // back to expressions.
5644 // FIXME: StructuralValue is untested here.
5645 ExprResult R =
5647 assert(R.isUsable());
5648 if (!checkExpr(R.get()))
5649 return true;
5650 break;
5651 }
5652
5655 // We were given a template template argument. It may not be ill-formed;
5656 // see below.
5659 // We have a template argument such as \c T::template X, which we
5660 // parsed as a template template argument. However, since we now
5661 // know that we need a non-type template argument, convert this
5662 // template name into an expression.
5663
5664 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5665 ArgLoc.getTemplateNameLoc());
5666
5667 CXXScopeSpec SS;
5668 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5669 // FIXME: the template-template arg was a DependentTemplateName,
5670 // so it was provided with a template keyword. However, its source
5671 // location is not stored in the template argument structure.
5672 SourceLocation TemplateKWLoc;
5674 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5675 nullptr);
5676
5677 // If we parsed the template argument as a pack expansion, create a
5678 // pack expansion expression.
5681 if (E.isInvalid())
5682 return true;
5683 }
5684
5685 TemplateArgument SugaredResult, CanonicalResult;
5687 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5688 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5689 if (E.isInvalid())
5690 return true;
5691
5692 CTAI.SugaredConverted.push_back(SugaredResult);
5693 CTAI.CanonicalConverted.push_back(CanonicalResult);
5694 break;
5695 }
5696
5697 // We have a template argument that actually does refer to a class
5698 // template, alias template, or template template parameter, and
5699 // therefore cannot be a non-type template argument.
5700 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5701 << ArgLoc.getSourceRange();
5703
5704 return true;
5705
5707 // We have a non-type template parameter but the template
5708 // argument is a type.
5709
5710 // C++ [temp.arg]p2:
5711 // In a template-argument, an ambiguity between a type-id and
5712 // an expression is resolved to a type-id, regardless of the
5713 // form of the corresponding template-parameter.
5714 //
5715 // We warn specifically about this case, since it can be rather
5716 // confusing for users.
5717 QualType T = Arg.getAsType();
5718 SourceRange SR = ArgLoc.getSourceRange();
5719 if (T->isFunctionType())
5720 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5721 else
5722 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5724 return true;
5725 }
5726
5728 llvm_unreachable("Caller must expand template argument packs");
5729 }
5730
5731 return false;
5732 }
5733
5734
5735 // Check template template parameters.
5737
5738 TemplateParameterList *Params = TempParm->getTemplateParameters();
5739 if (TempParm->isExpandedParameterPack())
5740 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5741
5742 // Substitute into the template parameter list of the template
5743 // template parameter, since previously-supplied template arguments
5744 // may appear within the template template parameter.
5745 //
5746 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5747 {
5748 // Set up a template instantiation context.
5750 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5751 CTAI.SugaredConverted,
5752 SourceRange(TemplateLoc, RAngleLoc));
5753 if (Inst.isInvalid())
5754 return true;
5755
5756 Params = SubstTemplateParams(
5757 Params, CurContext,
5759 /*Final=*/true),
5760 /*EvaluateConstraints=*/false);
5761 if (!Params)
5762 return true;
5763 }
5764
5765 // C++1z [temp.local]p1: (DR1004)
5766 // When [the injected-class-name] is used [...] as a template-argument for
5767 // a template template-parameter [...] it refers to the class template
5768 // itself.
5769 if (Arg.getKind() == TemplateArgument::Type) {
5771 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5772 if (!ConvertedArg.getArgument().isNull())
5773 ArgLoc = ConvertedArg;
5774 }
5775
5776 switch (Arg.getKind()) {
5778 llvm_unreachable("Should never see a NULL template argument here");
5779
5782 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5783 CTAI.PartialOrdering,
5784 &CTAI.StrictPackMatch))
5785 return true;
5786
5787 CTAI.SugaredConverted.push_back(Arg);
5788 CTAI.CanonicalConverted.push_back(
5789 Context.getCanonicalTemplateArgument(Arg));
5790 break;
5791
5794 auto Kind = 0;
5795 switch (TempParm->templateParameterKind()) {
5797 Kind = 1;
5798 break;
5800 Kind = 2;
5801 break;
5802 default:
5803 break;
5804 }
5805
5806 // We have a template template parameter but the template
5807 // argument does not refer to a template.
5808 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5809 << Kind << getLangOpts().CPlusPlus11;
5810 return true;
5811 }
5812
5817 llvm_unreachable("non-type argument with template template parameter");
5818
5820 llvm_unreachable("Caller must expand template argument packs");
5821 }
5822
5823 return false;
5824}
5825
5826/// Diagnose a missing template argument.
5827template<typename TemplateParmDecl>
5829 TemplateDecl *TD,
5830 const TemplateParmDecl *D,
5832 // Dig out the most recent declaration of the template parameter; there may be
5833 // declarations of the template that are more recent than TD.
5835 ->getTemplateParameters()
5836 ->getParam(D->getIndex()));
5837
5838 // If there's a default argument that's not reachable, diagnose that we're
5839 // missing a module import.
5841 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5843 D->getDefaultArgumentLoc(), Modules,
5845 /*Recover*/true);
5846 return true;
5847 }
5848
5849 // FIXME: If there's a more recent default argument that *is* visible,
5850 // diagnose that it was declared too late.
5851
5853
5854 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5855 << /*not enough args*/0
5857 << TD;
5858 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5859 return true;
5860}
5861
5862/// Check that the given template argument list is well-formed
5863/// for specializing the given template.
5865 TemplateDecl *Template, SourceLocation TemplateLoc,
5866 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5867 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5868 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5870 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5871 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5873}
5874
5875/// Check that the given template argument list is well-formed
5876/// for specializing the given template.
5879 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5880 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5881 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5883
5885 *ConstraintsNotSatisfied = false;
5886
5887 // Make a copy of the template arguments for processing. Only make the
5888 // changes at the end when successful in matching the arguments to the
5889 // template.
5890 TemplateArgumentListInfo NewArgs = TemplateArgs;
5891
5892 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5893
5894 // C++23 [temp.arg.general]p1:
5895 // [...] The type and form of each template-argument specified in
5896 // a template-id shall match the type and form specified for the
5897 // corresponding parameter declared by the template in its
5898 // template-parameter-list.
5899 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5900 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5901 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5902 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5903 LocalInstantiationScope InstScope(*this, true);
5904 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5905 ParamEnd = Params->end(),
5906 Param = ParamBegin;
5907 Param != ParamEnd;
5908 /* increment in loop */) {
5909 if (size_t ParamIdx = Param - ParamBegin;
5910 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5911 // All written arguments should have been consumed by this point.
5912 assert(ArgIdx == NumArgs && "bad default argument deduction");
5913 if (ParamIdx == DefaultArgs.StartPos) {
5914 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5915 // Default arguments from a DeducedTemplateName are already converted.
5916 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5917 CTAI.SugaredConverted.push_back(DefArg);
5918 CTAI.CanonicalConverted.push_back(
5919 Context.getCanonicalTemplateArgument(DefArg));
5920 ++Param;
5921 }
5922 continue;
5923 }
5924 }
5925
5926 // If we have an expanded parameter pack, make sure we don't have too
5927 // many arguments.
5928 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5929 if (*Expansions == SugaredArgumentPack.size()) {
5930 // We're done with this parameter pack. Pack up its arguments and add
5931 // them to the list.
5932 CTAI.SugaredConverted.push_back(
5933 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5934 SugaredArgumentPack.clear();
5935
5936 CTAI.CanonicalConverted.push_back(
5937 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5938 CanonicalArgumentPack.clear();
5939
5940 // This argument is assigned to the next parameter.
5941 ++Param;
5942 continue;
5943 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5944 // Not enough arguments for this parameter pack.
5945 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5946 << /*not enough args*/0
5948 << Template;
5950 return true;
5951 }
5952 }
5953
5954 // Check for builtins producing template packs in this context, we do not
5955 // support them yet.
5956 if (const NonTypeTemplateParmDecl *NTTP =
5957 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5958 NTTP && NTTP->isPackExpansion()) {
5959 auto TL = NTTP->getTypeSourceInfo()
5960 ->getTypeLoc()
5963 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5964 for (const auto &UPP : Unexpanded) {
5965 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5966 if (!TST)
5967 continue;
5968 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5969 // Expanding a built-in pack in this context is not yet supported.
5970 Diag(TL.getEllipsisLoc(),
5971 diag::err_unsupported_builtin_template_pack_expansion)
5972 << TST->getTemplateName();
5973 return true;
5974 }
5975 }
5976
5977 if (ArgIdx < NumArgs) {
5978 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5979 bool NonPackParameter =
5980 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5981 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5982
5983 if (ArgIsExpansion && CTAI.MatchingTTP) {
5984 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5985 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5986 ++Param) {
5987 TemplateArgument &Arg = Args[Param - First];
5988 Arg = ArgLoc.getArgument();
5989 if (!(*Param)->isTemplateParameterPack() ||
5990 getExpandedPackSize(*Param))
5991 Arg = Arg.getPackExpansionPattern();
5992 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5993 SaveAndRestore _1(CTAI.PartialOrdering, false);
5994 SaveAndRestore _2(CTAI.MatchingTTP, true);
5995 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5996 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5998 return true;
5999 Arg = NewArgLoc.getArgument();
6000 CTAI.CanonicalConverted.back().setIsDefaulted(
6001 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6002 CTAI.CanonicalConverted,
6003 Params->getDepth()));
6004 }
6005 ArgLoc = TemplateArgumentLoc(
6008 } else {
6009 SaveAndRestore _1(CTAI.PartialOrdering, false);
6010 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6011 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6013 return true;
6014 CTAI.CanonicalConverted.back().setIsDefaulted(
6015 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6016 *Param, CTAI.CanonicalConverted,
6017 Params->getDepth()));
6018 if (ArgIsExpansion && NonPackParameter) {
6019 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6020 // alias template, builtin template, or concept, and it's not part of
6021 // a parameter pack. This can't be canonicalized, so reject it now.
6023 Template)) {
6024 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6026 : 0;
6027 Diag(ArgLoc.getLocation(),
6028 diag::err_template_expansion_into_fixed_list)
6029 << DiagSelect << ArgLoc.getSourceRange();
6031 return true;
6032 }
6033 }
6034 }
6035
6036 // We're now done with this argument.
6037 ++ArgIdx;
6038
6039 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6040 // Directly convert the remaining arguments, because we don't know what
6041 // parameters they'll match up with.
6042
6043 if (!SugaredArgumentPack.empty()) {
6044 // If we were part way through filling in an expanded parameter pack,
6045 // fall back to just producing individual arguments.
6046 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6047 SugaredArgumentPack.begin(),
6048 SugaredArgumentPack.end());
6049 SugaredArgumentPack.clear();
6050
6051 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6052 CanonicalArgumentPack.begin(),
6053 CanonicalArgumentPack.end());
6054 CanonicalArgumentPack.clear();
6055 }
6056
6057 while (ArgIdx < NumArgs) {
6058 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6059 CTAI.SugaredConverted.push_back(Arg);
6060 CTAI.CanonicalConverted.push_back(
6061 Context.getCanonicalTemplateArgument(Arg));
6062 ++ArgIdx;
6063 }
6064
6065 return false;
6066 }
6067
6068 if ((*Param)->isTemplateParameterPack()) {
6069 // The template parameter was a template parameter pack, so take the
6070 // deduced argument and place it on the argument pack. Note that we
6071 // stay on the same template parameter so that we can deduce more
6072 // arguments.
6073 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6074 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6075 } else {
6076 // Move to the next template parameter.
6077 ++Param;
6078 }
6079 continue;
6080 }
6081
6082 // If we're checking a partial template argument list, we're done.
6083 if (PartialTemplateArgs) {
6084 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6085 CTAI.SugaredConverted.push_back(
6086 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6087 CTAI.CanonicalConverted.push_back(
6088 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6089 }
6090 return false;
6091 }
6092
6093 // If we have a template parameter pack with no more corresponding
6094 // arguments, just break out now and we'll fill in the argument pack below.
6095 if ((*Param)->isTemplateParameterPack()) {
6096 assert(!getExpandedPackSize(*Param) &&
6097 "Should have dealt with this already");
6098
6099 // A non-expanded parameter pack before the end of the parameter list
6100 // only occurs for an ill-formed template parameter list, unless we've
6101 // got a partial argument list for a function template, so just bail out.
6102 if (Param + 1 != ParamEnd) {
6103 assert(
6104 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6105 "Concept templates must have parameter packs at the end.");
6106 return true;
6107 }
6108
6109 CTAI.SugaredConverted.push_back(
6110 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6111 SugaredArgumentPack.clear();
6112
6113 CTAI.CanonicalConverted.push_back(
6114 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6115 CanonicalArgumentPack.clear();
6116
6117 ++Param;
6118 continue;
6119 }
6120
6121 // Check whether we have a default argument.
6122 bool HasDefaultArg;
6123
6124 // Retrieve the default template argument from the template
6125 // parameter. For each kind of template parameter, we substitute the
6126 // template arguments provided thus far and any "outer" template arguments
6127 // (when the template parameter was part of a nested template) into
6128 // the default argument.
6130 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6131 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6132
6133 if (Arg.getArgument().isNull()) {
6134 if (!HasDefaultArg) {
6135 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6136 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6137 NewArgs);
6138 if (NonTypeTemplateParmDecl *NTTP =
6139 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6140 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6141 NewArgs);
6142 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6144 NewArgs);
6145 }
6146 return true;
6147 }
6148
6149 // Introduce an instantiation record that describes where we are using
6150 // the default template argument. We're not actually instantiating a
6151 // template here, we just create this object to put a note into the
6152 // context stack.
6153 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6154 CTAI.SugaredConverted,
6155 SourceRange(TemplateLoc, RAngleLoc));
6156 if (Inst.isInvalid())
6157 return true;
6158
6159 SaveAndRestore _1(CTAI.PartialOrdering, false);
6160 SaveAndRestore _2(CTAI.MatchingTTP, false);
6161 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6162 // Check the default template argument.
6163 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6164 CTAI, CTAK_Specified))
6165 return true;
6166
6167 CTAI.SugaredConverted.back().setIsDefaulted(true);
6168 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6169
6170 // Core issue 150 (assumed resolution): if this is a template template
6171 // parameter, keep track of the default template arguments from the
6172 // template definition.
6173 if (isTemplateTemplateParameter)
6174 NewArgs.addArgument(Arg);
6175
6176 // Move to the next template parameter and argument.
6177 ++Param;
6178 ++ArgIdx;
6179 }
6180
6181 // If we're performing a partial argument substitution, allow any trailing
6182 // pack expansions; they might be empty. This can happen even if
6183 // PartialTemplateArgs is false (the list of arguments is complete but
6184 // still dependent).
6185 if (CTAI.MatchingTTP ||
6187 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6188 while (ArgIdx < NumArgs &&
6189 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6190 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6191 CTAI.SugaredConverted.push_back(Arg);
6192 CTAI.CanonicalConverted.push_back(
6193 Context.getCanonicalTemplateArgument(Arg));
6194 }
6195 }
6196
6197 // If we have any leftover arguments, then there were too many arguments.
6198 // Complain and fail.
6199 if (ArgIdx < NumArgs) {
6200 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6201 << /*too many args*/1
6203 << Template
6204 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6206 return true;
6207 }
6208
6209 // No problems found with the new argument list, propagate changes back
6210 // to caller.
6211 if (UpdateArgsWithConversions)
6212 TemplateArgs = std::move(NewArgs);
6213
6214 if (!PartialTemplateArgs) {
6215 // Setup the context/ThisScope for the case where we are needing to
6216 // re-instantiate constraints outside of normal instantiation.
6217 DeclContext *NewContext = Template->getDeclContext();
6218
6219 // If this template is in a template, make sure we extract the templated
6220 // decl.
6221 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6222 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6223 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6224
6225 Qualifiers ThisQuals;
6226 if (const auto *Method =
6227 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6228 ThisQuals = Method->getMethodQualifiers();
6229
6230 ContextRAII Context(*this, NewContext);
6231 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6232
6234 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6235 /*RelativeToPrimary=*/true,
6236 /*Pattern=*/nullptr,
6237 /*ForConceptInstantiation=*/true);
6238 if (!isa<ConceptDecl>(Template) &&
6240 Template, MLTAL,
6241 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6244 return true;
6245 }
6246 }
6247
6248 return false;
6249}
6250
6251namespace {
6252 class UnnamedLocalNoLinkageFinder
6253 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6254 {
6255 Sema &S;
6256 SourceRange SR;
6257
6259
6260 public:
6261 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6262
6263 bool Visit(QualType T) {
6264 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6265 }
6266
6267#define TYPE(Class, Parent) \
6268 bool Visit##Class##Type(const Class##Type *);
6269#define ABSTRACT_TYPE(Class, Parent) \
6270 bool Visit##Class##Type(const Class##Type *) { return false; }
6271#define NON_CANONICAL_TYPE(Class, Parent) \
6272 bool Visit##Class##Type(const Class##Type *) { return false; }
6273#include "clang/AST/TypeNodes.inc"
6274
6275 bool VisitTagDecl(const TagDecl *Tag);
6276 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6277 };
6278} // end anonymous namespace
6279
6280bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6281 return false;
6282}
6283
6284bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6285 return Visit(T->getElementType());
6286}
6287
6288bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6289 return Visit(T->getPointeeType());
6290}
6291
6292bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6293 const BlockPointerType* T) {
6294 return Visit(T->getPointeeType());
6295}
6296
6297bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6298 const LValueReferenceType* T) {
6299 return Visit(T->getPointeeType());
6300}
6301
6302bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6303 const RValueReferenceType* T) {
6304 return Visit(T->getPointeeType());
6305}
6306
6307bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6308 const MemberPointerType *T) {
6309 if (Visit(T->getPointeeType()))
6310 return true;
6311 if (auto *RD = T->getMostRecentCXXRecordDecl())
6312 return VisitTagDecl(RD);
6313 return VisitNestedNameSpecifier(T->getQualifier());
6314}
6315
6316bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6317 const ConstantArrayType* T) {
6318 return Visit(T->getElementType());
6319}
6320
6321bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6322 const IncompleteArrayType* T) {
6323 return Visit(T->getElementType());
6324}
6325
6326bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6327 const VariableArrayType* T) {
6328 return Visit(T->getElementType());
6329}
6330
6331bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6332 const DependentSizedArrayType* T) {
6333 return Visit(T->getElementType());
6334}
6335
6336bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6337 const DependentSizedExtVectorType* T) {
6338 return Visit(T->getElementType());
6339}
6340
6341bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6342 const DependentSizedMatrixType *T) {
6343 return Visit(T->getElementType());
6344}
6345
6346bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6347 const DependentAddressSpaceType *T) {
6348 return Visit(T->getPointeeType());
6349}
6350
6351bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6352 return Visit(T->getElementType());
6353}
6354
6355bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6356 const DependentVectorType *T) {
6357 return Visit(T->getElementType());
6358}
6359
6360bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6361 return Visit(T->getElementType());
6362}
6363
6364bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6365 const ConstantMatrixType *T) {
6366 return Visit(T->getElementType());
6367}
6368
6369bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6370 const FunctionProtoType* T) {
6371 for (const auto &A : T->param_types()) {
6372 if (Visit(A))
6373 return true;
6374 }
6375
6376 return Visit(T->getReturnType());
6377}
6378
6379bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6380 const FunctionNoProtoType* T) {
6381 return Visit(T->getReturnType());
6382}
6383
6384bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6385 const UnresolvedUsingType*) {
6386 return false;
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6390 return false;
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6394 return Visit(T->getUnmodifiedType());
6395}
6396
6397bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6398 return false;
6399}
6400
6401bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6402 const PackIndexingType *) {
6403 return false;
6404}
6405
6406bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6407 const UnaryTransformType*) {
6408 return false;
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6412 return Visit(T->getDeducedType());
6413}
6414
6415bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6416 const DeducedTemplateSpecializationType *T) {
6417 return Visit(T->getDeducedType());
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6421 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6425 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6429 const TemplateTypeParmType*) {
6430 return false;
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6434 const SubstTemplateTypeParmPackType *) {
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6439 const SubstBuiltinTemplatePackType *) {
6440 return false;
6441}
6442
6443bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6444 const TemplateSpecializationType*) {
6445 return false;
6446}
6447
6448bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6449 const InjectedClassNameType* T) {
6450 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6451}
6452
6453bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6454 const DependentNameType* T) {
6455 return VisitNestedNameSpecifier(T->getQualifier());
6456}
6457
6458bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6459 const PackExpansionType* T) {
6460 return Visit(T->getPattern());
6461}
6462
6463bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6464 return false;
6465}
6466
6467bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6468 const ObjCInterfaceType *) {
6469 return false;
6470}
6471
6472bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6473 const ObjCObjectPointerType *) {
6474 return false;
6475}
6476
6477bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6478 return Visit(T->getValueType());
6479}
6480
6481bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6482 const OverflowBehaviorType *T) {
6483 return Visit(T->getUnderlyingType());
6484}
6485
6486bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6487 return false;
6488}
6489
6490bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6491 return false;
6492}
6493
6494bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6495 const ArrayParameterType *T) {
6496 return VisitConstantArrayType(T);
6497}
6498
6499bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6500 const DependentBitIntType *T) {
6501 return false;
6502}
6503
6504bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6505 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6506 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6507 ? diag::warn_cxx98_compat_template_arg_local_type
6508 : diag::ext_template_arg_local_type)
6509 << S.Context.getCanonicalTagType(Tag) << SR;
6510 return true;
6511 }
6512
6513 if (!Tag->hasNameForLinkage()) {
6514 S.Diag(SR.getBegin(),
6515 S.getLangOpts().CPlusPlus11 ?
6516 diag::warn_cxx98_compat_template_arg_unnamed_type :
6517 diag::ext_template_arg_unnamed_type) << SR;
6518 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6519 return true;
6520 }
6521
6522 return false;
6523}
6524
6525bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6526 NestedNameSpecifier NNS) {
6527 switch (NNS.getKind()) {
6532 return false;
6534 return Visit(QualType(NNS.getAsType(), 0));
6535 }
6536 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6537}
6538
6539bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6540 const HLSLAttributedResourceType *T) {
6541 if (T->hasContainedType() && Visit(T->getContainedType()))
6542 return true;
6543 return Visit(T->getWrappedType());
6544}
6545
6546bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6547 const HLSLInlineSpirvType *T) {
6548 for (auto &Operand : T->getOperands())
6549 if (Operand.isConstant() && Operand.isLiteral())
6550 if (Visit(Operand.getResultType()))
6551 return true;
6552 return false;
6553}
6554
6556 assert(ArgInfo && "invalid TypeSourceInfo");
6557 QualType Arg = ArgInfo->getType();
6558 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6559 QualType CanonArg = Context.getCanonicalType(Arg);
6560
6561 if (CanonArg->isVariablyModifiedType()) {
6562 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6563 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6564 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6565 }
6566
6567 // C++03 [temp.arg.type]p2:
6568 // A local type, a type with no linkage, an unnamed type or a type
6569 // compounded from any of these types shall not be used as a
6570 // template-argument for a template type-parameter.
6571 //
6572 // C++11 allows these, and even in C++03 we allow them as an extension with
6573 // a warning.
6574 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6575 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6576 (void)Finder.Visit(CanonArg);
6577 }
6578
6579 return false;
6580}
6581
6587
6588/// Determine whether the given template argument is a null pointer
6589/// value of the appropriate type.
6592 QualType ParamType, Expr *Arg,
6593 Decl *Entity = nullptr) {
6594 if (Arg->isValueDependent() || Arg->isTypeDependent())
6595 return NPV_NotNullPointer;
6596
6597 // dllimport'd entities aren't constant but are available inside of template
6598 // arguments.
6599 if (Entity && Entity->hasAttr<DLLImportAttr>())
6600 return NPV_NotNullPointer;
6601
6602 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6603 llvm_unreachable(
6604 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6605
6606 if (!S.getLangOpts().CPlusPlus11)
6607 return NPV_NotNullPointer;
6608
6609 // Determine whether we have a constant expression.
6611 if (ArgRV.isInvalid())
6612 return NPV_Error;
6613 Arg = ArgRV.get();
6614
6615 Expr::EvalResult EvalResult;
6617 EvalResult.Diag = &Notes;
6618 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6619 EvalResult.HasSideEffects) {
6620 SourceLocation DiagLoc = Arg->getExprLoc();
6621
6622 // If our only note is the usual "invalid subexpression" note, just point
6623 // the caret at its location rather than producing an essentially
6624 // redundant note.
6625 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6626 diag::note_invalid_subexpr_in_const_expr) {
6627 DiagLoc = Notes[0].first;
6628 Notes.clear();
6629 }
6630
6631 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6632 << Arg->getType() << Arg->getSourceRange();
6633 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6634 S.Diag(Notes[I].first, Notes[I].second);
6635
6637 return NPV_Error;
6638 }
6639
6640 // C++11 [temp.arg.nontype]p1:
6641 // - an address constant expression of type std::nullptr_t
6642 if (Arg->getType()->isNullPtrType())
6643 return NPV_NullPointer;
6644
6645 // - a constant expression that evaluates to a null pointer value (4.10); or
6646 // - a constant expression that evaluates to a null member pointer value
6647 // (4.11); or
6648 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6649 (EvalResult.Val.isMemberPointer() &&
6650 !EvalResult.Val.getMemberPointerDecl())) {
6651 // If our expression has an appropriate type, we've succeeded.
6652 bool ObjCLifetimeConversion;
6653 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6654 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6655 ObjCLifetimeConversion))
6656 return NPV_NullPointer;
6657
6658 // The types didn't match, but we know we got a null pointer; complain,
6659 // then recover as if the types were correct.
6660 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6661 << Arg->getType() << ParamType << Arg->getSourceRange();
6663 return NPV_NullPointer;
6664 }
6665
6666 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6667 // We found a pointer that isn't null, but doesn't refer to an object.
6668 // We could just return NPV_NotNullPointer, but we can print a better
6669 // message with the information we have here.
6670 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6671 << EvalResult.Val.getAsString(S.Context, ParamType);
6673 return NPV_Error;
6674 }
6675
6676 // If we don't have a null pointer value, but we do have a NULL pointer
6677 // constant, suggest a cast to the appropriate type.
6679 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6680 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6681 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6683 ")");
6685 return NPV_NullPointer;
6686 }
6687
6688 // FIXME: If we ever want to support general, address-constant expressions
6689 // as non-type template arguments, we should return the ExprResult here to
6690 // be interpreted by the caller.
6691 return NPV_NotNullPointer;
6692}
6693
6694/// Checks whether the given template argument is compatible with its
6695/// template parameter.
6696static bool
6698 QualType ParamType, Expr *ArgIn,
6699 Expr *Arg, QualType ArgType) {
6700 bool ObjCLifetimeConversion;
6701 if (ParamType->isPointerType() &&
6702 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6703 S.IsQualificationConversion(ArgType, ParamType, false,
6704 ObjCLifetimeConversion)) {
6705 // For pointer-to-object types, qualification conversions are
6706 // permitted.
6707 } else {
6708 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6709 if (!ParamRef->getPointeeType()->isFunctionType()) {
6710 // C++ [temp.arg.nontype]p5b3:
6711 // For a non-type template-parameter of type reference to
6712 // object, no conversions apply. The type referred to by the
6713 // reference may be more cv-qualified than the (otherwise
6714 // identical) type of the template- argument. The
6715 // template-parameter is bound directly to the
6716 // template-argument, which shall be an lvalue.
6717
6718 // FIXME: Other qualifiers?
6719 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6720 unsigned ArgQuals = ArgType.getCVRQualifiers();
6721
6722 if ((ParamQuals | ArgQuals) != ParamQuals) {
6723 S.Diag(Arg->getBeginLoc(),
6724 diag::err_template_arg_ref_bind_ignores_quals)
6725 << ParamType << Arg->getType() << Arg->getSourceRange();
6727 return true;
6728 }
6729 }
6730 }
6731
6732 // At this point, the template argument refers to an object or
6733 // function with external linkage. We now need to check whether the
6734 // argument and parameter types are compatible.
6735 if (!S.Context.hasSameUnqualifiedType(ArgType,
6736 ParamType.getNonReferenceType())) {
6737 // We can't perform this conversion or binding.
6738 if (ParamType->isReferenceType())
6739 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6740 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6741 else
6742 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6743 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6745 return true;
6746 }
6747 }
6748
6749 return false;
6750}
6751
6752/// Checks whether the given template argument is the address
6753/// of an object or function according to C++ [temp.arg.nontype]p1.
6755 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6756 bool IsSpecified, TemplateArgument &SugaredConverted,
6757 TemplateArgument &CanonicalConverted) {
6758 Expr *Arg = ArgIn;
6759 QualType ArgType = Arg->getType();
6760
6761 bool AddressTaken = false;
6762 SourceLocation AddrOpLoc;
6763 if (S.getLangOpts().MicrosoftExt) {
6764 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6765 // dereference and address-of operators.
6766 Arg = Arg->IgnoreParenCasts();
6767
6768 bool ExtWarnMSTemplateArg = false;
6769 UnaryOperatorKind FirstOpKind;
6770 SourceLocation FirstOpLoc;
6771 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6772 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6773 if (UnOpKind == UO_Deref)
6774 ExtWarnMSTemplateArg = true;
6775 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6776 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6777 if (!AddrOpLoc.isValid()) {
6778 FirstOpKind = UnOpKind;
6779 FirstOpLoc = UnOp->getOperatorLoc();
6780 }
6781 } else
6782 break;
6783 }
6784 if (FirstOpLoc.isValid()) {
6785 if (ExtWarnMSTemplateArg)
6786 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6787 << ArgIn->getSourceRange();
6788
6789 if (FirstOpKind == UO_AddrOf)
6790 AddressTaken = true;
6791 else if (Arg->getType()->isPointerType()) {
6792 // We cannot let pointers get dereferenced here, that is obviously not a
6793 // constant expression.
6794 assert(FirstOpKind == UO_Deref);
6795 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6796 << Arg->getSourceRange();
6797 }
6798 }
6799 } else {
6800 // See through any implicit casts we added to fix the type.
6801 // Also ignore parentheses for deduced template arguments.
6802 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6803
6804 // C++ [temp.arg.nontype]p1:
6805 //
6806 // A template-argument for a non-type, non-template
6807 // template-parameter shall be one of: [...]
6808 //
6809 // -- the address of an object or function with external
6810 // linkage, including function templates and function
6811 // template-ids but excluding non-static class members,
6812 // expressed as & id-expression where the & is optional if
6813 // the name refers to a function or array, or if the
6814 // corresponding template-parameter is a reference; or
6815
6816 // In C++98/03 mode, give an extension warning on any extra parentheses.
6817 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6818 if (IsSpecified) {
6819 bool ExtraParens = false;
6820 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6821 if (!ExtraParens) {
6822 S.DiagCompat(Arg->getBeginLoc(),
6823 diag_compat::template_arg_extra_parens)
6824 << Arg->getSourceRange();
6825 ExtraParens = true;
6826 }
6827
6828 Arg = Parens->getSubExpr();
6829 }
6830 }
6831
6832 while (SubstNonTypeTemplateParmExpr *subst =
6833 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6834 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6835
6836 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6837 if (UnOp->getOpcode() == UO_AddrOf) {
6838 Arg = UnOp->getSubExpr();
6839 AddressTaken = true;
6840 AddrOpLoc = UnOp->getOperatorLoc();
6841 }
6842 }
6843
6844 while (SubstNonTypeTemplateParmExpr *subst =
6845 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6846 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6847 }
6848
6849 ValueDecl *Entity = nullptr;
6850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6851 Entity = DRE->getDecl();
6852 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6853 Entity = CUE->getGuidDecl();
6854
6855 // If our parameter has pointer type, check for a null template value.
6856 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6857 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6858 Entity)) {
6859 case NPV_NullPointer:
6860 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6861 SugaredConverted = TemplateArgument(ParamType,
6862 /*isNullPtr=*/true);
6863 CanonicalConverted =
6865 /*isNullPtr=*/true);
6866 return false;
6867
6868 case NPV_Error:
6869 return true;
6870
6871 case NPV_NotNullPointer:
6872 break;
6873 }
6874 }
6875
6876 // Stop checking the precise nature of the argument if it is value dependent,
6877 // it should be checked when instantiated.
6878 if (Arg->isValueDependent()) {
6879 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6880 CanonicalConverted =
6881 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6882 return false;
6883 }
6884
6885 if (!Entity) {
6886 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6887 << Arg->getSourceRange();
6889 return true;
6890 }
6891
6892 // Cannot refer to non-static data members
6893 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6894 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6895 << Entity << Arg->getSourceRange();
6897 return true;
6898 }
6899
6900 // Cannot refer to non-static member functions
6901 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6902 if (!Method->isStatic()) {
6903 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6904 << Method << Arg->getSourceRange();
6906 return true;
6907 }
6908 }
6909
6910 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6911 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6912 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6913
6914 // A non-type template argument must refer to an object or function.
6915 if (!Func && !Var && !Guid) {
6916 // We found something, but we don't know specifically what it is.
6917 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6918 << Arg->getSourceRange();
6919 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6920 return true;
6921 }
6922
6923 // Address / reference template args must have external linkage in C++98.
6924 if (Entity->getFormalLinkage() == Linkage::Internal) {
6925 S.Diag(Arg->getBeginLoc(),
6926 S.getLangOpts().CPlusPlus11
6927 ? diag::warn_cxx98_compat_template_arg_object_internal
6928 : diag::ext_template_arg_object_internal)
6929 << !Func << Entity << Arg->getSourceRange();
6930 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6931 << !Func;
6932 } else if (!Entity->hasLinkage()) {
6933 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6934 << !Func << Entity << Arg->getSourceRange();
6935 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6936 << !Func;
6937 return true;
6938 }
6939
6940 if (Var) {
6941 // A value of reference type is not an object.
6942 if (Var->getType()->isReferenceType()) {
6943 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6944 << Var->getType() << Arg->getSourceRange();
6946 return true;
6947 }
6948
6949 // A template argument must have static storage duration.
6950 if (Var->getTLSKind()) {
6951 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6952 << Arg->getSourceRange();
6953 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6954 return true;
6955 }
6956 }
6957
6958 if (AddressTaken && ParamType->isReferenceType()) {
6959 // If we originally had an address-of operator, but the
6960 // parameter has reference type, complain and (if things look
6961 // like they will work) drop the address-of operator.
6962 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6963 ParamType.getNonReferenceType())) {
6964 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6965 << ParamType;
6967 return true;
6968 }
6969
6970 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6971 << ParamType
6972 << FixItHint::CreateRemoval(AddrOpLoc);
6974
6975 ArgType = Entity->getType();
6976 }
6977
6978 // If the template parameter has pointer type, either we must have taken the
6979 // address or the argument must decay to a pointer.
6980 if (!AddressTaken && ParamType->isPointerType()) {
6981 if (Func) {
6982 // Function-to-pointer decay.
6983 ArgType = S.Context.getPointerType(Func->getType());
6984 } else if (Entity->getType()->isArrayType()) {
6985 // Array-to-pointer decay.
6986 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6987 } else {
6988 // If the template parameter has pointer type but the address of
6989 // this object was not taken, complain and (possibly) recover by
6990 // taking the address of the entity.
6991 ArgType = S.Context.getPointerType(Entity->getType());
6992 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6993 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6994 << ParamType;
6996 return true;
6997 }
6998
6999 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7000 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7001
7003 }
7004 }
7005
7006 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7007 Arg, ArgType))
7008 return true;
7009
7010 // Create the template argument.
7011 SugaredConverted = TemplateArgument(Entity, ParamType);
7012 CanonicalConverted =
7014 S.Context.getCanonicalType(ParamType));
7015 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7016 return false;
7017}
7018
7019/// Checks whether the given template argument is a pointer to
7020/// member constant according to C++ [temp.arg.nontype]p1.
7022 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7023 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7024 bool Invalid = false;
7025
7026 Expr *Arg = ResultArg;
7027 bool ObjCLifetimeConversion;
7028
7029 // C++ [temp.arg.nontype]p1:
7030 //
7031 // A template-argument for a non-type, non-template
7032 // template-parameter shall be one of: [...]
7033 //
7034 // -- a pointer to member expressed as described in 5.3.1.
7035 DeclRefExpr *DRE = nullptr;
7036
7037 // In C++98/03 mode, give an extension warning on any extra parentheses.
7038 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7039 bool ExtraParens = false;
7040 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7041 if (!Invalid && !ExtraParens) {
7042 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7043 << Arg->getSourceRange();
7044 ExtraParens = true;
7045 }
7046
7047 Arg = Parens->getSubExpr();
7048 }
7049
7050 while (SubstNonTypeTemplateParmExpr *subst =
7051 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7052 Arg = subst->getReplacement()->IgnoreImpCasts();
7053
7054 // A pointer-to-member constant written &Class::member.
7055 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7056 if (UnOp->getOpcode() == UO_AddrOf) {
7057 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7058 if (DRE && !DRE->getQualifier())
7059 DRE = nullptr;
7060 }
7061 }
7062 // A constant of pointer-to-member type.
7063 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7064 ValueDecl *VD = DRE->getDecl();
7065 if (VD->getType()->isMemberPointerType()) {
7067 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7068 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7069 CanonicalConverted =
7070 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7071 } else {
7072 SugaredConverted = TemplateArgument(VD, ParamType);
7073 CanonicalConverted =
7075 S.Context.getCanonicalType(ParamType));
7076 }
7077 return Invalid;
7078 }
7079 }
7080
7081 DRE = nullptr;
7082 }
7083
7084 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7085
7086 // Check for a null pointer value.
7087 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7088 Entity)) {
7089 case NPV_Error:
7090 return true;
7091 case NPV_NullPointer:
7092 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7093 SugaredConverted = TemplateArgument(ParamType,
7094 /*isNullPtr*/ true);
7095 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7096 /*isNullPtr*/ true);
7097 return false;
7098 case NPV_NotNullPointer:
7099 break;
7100 }
7101
7102 if (S.IsQualificationConversion(ResultArg->getType(),
7103 ParamType.getNonReferenceType(), false,
7104 ObjCLifetimeConversion)) {
7105 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7106 ResultArg->getValueKind())
7107 .get();
7108 } else if (!S.Context.hasSameUnqualifiedType(
7109 ResultArg->getType(), ParamType.getNonReferenceType())) {
7110 // We can't perform this conversion.
7111 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7112 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7114 return true;
7115 }
7116
7117 if (!DRE)
7118 return S.Diag(Arg->getBeginLoc(),
7119 diag::err_template_arg_not_pointer_to_member_form)
7120 << Arg->getSourceRange();
7121
7122 if (isa<FieldDecl>(DRE->getDecl()) ||
7124 isa<CXXMethodDecl>(DRE->getDecl())) {
7125 assert((isa<FieldDecl>(DRE->getDecl()) ||
7128 ->isImplicitObjectMemberFunction()) &&
7129 "Only non-static member pointers can make it here");
7130
7131 // Okay: this is the address of a non-static member, and therefore
7132 // a member pointer constant.
7133 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7134 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7135 CanonicalConverted =
7136 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7137 } else {
7138 ValueDecl *D = DRE->getDecl();
7139 SugaredConverted = TemplateArgument(D, ParamType);
7140 CanonicalConverted =
7142 S.Context.getCanonicalType(ParamType));
7143 }
7144 return Invalid;
7145 }
7146
7147 // We found something else, but we don't know specifically what it is.
7148 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7149 << Arg->getSourceRange();
7150 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7151 return true;
7152}
7153
7154/// Check a template argument against its corresponding
7155/// non-type template parameter.
7156///
7157/// This routine implements the semantics of C++ [temp.arg.nontype].
7158/// If an error occurred, it returns ExprError(); otherwise, it
7159/// returns the converted template argument. \p ParamType is the
7160/// type of the non-type template parameter after it has been instantiated.
7162 Expr *Arg,
7163 TemplateArgument &SugaredConverted,
7164 TemplateArgument &CanonicalConverted,
7165 bool StrictCheck,
7167 SourceLocation StartLoc = Arg->getBeginLoc();
7168 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7169 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7170 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7171 DeductionArg = NewDeductionArg;
7172 if (ArgPE) {
7173 // Recreate a pack expansion if we unwrapped one.
7174 Arg = new (Context) PackExpansionExpr(
7175 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7176 } else {
7177 Arg = DeductionArg;
7178 }
7179 };
7180
7181 // If the parameter type somehow involves auto, deduce the type now.
7182 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7183 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7184 if (IsDeduced) {
7185 // When checking a deduced template argument, deduce from its type even if
7186 // the type is dependent, in order to check the types of non-type template
7187 // arguments line up properly in partial ordering.
7188 TypeSourceInfo *TSI =
7189 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7191 InitializedEntity Entity =
7194 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7195 Expr *Inits[1] = {DeductionArg};
7196 ParamType =
7198 if (ParamType.isNull())
7199 return ExprError();
7200 } else {
7201 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7202 Param->getTemplateDepth() + 1);
7203 ParamType = QualType();
7205 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7206 /*DependentDeduction=*/true,
7207 // We do not check constraints right now because the
7208 // immediately-declared constraint of the auto type is
7209 // also an associated constraint, and will be checked
7210 // along with the other associated constraints after
7211 // checking the template argument list.
7212 /*IgnoreConstraints=*/true);
7214 ParamType = TSI->getType();
7215 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7217 return ExprError();
7218 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7219 Diag(Arg->getExprLoc(),
7220 diag::err_non_type_template_parm_type_deduction_failure)
7221 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7222 << Arg->getSourceRange();
7224 return ExprError();
7225 }
7226 ParamType = SubstAutoTypeDependent(ParamType);
7227 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7228 }
7229 }
7230 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7231 // an error. The error message normally references the parameter
7232 // declaration, but here we'll pass the argument location because that's
7233 // where the parameter type is deduced.
7234 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7235 if (ParamType.isNull()) {
7237 return ExprError();
7238 }
7239 }
7240
7241 // We should have already dropped all cv-qualifiers by now.
7242 assert(!ParamType.hasQualifiers() &&
7243 "non-type template parameter type cannot be qualified");
7244
7245 // If either the parameter has a dependent type or the argument is
7246 // type-dependent, there's nothing we can check now.
7247 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7248 // Force the argument to the type of the parameter to maintain invariants.
7249 if (!IsDeduced) {
7251 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7252 ParamType->isLValueReferenceType() ? VK_LValue
7253 : ParamType->isRValueReferenceType() ? VK_XValue
7254 : VK_PRValue);
7255 if (E.isInvalid())
7256 return ExprError();
7257 setDeductionArg(E.get());
7258 }
7259 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7260 CanonicalConverted = TemplateArgument(
7261 Context.getCanonicalTemplateArgument(SugaredConverted));
7262 return Arg;
7263 }
7264
7265 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7266 if (CTAK == CTAK_Deduced && !StrictCheck &&
7267 (ParamType->isReferenceType()
7268 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7269 DeductionArg->getType())
7270 : !Context.hasSameUnqualifiedType(ParamType,
7271 DeductionArg->getType()))) {
7272 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7273 // we should actually be checking the type of the template argument in P,
7274 // not the type of the template argument deduced from A, against the
7275 // template parameter type.
7276 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7277 << Arg->getType() << ParamType.getUnqualifiedType();
7279 return ExprError();
7280 }
7281
7282 // If the argument is a pack expansion, we don't know how many times it would
7283 // expand. If we continue checking the argument, this will make the template
7284 // definition ill-formed if it would be ill-formed for any number of
7285 // expansions during instantiation time. When partial ordering or matching
7286 // template template parameters, this is exactly what we want. Otherwise, the
7287 // normal template rules apply: we accept the template if it would be valid
7288 // for any number of expansions (i.e. none).
7289 if (ArgPE && !StrictCheck) {
7290 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7291 CanonicalConverted = TemplateArgument(
7292 Context.getCanonicalTemplateArgument(SugaredConverted));
7293 return Arg;
7294 }
7295
7296 // Avoid making a copy when initializing a template parameter of class type
7297 // from a template parameter object of the same type. This is going beyond
7298 // the standard, but is required for soundness: in
7299 // template<A a> struct X { X *p; X<a> *q; };
7300 // ... we need p and q to have the same type.
7301 //
7302 // Similarly, don't inject a call to a copy constructor when initializing
7303 // from a template parameter of the same type.
7304 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7305 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7306 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7307 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7308 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7309
7310 SugaredConverted = TemplateArgument(TPO, ParamType);
7311 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7312 ParamType.getCanonicalType());
7313 return Arg;
7314 }
7316 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7317 CanonicalConverted =
7318 Context.getCanonicalTemplateArgument(SugaredConverted);
7319 return Arg;
7320 }
7321 }
7322
7323 // The initialization of the parameter from the argument is
7324 // a constant-evaluated context.
7327
7328 bool IsConvertedConstantExpression = true;
7329 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7331 StartLoc, /*DirectInit=*/false, DeductionArg);
7332 Expr *Inits[1] = {DeductionArg};
7333 InitializedEntity Entity =
7335 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7336 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7337 if (Result.isInvalid() || !Result.get())
7338 return ExprError();
7340 if (Result.isInvalid() || !Result.get())
7341 return ExprError();
7342 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7343 /*DiscardedValue=*/false,
7344 /*IsConstexpr=*/true,
7345 /*IsTemplateArgument=*/true)
7346 .get());
7347 IsConvertedConstantExpression = false;
7348 }
7349
7350 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7351 // C++17 [temp.arg.nontype]p1:
7352 // A template-argument for a non-type template parameter shall be
7353 // a converted constant expression of the type of the template-parameter.
7354 APValue Value;
7355 ExprResult ArgResult;
7356 if (IsConvertedConstantExpression) {
7358 DeductionArg, ParamType,
7359 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7360 assert(!ArgResult.isUnset());
7361 if (ArgResult.isInvalid()) {
7363 return ExprError();
7364 }
7365 } else {
7366 ArgResult = DeductionArg;
7367 }
7368
7369 // For a value-dependent argument, CheckConvertedConstantExpression is
7370 // permitted (and expected) to be unable to determine a value.
7371 if (ArgResult.get()->isValueDependent()) {
7372 setDeductionArg(ArgResult.get());
7373 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7374 CanonicalConverted =
7375 Context.getCanonicalTemplateArgument(SugaredConverted);
7376 return Arg;
7377 }
7378
7379 APValue PreNarrowingValue;
7381 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7382 false, PreNarrowingValue);
7383 if (ArgResult.isInvalid())
7384 return ExprError();
7385 setDeductionArg(ArgResult.get());
7386
7387 if (Value.isLValue()) {
7388 APValue::LValueBase Base = Value.getLValueBase();
7389 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7390 // For a non-type template-parameter of pointer or reference type,
7391 // the value of the constant expression shall not refer to
7392 assert(ParamType->isPointerOrReferenceType() ||
7393 ParamType->isNullPtrType());
7394 // -- a temporary object
7395 // -- a string literal
7396 // -- the result of a typeid expression, or
7397 // -- a predefined __func__ variable
7398 if (Base &&
7399 (!VD ||
7401 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7402 << Arg->getSourceRange();
7403 return ExprError();
7404 }
7405
7406 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7407 VD->getType()->isArrayType() &&
7408 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7409 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7410 if (ArgPE) {
7411 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7412 CanonicalConverted =
7413 Context.getCanonicalTemplateArgument(SugaredConverted);
7414 } else {
7415 SugaredConverted = TemplateArgument(VD, ParamType);
7416 CanonicalConverted =
7417 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7418 ParamType.getCanonicalType());
7419 }
7420 return Arg;
7421 }
7422
7423 // -- a subobject [until C++20]
7424 if (!getLangOpts().CPlusPlus20) {
7425 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7426 Value.isLValueOnePastTheEnd()) {
7427 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7428 << Value.getAsString(Context, ParamType);
7429 return ExprError();
7430 }
7431 assert((VD || !ParamType->isReferenceType()) &&
7432 "null reference should not be a constant expression");
7433 assert((!VD || !ParamType->isNullPtrType()) &&
7434 "non-null value of type nullptr_t?");
7435 }
7436 }
7437
7438 if (Value.isAddrLabelDiff())
7439 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7440
7441 if (ArgPE) {
7442 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7443 CanonicalConverted =
7444 Context.getCanonicalTemplateArgument(SugaredConverted);
7445 } else {
7446 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7447 CanonicalConverted =
7449 }
7450 return Arg;
7451 }
7452
7453 // These should have all been handled above using the C++17 rules.
7454 assert(!ArgPE && !StrictCheck);
7455
7456 // C++ [temp.arg.nontype]p5:
7457 // The following conversions are performed on each expression used
7458 // as a non-type template-argument. If a non-type
7459 // template-argument cannot be converted to the type of the
7460 // corresponding template-parameter then the program is
7461 // ill-formed.
7462 if (ParamType->isIntegralOrEnumerationType()) {
7463 // C++11:
7464 // -- for a non-type template-parameter of integral or
7465 // enumeration type, conversions permitted in a converted
7466 // constant expression are applied.
7467 //
7468 // C++98:
7469 // -- for a non-type template-parameter of integral or
7470 // enumeration type, integral promotions (4.5) and integral
7471 // conversions (4.7) are applied.
7472
7473 if (getLangOpts().CPlusPlus11) {
7474 // C++ [temp.arg.nontype]p1:
7475 // A template-argument for a non-type, non-template template-parameter
7476 // shall be one of:
7477 //
7478 // -- for a non-type template-parameter of integral or enumeration
7479 // type, a converted constant expression of the type of the
7480 // template-parameter; or
7481 llvm::APSInt Value;
7483 Arg, ParamType, Value, CCEKind::TemplateArg);
7484 if (ArgResult.isInvalid())
7485 return ExprError();
7486 Arg = ArgResult.get();
7487
7488 // We can't check arbitrary value-dependent arguments.
7489 if (Arg->isValueDependent()) {
7490 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7491 CanonicalConverted =
7492 Context.getCanonicalTemplateArgument(SugaredConverted);
7493 return Arg;
7494 }
7495
7496 // Widen the argument value to sizeof(parameter type). This is almost
7497 // always a no-op, except when the parameter type is bool. In
7498 // that case, this may extend the argument from 1 bit to 8 bits.
7499 QualType IntegerType = ParamType;
7500 if (const auto *ED = IntegerType->getAsEnumDecl())
7501 IntegerType = ED->getIntegerType();
7502 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7503 ? Context.getIntWidth(IntegerType)
7504 : Context.getTypeSize(IntegerType));
7505
7506 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7507 CanonicalConverted =
7508 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7509 return Arg;
7510 }
7511
7512 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7513 if (ArgResult.isInvalid())
7514 return ExprError();
7515 Arg = ArgResult.get();
7516
7517 QualType ArgType = Arg->getType();
7518
7519 // C++ [temp.arg.nontype]p1:
7520 // A template-argument for a non-type, non-template
7521 // template-parameter shall be one of:
7522 //
7523 // -- an integral constant-expression of integral or enumeration
7524 // type; or
7525 // -- the name of a non-type template-parameter; or
7526 llvm::APSInt Value;
7527 if (!ArgType->isIntegralOrEnumerationType()) {
7528 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7529 << ArgType << Arg->getSourceRange();
7531 return ExprError();
7532 }
7533 if (!Arg->isValueDependent()) {
7534 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7535 QualType T;
7536
7537 public:
7538 TmplArgICEDiagnoser(QualType T) : T(T) { }
7539
7540 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7541 SourceLocation Loc) override {
7542 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7543 }
7544 } Diagnoser(ArgType);
7545
7546 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7547 if (!Arg)
7548 return ExprError();
7549 }
7550
7551 // From here on out, all we care about is the unqualified form
7552 // of the argument type.
7553 ArgType = ArgType.getUnqualifiedType();
7554
7555 // Try to convert the argument to the parameter's type.
7556 if (Context.hasSameType(ParamType, ArgType)) {
7557 // Okay: no conversion necessary
7558 } else if (ParamType->isBooleanType()) {
7559 // This is an integral-to-boolean conversion.
7560 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7561 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7562 !ParamType->isEnumeralType()) {
7563 // This is an integral promotion or conversion.
7564 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7565 } else {
7566 // We can't perform this conversion.
7567 Diag(StartLoc, diag::err_template_arg_not_convertible)
7568 << Arg->getType() << ParamType << Arg->getSourceRange();
7570 return ExprError();
7571 }
7572
7573 // Add the value of this argument to the list of converted
7574 // arguments. We use the bitwidth and signedness of the template
7575 // parameter.
7576 if (Arg->isValueDependent()) {
7577 // The argument is value-dependent. Create a new
7578 // TemplateArgument with the converted expression.
7579 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7580 CanonicalConverted =
7581 Context.getCanonicalTemplateArgument(SugaredConverted);
7582 return Arg;
7583 }
7584
7585 QualType IntegerType = ParamType;
7586 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7587 IntegerType = ED->getIntegerType();
7588 }
7589
7590 if (ParamType->isBooleanType()) {
7591 // Value must be zero or one.
7592 Value = Value != 0;
7593 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7594 if (Value.getBitWidth() != AllowedBits)
7595 Value = Value.extOrTrunc(AllowedBits);
7596 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7597 } else {
7598 llvm::APSInt OldValue = Value;
7599
7600 // Coerce the template argument's value to the value it will have
7601 // based on the template parameter's type.
7602 unsigned AllowedBits = IntegerType->isBitIntType()
7603 ? Context.getIntWidth(IntegerType)
7604 : Context.getTypeSize(IntegerType);
7605 if (Value.getBitWidth() != AllowedBits)
7606 Value = Value.extOrTrunc(AllowedBits);
7607 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7608
7609 // Complain if an unsigned parameter received a negative value.
7610 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7611 (OldValue.isSigned() && OldValue.isNegative())) {
7612 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7613 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7614 << Arg->getSourceRange();
7616 }
7617
7618 // Complain if we overflowed the template parameter's type.
7619 unsigned RequiredBits;
7620 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7621 RequiredBits = OldValue.getActiveBits();
7622 else if (OldValue.isUnsigned())
7623 RequiredBits = OldValue.getActiveBits() + 1;
7624 else
7625 RequiredBits = OldValue.getSignificantBits();
7626 if (RequiredBits > AllowedBits) {
7627 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7628 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7629 << Arg->getSourceRange();
7631 }
7632 }
7633
7634 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7635 SugaredConverted = TemplateArgument(Context, Value, T);
7636 CanonicalConverted =
7637 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7638 return Arg;
7639 }
7640
7641 QualType ArgType = Arg->getType();
7642 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7643 bool IsSpecified = CTAK == CTAK_Specified;
7644
7645 // Handle pointer-to-function, reference-to-function, and
7646 // pointer-to-member-function all in (roughly) the same way.
7647 if (// -- For a non-type template-parameter of type pointer to
7648 // function, only the function-to-pointer conversion (4.3) is
7649 // applied. If the template-argument represents a set of
7650 // overloaded functions (or a pointer to such), the matching
7651 // function is selected from the set (13.4).
7652 (ParamType->isPointerType() &&
7653 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7654 // -- For a non-type template-parameter of type reference to
7655 // function, no conversions apply. If the template-argument
7656 // represents a set of overloaded functions, the matching
7657 // function is selected from the set (13.4).
7658 (ParamType->isReferenceType() &&
7659 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7660 // -- For a non-type template-parameter of type pointer to
7661 // member function, no conversions apply. If the
7662 // template-argument represents a set of overloaded member
7663 // functions, the matching member function is selected from
7664 // the set (13.4).
7665 (ParamType->isMemberPointerType() &&
7666 ParamType->castAs<MemberPointerType>()->getPointeeType()
7667 ->isFunctionType())) {
7668
7669 if (Arg->getType() == Context.OverloadTy) {
7670 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7671 true,
7672 FoundResult)) {
7673 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7674 return ExprError();
7675
7676 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7677 if (Res.isInvalid())
7678 return ExprError();
7679 Arg = Res.get();
7680 ArgType = Arg->getType();
7681 } else
7682 return ExprError();
7683 }
7684
7685 if (!ParamType->isMemberPointerType()) {
7687 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7688 CanonicalConverted))
7689 return ExprError();
7690 return Arg;
7691 }
7692
7694 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7695 return ExprError();
7696 return Arg;
7697 }
7698
7699 if (ParamType->isPointerType()) {
7700 // -- for a non-type template-parameter of type pointer to
7701 // object, qualification conversions (4.4) and the
7702 // array-to-pointer conversion (4.2) are applied.
7703 // C++0x also allows a value of std::nullptr_t.
7704 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7705 "Only object pointers allowed here");
7706
7708 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7709 CanonicalConverted))
7710 return ExprError();
7711 return Arg;
7712 }
7713
7714 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7715 // -- For a non-type template-parameter of type reference to
7716 // object, no conversions apply. The type referred to by the
7717 // reference may be more cv-qualified than the (otherwise
7718 // identical) type of the template-argument. The
7719 // template-parameter is bound directly to the
7720 // template-argument, which must be an lvalue.
7721 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7722 "Only object references allowed here");
7723
7724 if (Arg->getType() == Context.OverloadTy) {
7726 ParamRefType->getPointeeType(),
7727 true,
7728 FoundResult)) {
7729 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7730 return ExprError();
7731 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7732 if (Res.isInvalid())
7733 return ExprError();
7734 Arg = Res.get();
7735 ArgType = Arg->getType();
7736 } else
7737 return ExprError();
7738 }
7739
7741 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7742 CanonicalConverted))
7743 return ExprError();
7744 return Arg;
7745 }
7746
7747 // Deal with parameters of type std::nullptr_t.
7748 if (ParamType->isNullPtrType()) {
7749 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7750 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7751 CanonicalConverted =
7752 Context.getCanonicalTemplateArgument(SugaredConverted);
7753 return Arg;
7754 }
7755
7756 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7757 case NPV_NotNullPointer:
7758 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7759 << Arg->getType() << ParamType;
7761 return ExprError();
7762
7763 case NPV_Error:
7764 return ExprError();
7765
7766 case NPV_NullPointer:
7767 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7768 SugaredConverted = TemplateArgument(ParamType,
7769 /*isNullPtr=*/true);
7770 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7771 /*isNullPtr=*/true);
7772 return Arg;
7773 }
7774 }
7775
7776 // -- For a non-type template-parameter of type pointer to data
7777 // member, qualification conversions (4.4) are applied.
7778 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7779
7781 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7782 return ExprError();
7783 return Arg;
7784}
7785
7789
7792 const TemplateArgumentLoc &Arg) {
7793 // C++0x [temp.arg.template]p1:
7794 // A template-argument for a template template-parameter shall be
7795 // the name of a class template or an alias template, expressed as an
7796 // id-expression. When the template-argument names a class template, only
7797 // primary class templates are considered when matching the
7798 // template template argument with the corresponding parameter;
7799 // partial specializations are not considered even if their
7800 // parameter lists match that of the template template parameter.
7801 //
7802
7804 unsigned DiagFoundKind = 0;
7805
7806 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7807 switch (TTP->templateParameterKind()) {
7809 DiagFoundKind = 3;
7810 break;
7812 DiagFoundKind = 2;
7813 break;
7814 default:
7815 DiagFoundKind = 1;
7816 break;
7817 }
7818 Kind = TTP->templateParameterKind();
7819 } else if (isa<ConceptDecl>(Template)) {
7821 DiagFoundKind = 3;
7822 } else if (isa<FunctionTemplateDecl>(Template)) {
7824 DiagFoundKind = 0;
7825 } else if (isa<VarTemplateDecl>(Template)) {
7827 DiagFoundKind = 2;
7828 } else if (isa<ClassTemplateDecl>(Template) ||
7832 DiagFoundKind = 1;
7833 } else {
7834 assert(false && "Unexpected Decl");
7835 }
7836
7837 if (Kind == Param->templateParameterKind()) {
7838 return true;
7839 }
7840
7841 unsigned DiagKind = 0;
7842 switch (Param->templateParameterKind()) {
7844 DiagKind = 2;
7845 break;
7847 DiagKind = 1;
7848 break;
7849 default:
7850 DiagKind = 0;
7851 break;
7852 }
7853 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7854 << DiagKind;
7855 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7856 << DiagFoundKind << Template;
7857 return false;
7858}
7859
7860/// Check a template argument against its corresponding
7861/// template template parameter.
7862///
7863/// This routine implements the semantics of C++ [temp.arg.template].
7864/// It returns true if an error occurred, and false otherwise.
7866 TemplateParameterList *Params,
7868 bool PartialOrdering,
7869 bool *StrictPackMatch) {
7871 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7872 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7873 if (!Template) {
7874 // FIXME: Handle AssumedTemplateNames
7875 // Any dependent template name is fine.
7876 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7877 return false;
7878 }
7879
7880 if (Template->isInvalidDecl())
7881 return true;
7882
7884 return true;
7885 }
7886
7887 // C++1z [temp.arg.template]p3: (DR 150)
7888 // A template-argument matches a template template-parameter P when P
7889 // is at least as specialized as the template-argument A.
7891 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7892 PartialOrdering, StrictPackMatch))
7893 return true;
7894 // P2113
7895 // C++20[temp.func.order]p2
7896 // [...] If both deductions succeed, the partial ordering selects the
7897 // more constrained template (if one exists) as determined below.
7898 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7899 Params->getAssociatedConstraints(ParamsAC);
7900 // C++20[temp.arg.template]p3
7901 // [...] In this comparison, if P is unconstrained, the constraints on A
7902 // are not considered.
7903 if (ParamsAC.empty())
7904 return false;
7905
7906 Template->getAssociatedConstraints(TemplateAC);
7907
7908 bool IsParamAtLeastAsConstrained;
7909 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7910 IsParamAtLeastAsConstrained))
7911 return true;
7912 if (!IsParamAtLeastAsConstrained) {
7913 Diag(Arg.getLocation(),
7914 diag::err_template_template_parameter_not_at_least_as_constrained)
7915 << Template << Param << Arg.getSourceRange();
7916 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7917 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7919 TemplateAC);
7920 return true;
7921 }
7922 return false;
7923}
7924
7926 unsigned HereDiagID,
7927 unsigned ExternalDiagID) {
7928 if (Decl.getLocation().isValid())
7929 return S.Diag(Decl.getLocation(), HereDiagID);
7930
7931 SmallString<128> Str;
7932 llvm::raw_svector_ostream Out(Str);
7934 PP.TerseOutput = 1;
7935 Decl.print(Out, PP);
7936 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7937}
7938
7940 std::optional<SourceRange> ParamRange) {
7942 noteLocation(*this, Decl, diag::note_template_decl_here,
7943 diag::note_template_decl_external);
7944 if (ParamRange && ParamRange->isValid()) {
7945 assert(Decl.getLocation().isValid() &&
7946 "Parameter range has location when Decl does not");
7947 DB << *ParamRange;
7948 }
7949}
7950
7952 noteLocation(*this, Decl, diag::note_template_param_here,
7953 diag::note_template_param_external);
7954}
7955
7956/// Given a non-type template argument that refers to a
7957/// declaration and the type of its corresponding non-type template
7958/// parameter, produce an expression that properly refers to that
7959/// declaration.
7961 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7962 // C++ [temp.param]p8:
7963 //
7964 // A non-type template-parameter of type "array of T" or
7965 // "function returning T" is adjusted to be of type "pointer to
7966 // T" or "pointer to function returning T", respectively.
7967 if (ParamType->isArrayType())
7968 ParamType = Context.getArrayDecayedType(ParamType);
7969 else if (ParamType->isFunctionType())
7970 ParamType = Context.getPointerType(ParamType);
7971
7972 // For a NULL non-type template argument, return nullptr casted to the
7973 // parameter's type.
7974 if (Arg.getKind() == TemplateArgument::NullPtr) {
7975 return ImpCastExprToType(
7976 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7977 ParamType,
7978 ParamType->getAs<MemberPointerType>()
7979 ? CK_NullToMemberPointer
7980 : CK_NullToPointer);
7981 }
7982 assert(Arg.getKind() == TemplateArgument::Declaration &&
7983 "Only declaration template arguments permitted here");
7984
7985 ValueDecl *VD = Arg.getAsDecl();
7986
7987 CXXScopeSpec SS;
7988 if (ParamType->isMemberPointerType()) {
7989 // If this is a pointer to member, we need to use a qualified name to
7990 // form a suitable pointer-to-member constant.
7991 assert(VD->getDeclContext()->isRecord() &&
7992 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7994 CanQualType ClassType =
7995 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7996 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7997 SS.MakeTrivial(Context, Qualifier, Loc);
7998 }
7999
8001 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8002 if (RefExpr.isInvalid())
8003 return ExprError();
8004
8005 // For a pointer, the argument declaration is the pointee. Take its address.
8006 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8007 if (ParamType->isPointerType() && !ElemT.isNull() &&
8008 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8009 // Decay an array argument if we want a pointer to its first element.
8010 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8011 if (RefExpr.isInvalid())
8012 return ExprError();
8013 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8014 // For any other pointer, take the address (or form a pointer-to-member).
8015 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8016 if (RefExpr.isInvalid())
8017 return ExprError();
8018 } else if (ParamType->isRecordType()) {
8019 assert(isa<TemplateParamObjectDecl>(VD) &&
8020 "arg for class template param not a template parameter object");
8021 // No conversions apply in this case.
8022 return RefExpr;
8023 } else {
8024 assert(ParamType->isReferenceType() &&
8025 "unexpected type for decl template argument");
8026 // If the parameter has reference type, wrap it in paretheses so that this
8027 // expression will have the correct type under `decltype`.
8028 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8029 }
8030
8031 // At this point we should have the right value category.
8032 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8033 "value kind mismatch for non-type template argument");
8034
8035 // The type of the template parameter can differ from the type of the
8036 // argument in various ways; convert it now if necessary.
8037 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8038 QualType SrcExprType = RefExpr.get()->getType();
8039 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8040 CastKind CK;
8041 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8042 IsFunctionConversion(SrcExprType, DestExprType)) {
8043 CK = CK_NoOp;
8044 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8045 CK = CK_BitCast;
8046 } else {
8047 // FIXME: Pointers to members can need conversion derived-to-base or
8048 // base-to-derived conversions. We currently don't retain enough
8049 // information to convert properly (we need to track a cast path or
8050 // subobject number in the template argument).
8051 llvm_unreachable(
8052 "unexpected conversion required for non-type template argument");
8053 }
8054 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8055 RefExpr.get()->getValueKind());
8056 }
8057
8058 return RefExpr;
8059}
8060
8061/// Construct a new expression that refers to the given
8062/// integral template argument with the given source-location
8063/// information.
8064///
8065/// This routine takes care of the mapping from an integral template
8066/// argument (which may have any integral type) to the appropriate
8067/// literal value.
8069 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8070 assert(OrigT->isIntegralOrEnumerationType());
8071
8072 // If this is an enum type that we're instantiating, we need to use an integer
8073 // type the same size as the enumerator. We don't want to build an
8074 // IntegerLiteral with enum type. The integer type of an enum type can be of
8075 // any integral type with C++11 enum classes, make sure we create the right
8076 // type of literal for it.
8077 QualType T = OrigT;
8078 if (const auto *ED = OrigT->getAsEnumDecl())
8079 T = ED->getIntegerType();
8080
8081 Expr *E;
8082 if (T->isAnyCharacterType()) {
8084 if (T->isWideCharType())
8086 else if (T->isChar8Type() && S.getLangOpts().Char8)
8088 else if (T->isChar16Type())
8090 else if (T->isChar32Type())
8092 else
8094
8095 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8096 } else if (T->isBooleanType()) {
8097 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8098 } else {
8099 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8100 }
8101
8102 if (OrigT->isEnumeralType()) {
8103 // FIXME: This is a hack. We need a better way to handle substituted
8104 // non-type template parameters.
8105 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8106 nullptr, S.CurFPFeatureOverrides(),
8107 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8108 Loc, Loc);
8109 }
8110
8111 return E;
8112}
8113
8115 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8116 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8117 auto *ILE = new (S.Context)
8118 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8119 ILE->setType(T);
8120 return ILE;
8121 };
8122
8123 switch (Val.getKind()) {
8125 // This cannot occur in a template argument at all.
8126 case APValue::Array:
8127 case APValue::Struct:
8128 case APValue::Union:
8129 // These can only occur within a template parameter object, which is
8130 // represented as a TemplateArgument::Declaration.
8131 llvm_unreachable("unexpected template argument value");
8132
8133 case APValue::Int:
8135 Loc);
8136
8137 case APValue::Float:
8138 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8139 T, Loc);
8140
8143 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8144 Val.getFixedPoint().getScale());
8145
8146 case APValue::ComplexInt: {
8147 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8149 S, ElemT, Val.getComplexIntReal(), Loc),
8151 S, ElemT, Val.getComplexIntImag(), Loc)});
8152 }
8153
8154 case APValue::ComplexFloat: {
8155 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8156 return MakeInitList(
8158 ElemT, Loc),
8160 ElemT, Loc)});
8161 }
8162
8163 case APValue::Vector: {
8164 QualType ElemT = T->castAs<VectorType>()->getElementType();
8166 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8168 S, ElemT, Val.getVectorElt(I), Loc));
8169 return MakeInitList(Elts);
8170 }
8171
8172 case APValue::Matrix:
8173 llvm_unreachable("Matrix template argument expression not yet supported");
8174
8175 case APValue::None:
8177 llvm_unreachable("Unexpected APValue kind.");
8178 case APValue::LValue:
8180 // There isn't necessarily a valid equivalent source-level syntax for
8181 // these; in particular, a naive lowering might violate access control.
8182 // So for now we lower to a ConstantExpr holding the value, wrapped around
8183 // an OpaqueValueExpr.
8184 // FIXME: We should have a better representation for this.
8186 if (T->isReferenceType()) {
8187 T = T->getPointeeType();
8188 VK = VK_LValue;
8189 }
8190 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8191 return ConstantExpr::Create(S.Context, OVE, Val);
8192 }
8193 llvm_unreachable("Unhandled APValue::ValueKind enum");
8194}
8195
8198 SourceLocation Loc) {
8199 switch (Arg.getKind()) {
8205 llvm_unreachable("not a non-type template argument");
8206
8208 return Arg.getAsExpr();
8209
8213 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8214
8217 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8218
8221 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8222 }
8223 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8224}
8225
8226/// Match two template parameters within template parameter lists.
8228 Sema &S, NamedDecl *New,
8229 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8230 const NamedDecl *OldInstFrom, bool Complain,
8232 // Check the actual kind (type, non-type, template).
8233 if (Old->getKind() != New->getKind()) {
8234 if (Complain) {
8235 unsigned NextDiag = diag::err_template_param_different_kind;
8236 if (TemplateArgLoc.isValid()) {
8237 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8238 NextDiag = diag::note_template_param_different_kind;
8239 }
8240 S.Diag(New->getLocation(), NextDiag)
8241 << (Kind != Sema::TPL_TemplateMatch);
8242 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8243 << (Kind != Sema::TPL_TemplateMatch);
8244 }
8245
8246 return false;
8247 }
8248
8249 // Check that both are parameter packs or neither are parameter packs.
8250 // However, if we are matching a template template argument to a
8251 // template template parameter, the template template parameter can have
8252 // a parameter pack where the template template argument does not.
8253 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8254 if (Complain) {
8255 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8256 if (TemplateArgLoc.isValid()) {
8257 S.Diag(TemplateArgLoc,
8258 diag::err_template_arg_template_params_mismatch);
8259 NextDiag = diag::note_template_parameter_pack_non_pack;
8260 }
8261
8262 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8264 : 2;
8265 S.Diag(New->getLocation(), NextDiag)
8266 << ParamKind << New->isParameterPack();
8267 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8268 << ParamKind << Old->isParameterPack();
8269 }
8270
8271 return false;
8272 }
8273 // For non-type template parameters, check the type of the parameter.
8274 if (NonTypeTemplateParmDecl *OldNTTP =
8275 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8277
8278 // If we are matching a template template argument to a template
8279 // template parameter and one of the non-type template parameter types
8280 // is dependent, then we must wait until template instantiation time
8281 // to actually compare the arguments.
8283 (!OldNTTP->getType()->isDependentType() &&
8284 !NewNTTP->getType()->isDependentType())) {
8285 // C++20 [temp.over.link]p6:
8286 // Two [non-type] template-parameters are equivalent [if] they have
8287 // equivalent types ignoring the use of type-constraints for
8288 // placeholder types
8289 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8290 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8291 if (!S.Context.hasSameType(OldType, NewType)) {
8292 if (Complain) {
8293 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8294 if (TemplateArgLoc.isValid()) {
8295 S.Diag(TemplateArgLoc,
8296 diag::err_template_arg_template_params_mismatch);
8297 NextDiag = diag::note_template_nontype_parm_different_type;
8298 }
8299 S.Diag(NewNTTP->getLocation(), NextDiag)
8300 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8301 S.Diag(OldNTTP->getLocation(),
8302 diag::note_template_nontype_parm_prev_declaration)
8303 << OldNTTP->getType();
8304 }
8305 return false;
8306 }
8307 }
8308 }
8309 // For template template parameters, check the template parameter types.
8310 // The template parameter lists of template template
8311 // parameters must agree.
8312 else if (TemplateTemplateParmDecl *OldTTP =
8313 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8315 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8316 return false;
8318 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8319 OldTTP->getTemplateParameters(), Complain,
8322 : Kind),
8323 TemplateArgLoc))
8324 return false;
8325 }
8326
8330 const Expr *NewC = nullptr, *OldC = nullptr;
8331
8333 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8334 NewC = TC->getImmediatelyDeclaredConstraint();
8335 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8336 OldC = TC->getImmediatelyDeclaredConstraint();
8337 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8338 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8339 ->getPlaceholderTypeConstraint())
8340 NewC = E;
8341 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8342 ->getPlaceholderTypeConstraint())
8343 OldC = E;
8344 } else
8345 llvm_unreachable("unexpected template parameter type");
8346
8347 auto Diagnose = [&] {
8348 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8349 diag::err_template_different_type_constraint);
8350 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8351 diag::note_template_prev_declaration) << /*declaration*/0;
8352 };
8353
8354 if (!NewC != !OldC) {
8355 if (Complain)
8356 Diagnose();
8357 return false;
8358 }
8359
8360 if (NewC) {
8361 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8362 NewC)) {
8363 if (Complain)
8364 Diagnose();
8365 return false;
8366 }
8367 }
8368 }
8369
8370 return true;
8371}
8372
8373/// Diagnose a known arity mismatch when comparing template argument
8374/// lists.
8375static
8380 SourceLocation TemplateArgLoc) {
8381 unsigned NextDiag = diag::err_template_param_list_different_arity;
8382 if (TemplateArgLoc.isValid()) {
8383 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8384 NextDiag = diag::note_template_param_list_different_arity;
8385 }
8386 S.Diag(New->getTemplateLoc(), NextDiag)
8387 << (New->size() > Old->size())
8388 << (Kind != Sema::TPL_TemplateMatch)
8389 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8390 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8391 << (Kind != Sema::TPL_TemplateMatch)
8392 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8393}
8394
8397 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8398 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8399 if (Old->size() != New->size()) {
8400 if (Complain)
8402 TemplateArgLoc);
8403
8404 return false;
8405 }
8406
8407 // C++0x [temp.arg.template]p3:
8408 // A template-argument matches a template template-parameter (call it P)
8409 // when each of the template parameters in the template-parameter-list of
8410 // the template-argument's corresponding class template or alias template
8411 // (call it A) matches the corresponding template parameter in the
8412 // template-parameter-list of P. [...]
8413 TemplateParameterList::iterator NewParm = New->begin();
8414 TemplateParameterList::iterator NewParmEnd = New->end();
8415 for (TemplateParameterList::iterator OldParm = Old->begin(),
8416 OldParmEnd = Old->end();
8417 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8418 if (NewParm == NewParmEnd) {
8419 if (Complain)
8421 TemplateArgLoc);
8422 return false;
8423 }
8424 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8425 OldInstFrom, Complain, Kind,
8426 TemplateArgLoc))
8427 return false;
8428 }
8429
8430 // Make sure we exhausted all of the arguments.
8431 if (NewParm != NewParmEnd) {
8432 if (Complain)
8434 TemplateArgLoc);
8435
8436 return false;
8437 }
8438
8439 if (Kind != TPL_TemplateParamsEquivalent) {
8440 const Expr *NewRC = New->getRequiresClause();
8441 const Expr *OldRC = Old->getRequiresClause();
8442
8443 auto Diagnose = [&] {
8444 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8445 diag::err_template_different_requires_clause);
8446 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8447 diag::note_template_prev_declaration) << /*declaration*/0;
8448 };
8449
8450 if (!NewRC != !OldRC) {
8451 if (Complain)
8452 Diagnose();
8453 return false;
8454 }
8455
8456 if (NewRC) {
8457 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8458 NewRC)) {
8459 if (Complain)
8460 Diagnose();
8461 return false;
8462 }
8463 }
8464 }
8465
8466 return true;
8467}
8468
8469bool
8471 if (!S)
8472 return false;
8473
8474 // Find the nearest enclosing declaration scope.
8475 S = S->getDeclParent();
8476
8477 // C++ [temp.pre]p6: [P2096]
8478 // A template, explicit specialization, or partial specialization shall not
8479 // have C linkage.
8480 DeclContext *Ctx = S->getEntity();
8481 if (Ctx && Ctx->isExternCContext()) {
8482 SourceRange Range =
8483 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8484 ? TemplateParams->getParam(0)->getSourceRange()
8485 : TemplateParams->getSourceRange();
8486 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8487 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8488 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8489 return true;
8490 }
8491 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8492
8493 // C++ [temp]p2:
8494 // A template-declaration can appear only as a namespace scope or
8495 // class scope declaration.
8496 // C++ [temp.expl.spec]p3:
8497 // An explicit specialization may be declared in any scope in which the
8498 // corresponding primary template may be defined.
8499 // C++ [temp.class.spec]p6: [P2096]
8500 // A partial specialization may be declared in any scope in which the
8501 // corresponding primary template may be defined.
8502 if (Ctx) {
8503 if (Ctx->isFileContext())
8504 return false;
8505 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8506 // C++ [temp.mem]p2:
8507 // A local class shall not have member templates.
8508 if (RD->isLocalClass())
8509 return Diag(TemplateParams->getTemplateLoc(),
8510 diag::err_template_inside_local_class)
8511 << TemplateParams->getSourceRange();
8512 else
8513 return false;
8514 }
8515 }
8516
8517 return Diag(TemplateParams->getTemplateLoc(),
8518 diag::err_template_outside_namespace_or_class_scope)
8519 << TemplateParams->getSourceRange();
8520}
8521
8522/// Determine what kind of template specialization the given declaration
8523/// is.
8525 if (!D)
8526 return TSK_Undeclared;
8527
8528 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8529 return Record->getTemplateSpecializationKind();
8530 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8531 return Function->getTemplateSpecializationKind();
8532 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8533 return Var->getTemplateSpecializationKind();
8534
8535 return TSK_Undeclared;
8536}
8537
8538/// Check whether a specialization is well-formed in the current
8539/// context.
8540///
8541/// This routine determines whether a template specialization can be declared
8542/// in the current context (C++ [temp.expl.spec]p2).
8543///
8544/// \param S the semantic analysis object for which this check is being
8545/// performed.
8546///
8547/// \param Specialized the entity being specialized or instantiated, which
8548/// may be a kind of template (class template, function template, etc.) or
8549/// a member of a class template (member function, static data member,
8550/// member class).
8551///
8552/// \param PrevDecl the previous declaration of this entity, if any.
8553///
8554/// \param Loc the location of the explicit specialization or instantiation of
8555/// this entity.
8556///
8557/// \param IsPartialSpecialization whether this is a partial specialization of
8558/// a class template.
8559///
8560/// \returns true if there was an error that we cannot recover from, false
8561/// otherwise.
8563 NamedDecl *Specialized,
8564 NamedDecl *PrevDecl,
8565 SourceLocation Loc,
8567 // Keep these "kind" numbers in sync with the %select statements in the
8568 // various diagnostics emitted by this routine.
8569 int EntityKind = 0;
8570 if (isa<ClassTemplateDecl>(Specialized))
8571 EntityKind = IsPartialSpecialization? 1 : 0;
8572 else if (isa<VarTemplateDecl>(Specialized))
8573 EntityKind = IsPartialSpecialization ? 3 : 2;
8574 else if (isa<FunctionTemplateDecl>(Specialized))
8575 EntityKind = 4;
8576 else if (isa<CXXMethodDecl>(Specialized))
8577 EntityKind = 5;
8578 else if (isa<VarDecl>(Specialized))
8579 EntityKind = 6;
8580 else if (isa<RecordDecl>(Specialized))
8581 EntityKind = 7;
8582 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8583 EntityKind = 8;
8584 else {
8585 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8586 << S.getLangOpts().CPlusPlus11;
8587 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8588 return true;
8589 }
8590
8591 // C++ [temp.expl.spec]p2:
8592 // An explicit specialization may be declared in any scope in which
8593 // the corresponding primary template may be defined.
8595 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8596 << Specialized;
8597 return true;
8598 }
8599
8600 // C++ [temp.class.spec]p6:
8601 // A class template partial specialization may be declared in any
8602 // scope in which the primary template may be defined.
8603 DeclContext *SpecializedContext =
8604 Specialized->getDeclContext()->getRedeclContext();
8606
8607 // Make sure that this redeclaration (or definition) occurs in the same
8608 // scope or an enclosing namespace.
8609 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8610 : DC->Equals(SpecializedContext))) {
8611 if (isa<TranslationUnitDecl>(SpecializedContext))
8612 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8613 << EntityKind << Specialized;
8614 else {
8615 auto *ND = cast<NamedDecl>(SpecializedContext);
8616 int Diag = diag::err_template_spec_redecl_out_of_scope;
8617 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8618 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8619 S.Diag(Loc, Diag) << EntityKind << Specialized
8620 << ND << isa<CXXRecordDecl>(ND);
8621 }
8622
8623 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8624
8625 // Don't allow specializing in the wrong class during error recovery.
8626 // Otherwise, things can go horribly wrong.
8627 if (DC->isRecord())
8628 return true;
8629 }
8630
8631 return false;
8632}
8633
8635 if (!E->isTypeDependent())
8636 return SourceLocation();
8637 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8638 Checker.TraverseStmt(E);
8639 if (Checker.MatchLoc.isInvalid())
8640 return E->getSourceRange();
8641 return Checker.MatchLoc;
8642}
8643
8644static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8645 if (!TL.getType()->isDependentType())
8646 return SourceLocation();
8647 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8648 Checker.TraverseTypeLoc(TL);
8649 if (Checker.MatchLoc.isInvalid())
8650 return TL.getSourceRange();
8651 return Checker.MatchLoc;
8652}
8653
8654/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8655/// that checks non-type template partial specialization arguments.
8657 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8658 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8659 bool HasError = false;
8660 for (unsigned I = 0; I != NumArgs; ++I) {
8661 if (Args[I].getKind() == TemplateArgument::Pack) {
8663 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8664 Args[I].pack_size(), IsDefaultArgument))
8665 return true;
8666
8667 continue;
8668 }
8669
8670 if (Args[I].getKind() != TemplateArgument::Expression)
8671 continue;
8672
8673 Expr *ArgExpr = Args[I].getAsExpr();
8674 if (ArgExpr->containsErrors()) {
8675 HasError = true;
8676 continue;
8677 }
8678
8679 // We can have a pack expansion of any of the bullets below.
8680 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8681 ArgExpr = Expansion->getPattern();
8682
8683 // Strip off any implicit casts we added as part of type checking.
8684 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8685 ArgExpr = ICE->getSubExpr();
8686
8687 // C++ [temp.class.spec]p8:
8688 // A non-type argument is non-specialized if it is the name of a
8689 // non-type parameter. All other non-type arguments are
8690 // specialized.
8691 //
8692 // Below, we check the two conditions that only apply to
8693 // specialized non-type arguments, so skip any non-specialized
8694 // arguments.
8695 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8696 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8697 continue;
8698
8699 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8700 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8701 continue;
8702 }
8703
8704 // C++ [temp.class.spec]p9:
8705 // Within the argument list of a class template partial
8706 // specialization, the following restrictions apply:
8707 // -- A partially specialized non-type argument expression
8708 // shall not involve a template parameter of the partial
8709 // specialization except when the argument expression is a
8710 // simple identifier.
8711 // -- The type of a template parameter corresponding to a
8712 // specialized non-type argument shall not be dependent on a
8713 // parameter of the specialization.
8714 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8715 // We implement a compromise between the original rules and DR1315:
8716 // -- A specialized non-type template argument shall not be
8717 // type-dependent and the corresponding template parameter
8718 // shall have a non-dependent type.
8719 SourceRange ParamUseRange =
8720 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8721 if (ParamUseRange.isValid()) {
8722 if (IsDefaultArgument) {
8723 S.Diag(TemplateNameLoc,
8724 diag::err_dependent_non_type_arg_in_partial_spec);
8725 S.Diag(ParamUseRange.getBegin(),
8726 diag::note_dependent_non_type_default_arg_in_partial_spec)
8727 << ParamUseRange;
8728 } else {
8729 S.Diag(ParamUseRange.getBegin(),
8730 diag::err_dependent_non_type_arg_in_partial_spec)
8731 << ParamUseRange;
8732 }
8733 return true;
8734 }
8735
8736 ParamUseRange = findTemplateParameter(
8737 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8738 if (ParamUseRange.isValid()) {
8739 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8740 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8741 << Param->getType();
8743 return true;
8744 }
8745 }
8746
8747 return HasError;
8748}
8749
8751 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8752 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8753 // We have to be conservative when checking a template in a dependent
8754 // context.
8755 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8756 return false;
8757
8758 TemplateParameterList *TemplateParams =
8759 PrimaryTemplate->getTemplateParameters();
8760 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8762 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8763 if (!Param)
8764 continue;
8765
8766 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8767 Param, &TemplateArgs[I],
8768 1, I >= NumExplicit))
8769 return true;
8770 }
8771
8772 return false;
8773}
8774
8776 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8777 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8779 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8780 assert(TUK != TagUseKind::Reference && "References are not specializations");
8781
8782 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8783 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8784 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8785
8786 // Find the class template we're specializing
8787 TemplateName Name = TemplateId.Template.get();
8789 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8790
8791 if (!ClassTemplate) {
8792 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8793 << (Name.getAsTemplateDecl() &&
8795 return true;
8796 }
8797
8798 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8799 auto Message = DSA->getMessage();
8800 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8801 << ClassTemplate << !Message.empty() << Message;
8802 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8803 }
8804
8805 if (S->isTemplateParamScope())
8806 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8807
8808 DeclContext *DC = ClassTemplate->getDeclContext();
8809
8810 bool isMemberSpecialization = false;
8811 bool isPartialSpecialization = false;
8812
8813 if (SS.isSet()) {
8814 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8815 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8816 TemplateNameLoc, &TemplateId,
8817 /*IsMemberSpecialization=*/false))
8818 return true;
8819 }
8820
8821 // Check the validity of the template headers that introduce this
8822 // template.
8823 // FIXME: We probably shouldn't complain about these headers for
8824 // friend declarations.
8825 bool Invalid = false;
8826 TemplateParameterList *TemplateParams =
8828 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8829 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8830 if (Invalid)
8831 return true;
8832
8833 // Check that we can declare a template specialization here.
8834 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8835 return true;
8836
8837 if (TemplateParams && DC->isDependentContext()) {
8838 ContextRAII SavedContext(*this, DC);
8840 return true;
8841 }
8842
8843 if (TemplateParams && TemplateParams->size() > 0) {
8844 isPartialSpecialization = true;
8845
8846 if (TUK == TagUseKind::Friend) {
8847 Diag(KWLoc, diag::err_partial_specialization_friend)
8848 << SourceRange(LAngleLoc, RAngleLoc);
8849 return true;
8850 }
8851
8852 // C++ [temp.class.spec]p10:
8853 // The template parameter list of a specialization shall not
8854 // contain default template argument values.
8855 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8856 Decl *Param = TemplateParams->getParam(I);
8857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8858 if (TTP->hasDefaultArgument()) {
8859 Diag(TTP->getDefaultArgumentLoc(),
8860 diag::err_default_arg_in_partial_spec);
8861 TTP->removeDefaultArgument();
8862 }
8863 } else if (NonTypeTemplateParmDecl *NTTP
8864 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8865 if (NTTP->hasDefaultArgument()) {
8866 Diag(NTTP->getDefaultArgumentLoc(),
8867 diag::err_default_arg_in_partial_spec)
8868 << NTTP->getDefaultArgument().getSourceRange();
8869 NTTP->removeDefaultArgument();
8870 }
8871 } else {
8873 if (TTP->hasDefaultArgument()) {
8875 diag::err_default_arg_in_partial_spec)
8877 TTP->removeDefaultArgument();
8878 }
8879 }
8880 }
8881 } else if (TemplateParams) {
8882 if (TUK == TagUseKind::Friend)
8883 Diag(KWLoc, diag::err_template_spec_friend)
8885 SourceRange(TemplateParams->getTemplateLoc(),
8886 TemplateParams->getRAngleLoc()))
8887 << SourceRange(LAngleLoc, RAngleLoc);
8888 } else {
8889 assert(TUK == TagUseKind::Friend &&
8890 "should have a 'template<>' for this decl");
8891 }
8892
8893 // Check that the specialization uses the same tag kind as the
8894 // original template.
8896 assert(Kind != TagTypeKind::Enum &&
8897 "Invalid enum tag in class template spec!");
8898 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8899 TUK == TagUseKind::Definition, KWLoc,
8900 ClassTemplate->getIdentifier())) {
8901 Diag(KWLoc, diag::err_use_with_wrong_tag)
8902 << ClassTemplate
8904 ClassTemplate->getTemplatedDecl()->getKindName());
8905 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8906 diag::note_previous_use);
8907 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8908 }
8909
8910 // Translate the parser's template argument list in our AST format.
8911 TemplateArgumentListInfo TemplateArgs =
8912 makeTemplateArgumentListInfo(*this, TemplateId);
8913
8914 // Check for unexpanded parameter packs in any of the template arguments.
8915 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8916 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8917 isPartialSpecialization
8920 return true;
8921
8922 // Check that the template argument list is well-formed for this
8923 // template.
8925 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8926 /*DefaultArgs=*/{},
8927 /*PartialTemplateArgs=*/false, CTAI,
8928 /*UpdateArgsWithConversions=*/true))
8929 return true;
8930
8931 // Find the class template (partial) specialization declaration that
8932 // corresponds to these arguments.
8933 if (isPartialSpecialization) {
8935 TemplateArgs.size(),
8936 CTAI.CanonicalConverted))
8937 return true;
8938
8939 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8940 // also do it during instantiation.
8941 if (!Name.isDependent() &&
8942 !TemplateSpecializationType::anyDependentTemplateArguments(
8943 TemplateArgs, CTAI.CanonicalConverted)) {
8944 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8945 << ClassTemplate->getDeclName();
8946 isPartialSpecialization = false;
8947 Invalid = true;
8948 }
8949 }
8950
8951 void *InsertPos = nullptr;
8952 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8953
8954 if (isPartialSpecialization)
8955 PrevDecl = ClassTemplate->findPartialSpecialization(
8956 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8957 else
8958 PrevDecl =
8959 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8960
8962
8963 // Check whether we can declare a class template specialization in
8964 // the current scope.
8965 if (TUK != TagUseKind::Friend &&
8967 TemplateNameLoc,
8968 isPartialSpecialization))
8969 return true;
8970
8971 if (!isPartialSpecialization) {
8972 // Create a new class template specialization declaration node for
8973 // this explicit specialization or friend declaration.
8975 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8976 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8977 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8979 if (TemplateParameterLists.size() > 0) {
8980 Specialization->setTemplateParameterListsInfo(Context,
8981 TemplateParameterLists);
8982 }
8983
8984 if (!PrevDecl)
8985 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8986 } else {
8988 Context.getCanonicalTemplateSpecializationType(
8990 TemplateName(ClassTemplate->getCanonicalDecl()),
8991 CTAI.CanonicalConverted));
8992 if (Context.hasSameType(
8993 CanonType,
8994 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8995 (!Context.getLangOpts().CPlusPlus20 ||
8996 !TemplateParams->hasAssociatedConstraints())) {
8997 // C++ [temp.class.spec]p9b3:
8998 //
8999 // -- The argument list of the specialization shall not be identical
9000 // to the implicit argument list of the primary template.
9001 //
9002 // This rule has since been removed, because it's redundant given DR1495,
9003 // but we keep it because it produces better diagnostics and recovery.
9004 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9005 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9006 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9007 return CheckClassTemplate(
9008 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9009 TemplateNameLoc, Attr, TemplateParams, AS_none,
9010 /*ModulePrivateLoc=*/SourceLocation(),
9011 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9012 TemplateParameterLists.data(), isMemberSpecialization);
9013 }
9014
9015 // Create a new class template partial specialization declaration node.
9017 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9020 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9021 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9022 Partial->setTemplateArgsAsWritten(TemplateArgs);
9023 SetNestedNameSpecifier(*this, Partial, SS);
9024 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9026 Context, TemplateParameterLists.drop_back(1));
9027 }
9028
9029 if (!PrevPartial)
9030 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9031 Specialization = Partial;
9032
9033 // If we are providing an explicit specialization of a member class
9034 // template specialization, make a note of that.
9035 if (isMemberSpecialization)
9036 Partial->setMemberSpecialization();
9037
9039 }
9040
9041 // C++ [temp.expl.spec]p6:
9042 // If a template, a member template or the member of a class template is
9043 // explicitly specialized then that specialization shall be declared
9044 // before the first use of that specialization that would cause an implicit
9045 // instantiation to take place, in every translation unit in which such a
9046 // use occurs; no diagnostic is required.
9047 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9048 bool Okay = false;
9049 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9050 // Is there any previous explicit specialization declaration?
9052 Okay = true;
9053 break;
9054 }
9055 }
9056
9057 if (!Okay) {
9058 SourceRange Range(TemplateNameLoc, RAngleLoc);
9059 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9060 << Context.getCanonicalTagType(Specialization) << Range;
9061
9062 Diag(PrevDecl->getPointOfInstantiation(),
9063 diag::note_instantiation_required_here)
9064 << (PrevDecl->getTemplateSpecializationKind()
9066 return true;
9067 }
9068 }
9069
9070 // If this is not a friend, note that this is an explicit specialization.
9071 if (TUK != TagUseKind::Friend)
9072 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9073
9074 // Check that this isn't a redefinition of this specialization.
9075 if (TUK == TagUseKind::Definition) {
9076 RecordDecl *Def = Specialization->getDefinition();
9077 NamedDecl *Hidden = nullptr;
9078 bool HiddenDefVisible = false;
9079 if (Def && SkipBody &&
9080 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9081 SkipBody->ShouldSkip = true;
9082 SkipBody->Previous = Def;
9083 if (!HiddenDefVisible && Hidden)
9085 } else if (Def) {
9086 SourceRange Range(TemplateNameLoc, RAngleLoc);
9087 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9088 Diag(Def->getLocation(), diag::note_previous_definition);
9089 Specialization->setInvalidDecl();
9090 return true;
9091 }
9092 }
9093
9096
9097 // Add alignment attributes if necessary; these attributes are checked when
9098 // the ASTContext lays out the structure.
9099 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9100 if (LangOpts.HLSL)
9101 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9104 }
9105
9106 if (ModulePrivateLoc.isValid())
9107 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9108 << (isPartialSpecialization? 1 : 0)
9109 << FixItHint::CreateRemoval(ModulePrivateLoc);
9110
9111 // C++ [temp.expl.spec]p9:
9112 // A template explicit specialization is in the scope of the
9113 // namespace in which the template was defined.
9114 //
9115 // We actually implement this paragraph where we set the semantic
9116 // context (in the creation of the ClassTemplateSpecializationDecl),
9117 // but we also maintain the lexical context where the actual
9118 // definition occurs.
9119 Specialization->setLexicalDeclContext(CurContext);
9120
9121 // We may be starting the definition of this specialization.
9122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9123 Specialization->startDefinition();
9124
9125 if (TUK == TagUseKind::Friend) {
9126 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9127 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9128 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9130 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9131 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9132
9133 // Build the fully-sugared type for this class template
9134 // specialization as the user wrote in the specialization
9135 // itself. This means that we'll pretty-print the type retrieved
9136 // from the specialization's declaration the way that the user
9137 // actually wrote the specialization, rather than formatting the
9138 // name based on the "canonical" representation used to store the
9139 // template arguments in the specialization.
9141 TemplateNameLoc,
9142 WrittenTy,
9143 /*FIXME:*/KWLoc);
9144 Friend->setAccess(AS_public);
9145 CurContext->addDecl(Friend);
9146 } else {
9147 // Add the specialization into its lexical context, so that it can
9148 // be seen when iterating through the list of declarations in that
9149 // context. However, specializations are not found by name lookup.
9150 CurContext->addDecl(Specialization);
9151 }
9152
9153 if (SkipBody && SkipBody->ShouldSkip)
9154 return SkipBody->Previous;
9155
9156 Specialization->setInvalidDecl(Invalid);
9158 return Specialization;
9159}
9160
9162 MultiTemplateParamsArg TemplateParameterLists,
9163 Declarator &D) {
9164 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9165 ActOnDocumentableDecl(NewDecl);
9166 return NewDecl;
9167}
9168
9170 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9171 const IdentifierInfo *Name, SourceLocation NameLoc) {
9172 DeclContext *DC = CurContext;
9173
9174 if (!DC->getRedeclContext()->isFileContext()) {
9175 Diag(NameLoc,
9176 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9177 return nullptr;
9178 }
9179
9180 if (TemplateParameterLists.size() > 1) {
9181 Diag(NameLoc, diag::err_concept_extra_headers);
9182 return nullptr;
9183 }
9184
9185 TemplateParameterList *Params = TemplateParameterLists.front();
9186
9187 if (Params->size() == 0) {
9188 Diag(NameLoc, diag::err_concept_no_parameters);
9189 return nullptr;
9190 }
9191
9192 // Ensure that the parameter pack, if present, is the last parameter in the
9193 // template.
9194 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9195 ParamEnd = Params->end();
9196 ParamIt != ParamEnd; ++ParamIt) {
9197 Decl const *Param = *ParamIt;
9198 if (Param->isParameterPack()) {
9199 if (++ParamIt == ParamEnd)
9200 break;
9201 Diag(Param->getLocation(),
9202 diag::err_template_param_pack_must_be_last_template_parameter);
9203 return nullptr;
9204 }
9205 }
9206
9207 ConceptDecl *NewDecl =
9208 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9209
9210 if (NewDecl->hasAssociatedConstraints()) {
9211 // C++2a [temp.concept]p4:
9212 // A concept shall not have associated constraints.
9213 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9214 NewDecl->setInvalidDecl();
9215 }
9216
9217 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9218 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9220 LookupName(Previous, S);
9221 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9222 /*AllowInlineNamespace*/ false);
9223
9224 // We cannot properly handle redeclarations until we parse the constraint
9225 // expression, so only inject the name if we are sure we are not redeclaring a
9226 // symbol
9227 if (Previous.empty())
9228 PushOnScopeChains(NewDecl, S, true);
9229
9230 return NewDecl;
9231}
9232
9234 bool Found = false;
9235 LookupResult::Filter F = R.makeFilter();
9236 while (F.hasNext()) {
9237 NamedDecl *D = F.next();
9238 if (D == C) {
9239 F.erase();
9240 Found = true;
9241 break;
9242 }
9243 }
9244 F.done();
9245 return Found;
9246}
9247
9250 Expr *ConstraintExpr,
9251 const ParsedAttributesView &Attrs) {
9252 assert(!C->hasDefinition() && "Concept already defined");
9253 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9254 C->setInvalidDecl();
9255 return nullptr;
9256 }
9257 C->setDefinition(ConstraintExpr);
9258 ProcessDeclAttributeList(S, C, Attrs);
9259
9260 // Check for conflicting previous declaration.
9261 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9262 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9264 LookupName(Previous, S);
9265 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9266 /*AllowInlineNamespace*/ false);
9267 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9268 bool AddToScope = true;
9269 CheckConceptRedefinition(C, Previous, AddToScope);
9270
9272 if (!WasAlreadyAdded && AddToScope)
9273 PushOnScopeChains(C, S);
9274
9275 return C;
9276}
9277
9279 LookupResult &Previous, bool &AddToScope) {
9280 AddToScope = true;
9281
9282 if (Previous.empty())
9283 return;
9284
9285 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9286 if (!OldConcept) {
9287 auto *Old = Previous.getRepresentativeDecl();
9288 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9289 << NewDecl->getDeclName();
9290 notePreviousDefinition(Old, NewDecl->getLocation());
9291 AddToScope = false;
9292 return;
9293 }
9294 // Check if we can merge with a concept declaration.
9295 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9296 if (!IsSame) {
9297 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9298 << NewDecl->getDeclName();
9299 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9300 AddToScope = false;
9301 return;
9302 }
9303 if (hasReachableDefinition(OldConcept) &&
9304 IsRedefinitionInModule(NewDecl, OldConcept)) {
9305 Diag(NewDecl->getLocation(), diag::err_redefinition)
9306 << NewDecl->getDeclName();
9307 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9308 AddToScope = false;
9309 return;
9310 }
9311 if (!Previous.isSingleResult()) {
9312 // FIXME: we should produce an error in case of ambig and failed lookups.
9313 // Other decls (e.g. namespaces) also have this shortcoming.
9314 return;
9315 }
9316 // We unwrap canonical decl late to check for module visibility.
9317 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9318}
9319
9321 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9322 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9323 Diag(Loc, diag::err_recursive_concept) << CE;
9324 Diag(CE->getLocation(), diag::note_declared_at);
9325 CE->setInvalidDecl();
9326 return true;
9327 }
9328 // Concept template parameters don't have a definition and can't
9329 // be defined recursively.
9330 return false;
9331}
9332
9333/// \brief Strips various properties off an implicit instantiation
9334/// that has just been explicitly specialized.
9335static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9336 if (MinGW || (isa<FunctionDecl>(D) &&
9337 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9338 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9339
9340 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9341 FD->setInlineSpecified(false);
9342}
9343
9344/// Create an ExplicitInstantiationDecl to record source-location info for an
9345/// explicit template instantiation statement, and add it to \p CurContext.
9346///
9347/// For class templates / nested classes, the caller should build a
9348/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9349/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9350///
9351/// For function / variable templates, the caller should pass TypeAsWritten for
9352/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9354 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9355 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9356 NestedNameSpecifierLoc QualifierLoc,
9357 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9358 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9360 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9361 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9362 Context.addExplicitInstantiationDecl(Spec, EID);
9363 CurContext->addDecl(EID);
9364}
9365
9366/// Compute the diagnostic location for an explicit instantiation
9367// declaration or definition.
9368static SourceLocation
9370 SourceLocation PointOfInstantiation) {
9371 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9372 if (EID->getTemplateSpecializationKind() ==
9374 return EID->getTemplateLoc();
9375
9376 // Explicit instantiations following a specialization have no effect and
9377 // hence no PointOfInstantiation. In that case, walk decl backwards
9378 // until a valid name loc is found.
9379 SourceLocation PrevDiagLoc = PointOfInstantiation;
9380 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9381 Prev = Prev->getPreviousDecl()) {
9382 PrevDiagLoc = Prev->getLocation();
9383 }
9384 assert(PrevDiagLoc.isValid() &&
9385 "Explicit instantiation without point of instantiation?");
9386 return PrevDiagLoc;
9387}
9388
9389bool
9392 NamedDecl *PrevDecl,
9394 SourceLocation PrevPointOfInstantiation,
9395 bool &HasNoEffect) {
9396 HasNoEffect = false;
9397
9398 switch (NewTSK) {
9399 case TSK_Undeclared:
9401 assert(
9402 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9403 "previous declaration must be implicit!");
9404 return false;
9405
9407 switch (PrevTSK) {
9408 case TSK_Undeclared:
9410 // Okay, we're just specializing something that is either already
9411 // explicitly specialized or has merely been mentioned without any
9412 // instantiation.
9413 return false;
9414
9416 if (PrevPointOfInstantiation.isInvalid()) {
9417 // The declaration itself has not actually been instantiated, so it is
9418 // still okay to specialize it.
9420 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9421 return false;
9422 }
9423 // Fall through
9424 [[fallthrough]];
9425
9428 assert((PrevTSK == TSK_ImplicitInstantiation ||
9429 PrevPointOfInstantiation.isValid()) &&
9430 "Explicit instantiation without point of instantiation?");
9431
9432 // C++ [temp.expl.spec]p6:
9433 // If a template, a member template or the member of a class template
9434 // is explicitly specialized then that specialization shall be declared
9435 // before the first use of that specialization that would cause an
9436 // implicit instantiation to take place, in every translation unit in
9437 // which such a use occurs; no diagnostic is required.
9438 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9439 // Is there any previous explicit specialization declaration?
9441 return false;
9442 }
9443
9444 Diag(NewLoc, diag::err_specialization_after_instantiation)
9445 << PrevDecl;
9446 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9447 << (PrevTSK != TSK_ImplicitInstantiation);
9448
9449 return true;
9450 }
9451 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9452
9454 switch (PrevTSK) {
9456 // This explicit instantiation declaration is redundant (that's okay).
9457 HasNoEffect = true;
9458 return false;
9459
9460 case TSK_Undeclared:
9462 // We're explicitly instantiating something that may have already been
9463 // implicitly instantiated; that's fine.
9464 return false;
9465
9467 // C++0x [temp.explicit]p4:
9468 // For a given set of template parameters, if an explicit instantiation
9469 // of a template appears after a declaration of an explicit
9470 // specialization for that template, the explicit instantiation has no
9471 // effect.
9472 HasNoEffect = true;
9473 return false;
9474
9476 // C++0x [temp.explicit]p10:
9477 // If an entity is the subject of both an explicit instantiation
9478 // declaration and an explicit instantiation definition in the same
9479 // translation unit, the definition shall follow the declaration.
9480 Diag(NewLoc,
9481 diag::err_explicit_instantiation_declaration_after_definition);
9482
9483 // Explicit instantiations following a specialization have no effect and
9484 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9485 // until a valid name loc is found.
9486 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9487 diag::note_explicit_instantiation_definition_here);
9488 HasNoEffect = true;
9489 return false;
9490 }
9491 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9492
9494 switch (PrevTSK) {
9495 case TSK_Undeclared:
9497 // We're explicitly instantiating something that may have already been
9498 // implicitly instantiated; that's fine.
9499 return false;
9500
9502 // C++ DR 259, C++0x [temp.explicit]p4:
9503 // For a given set of template parameters, if an explicit
9504 // instantiation of a template appears after a declaration of
9505 // an explicit specialization for that template, the explicit
9506 // instantiation has no effect.
9507 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9508 << PrevDecl;
9509 Diag(PrevDecl->getLocation(),
9510 diag::note_previous_template_specialization);
9511 HasNoEffect = true;
9512 return false;
9513
9515 // We're explicitly instantiating a definition for something for which we
9516 // were previously asked to suppress instantiations. That's fine.
9517
9518 // C++0x [temp.explicit]p4:
9519 // For a given set of template parameters, if an explicit instantiation
9520 // of a template appears after a declaration of an explicit
9521 // specialization for that template, the explicit instantiation has no
9522 // effect.
9523 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9524 // Is there any previous explicit specialization declaration?
9526 HasNoEffect = true;
9527 break;
9528 }
9529 }
9530
9531 return false;
9532
9534 // C++0x [temp.spec]p5:
9535 // For a given template and a given set of template-arguments,
9536 // - an explicit instantiation definition shall appear at most once
9537 // in a program,
9538
9539 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9540 Diag(NewLoc, (getLangOpts().MSVCCompat)
9541 ? diag::ext_explicit_instantiation_duplicate
9542 : diag::err_explicit_instantiation_duplicate)
9543 << PrevDecl;
9544 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9545 diag::note_previous_explicit_instantiation);
9546 HasNoEffect = true;
9547 return false;
9548 }
9549 }
9550
9551 llvm_unreachable("Missing specialization/instantiation case?");
9552}
9553
9555 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9557 // Remove anything from Previous that isn't a function template in
9558 // the correct context.
9559 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9560 LookupResult::Filter F = Previous.makeFilter();
9561 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9562 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9563 while (F.hasNext()) {
9564 NamedDecl *D = F.next()->getUnderlyingDecl();
9565 if (!isa<FunctionTemplateDecl>(D)) {
9566 F.erase();
9567 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9568 continue;
9569 }
9570
9571 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9573 F.erase();
9574 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9575 continue;
9576 }
9577 }
9578 F.done();
9579
9580 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9581 if (Previous.empty()) {
9582 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9583 << IsFriend;
9584 for (auto &P : DiscardedCandidates)
9585 Diag(P.second->getLocation(),
9586 diag::note_dependent_function_template_spec_discard_reason)
9587 << P.first << IsFriend;
9588 return true;
9589 }
9590
9592 ExplicitTemplateArgs);
9593 return false;
9594}
9595
9597 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9598 LookupResult &Previous, bool QualifiedFriend) {
9599 // The set of function template specializations that could match this
9600 // explicit function template specialization.
9601 UnresolvedSet<8> Candidates;
9602 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9603 /*ForTakingAddress=*/false);
9604
9605 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9606 ConvertedTemplateArgs;
9607
9608 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9609 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9610 I != E; ++I) {
9611 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9612 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9613 // Only consider templates found within the same semantic lookup scope as
9614 // FD.
9615 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9617 continue;
9618
9619 QualType FT = FD->getType();
9620 // C++11 [dcl.constexpr]p8:
9621 // A constexpr specifier for a non-static member function that is not
9622 // a constructor declares that member function to be const.
9623 //
9624 // When matching a constexpr member function template specialization
9625 // against the primary template, we don't yet know whether the
9626 // specialization has an implicit 'const' (because we don't know whether
9627 // it will be a static member function until we know which template it
9628 // specializes). This rule was removed in C++14.
9629 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9630 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9632 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9633 if (OldMD && OldMD->isConst()) {
9634 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9636 EPI.TypeQuals.addConst();
9637 FT = Context.getFunctionType(FPT->getReturnType(),
9638 FPT->getParamTypes(), EPI);
9639 }
9640 }
9641
9643 if (ExplicitTemplateArgs)
9644 Args = *ExplicitTemplateArgs;
9645
9646 // C++ [temp.expl.spec]p11:
9647 // A trailing template-argument can be left unspecified in the
9648 // template-id naming an explicit function template specialization
9649 // provided it can be deduced from the function argument type.
9650 // Perform template argument deduction to determine whether we may be
9651 // specializing this template.
9652 // FIXME: It is somewhat wasteful to build
9653 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9654 FunctionDecl *Specialization = nullptr;
9656 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9657 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9659 // Template argument deduction failed; record why it failed, so
9660 // that we can provide nifty diagnostics.
9661 FailedCandidates.addCandidate().set(
9662 I.getPair(), FunTmpl->getTemplatedDecl(),
9663 MakeDeductionFailureInfo(Context, TDK, Info));
9664 (void)TDK;
9665 continue;
9666 }
9667
9668 // Target attributes are part of the cuda function signature, so
9669 // the deduced template's cuda target must match that of the
9670 // specialization. Given that C++ template deduction does not
9671 // take target attributes into account, we reject candidates
9672 // here that have a different target.
9673 if (LangOpts.CUDA &&
9674 CUDA().IdentifyTarget(Specialization,
9675 /* IgnoreImplicitHDAttr = */ true) !=
9676 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9677 FailedCandidates.addCandidate().set(
9678 I.getPair(), FunTmpl->getTemplatedDecl(),
9681 continue;
9682 }
9683
9684 // Record this candidate.
9685 if (ExplicitTemplateArgs)
9686 ConvertedTemplateArgs[Specialization] = std::move(Args);
9687 Candidates.addDecl(Specialization, I.getAccess());
9688 }
9689 }
9690
9691 // For a qualified friend declaration (with no explicit marker to indicate
9692 // that a template specialization was intended), note all (template and
9693 // non-template) candidates.
9694 if (QualifiedFriend && Candidates.empty()) {
9695 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9696 << FD->getDeclName() << FDLookupContext;
9697 // FIXME: We should form a single candidate list and diagnose all
9698 // candidates at once, to get proper sorting and limiting.
9699 for (auto *OldND : Previous) {
9700 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9701 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9702 }
9703 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9704 return true;
9705 }
9706
9707 // Find the most specialized function template.
9709 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9710 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9711 PDiag(diag::err_function_template_spec_ambiguous)
9712 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9713 PDiag(diag::note_function_template_spec_matched));
9714
9715 if (Result == Candidates.end())
9716 return true;
9717
9718 // Ignore access information; it doesn't figure into redeclaration checking.
9720
9721 if (const auto *PT = Specialization->getPrimaryTemplate();
9722 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9723 auto Message = DSA->getMessage();
9724 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9725 << PT << !Message.empty() << Message;
9726 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9727 }
9728
9729 // C++23 [except.spec]p13:
9730 // An exception specification is considered to be needed when:
9731 // - [...]
9732 // - the exception specification is compared to that of another declaration
9733 // (e.g., an explicit specialization or an overriding virtual function);
9734 // - [...]
9735 //
9736 // The exception specification of a defaulted function is evaluated as
9737 // described above only when needed; similarly, the noexcept-specifier of a
9738 // specialization of a function template or member function of a class
9739 // template is instantiated only when needed.
9740 //
9741 // The standard doesn't specify what the "comparison with another declaration"
9742 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9743 // not state which properties of an explicit specialization must match the
9744 // primary template.
9745 //
9746 // We assume that an explicit specialization must correspond with (per
9747 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9748 // the declaration produced by substitution into the function template.
9749 //
9750 // Since the determination whether two function declarations correspond does
9751 // not consider exception specification, we only need to instantiate it once
9752 // we determine the primary template when comparing types per
9753 // [basic.link]p11.1.
9754 auto *SpecializationFPT =
9755 Specialization->getType()->castAs<FunctionProtoType>();
9756 // If the function has a dependent exception specification, resolve it after
9757 // we have selected the primary template so we can check whether it matches.
9758 if (getLangOpts().CPlusPlus17 &&
9759 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9760 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9761 return true;
9762
9764 = Specialization->getTemplateSpecializationInfo();
9765 assert(SpecInfo && "Function template specialization info missing?");
9766
9767 // Note: do not overwrite location info if previous template
9768 // specialization kind was explicit.
9770 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9771 Specialization->setLocation(FD->getLocation());
9772 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9773 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9774 // function can differ from the template declaration with respect to
9775 // the constexpr specifier.
9776 // FIXME: We need an update record for this AST mutation.
9777 // FIXME: What if there are multiple such prior declarations (for instance,
9778 // from different modules)?
9779 Specialization->setConstexprKind(FD->getConstexprKind());
9780 }
9781
9782 // FIXME: Check if the prior specialization has a point of instantiation.
9783 // If so, we have run afoul of .
9784
9785 // If this is a friend declaration, then we're not really declaring
9786 // an explicit specialization.
9787 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9788
9789 // Check the scope of this explicit specialization.
9790 if (!isFriend &&
9792 Specialization->getPrimaryTemplate(),
9794 false))
9795 return true;
9796
9797 // C++ [temp.expl.spec]p6:
9798 // If a template, a member template or the member of a class template is
9799 // explicitly specialized then that specialization shall be declared
9800 // before the first use of that specialization that would cause an implicit
9801 // instantiation to take place, in every translation unit in which such a
9802 // use occurs; no diagnostic is required.
9803 bool HasNoEffect = false;
9804 if (!isFriend &&
9809 SpecInfo->getPointOfInstantiation(),
9810 HasNoEffect))
9811 return true;
9812
9813 // Mark the prior declaration as an explicit specialization, so that later
9814 // clients know that this is an explicit specialization.
9815 // A dependent friend specialization which has a definition should be treated
9816 // as explicit specialization, despite being invalid.
9817 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9818 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9819 // Since explicit specializations do not inherit '=delete' from their
9820 // primary function template - check if the 'specialization' that was
9821 // implicitly generated (during template argument deduction for partial
9822 // ordering) from the most specialized of all the function templates that
9823 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9824 // first check that it was implicitly generated during template argument
9825 // deduction by making sure it wasn't referenced, and then reset the deleted
9826 // flag to not-deleted, so that we can inherit that information from 'FD'.
9827 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9828 !Specialization->getCanonicalDecl()->isReferenced()) {
9829 // FIXME: This assert will not hold in the presence of modules.
9830 assert(
9831 Specialization->getCanonicalDecl() == Specialization &&
9832 "This must be the only existing declaration of this specialization");
9833 // FIXME: We need an update record for this AST mutation.
9834 Specialization->setDeletedAsWritten(false);
9835 }
9836 // FIXME: We need an update record for this AST mutation.
9839 }
9840
9841 // Turn the given function declaration into a function template
9842 // specialization, with the template arguments from the previous
9843 // specialization.
9844 // Take copies of (semantic and syntactic) template argument lists.
9846 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9847 FD->setFunctionTemplateSpecialization(
9848 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9850 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9851
9852 // A function template specialization inherits the target attributes
9853 // of its template. (We require the attributes explicitly in the
9854 // code to match, but a template may have implicit attributes by
9855 // virtue e.g. of being constexpr, and it passes these implicit
9856 // attributes on to its specializations.)
9857 if (LangOpts.CUDA)
9858 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9859
9860 // The "previous declaration" for this function template specialization is
9861 // the prior function template specialization.
9862 Previous.clear();
9863 Previous.addDecl(Specialization);
9864 return false;
9865}
9866
9867bool
9869 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9870 "Only for non-template members");
9871
9872 // Try to find the member we are instantiating.
9873 NamedDecl *FoundInstantiation = nullptr;
9874 NamedDecl *Instantiation = nullptr;
9875 NamedDecl *InstantiatedFrom = nullptr;
9876 MemberSpecializationInfo *MSInfo = nullptr;
9877
9878 if (Previous.empty()) {
9879 // Nowhere to look anyway.
9880 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9881 UnresolvedSet<8> Candidates;
9882 for (NamedDecl *Candidate : Previous) {
9883 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9884 // Ignore any candidates that aren't member functions.
9885 if (!Method)
9886 continue;
9887
9888 QualType Adjusted = Function->getType();
9889 if (!hasExplicitCallingConv(Adjusted))
9890 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9891 // Ignore any candidates with the wrong type.
9892 // This doesn't handle deduced return types, but both function
9893 // declarations should be undeduced at this point.
9894 // FIXME: The exception specification should probably be ignored when
9895 // comparing the types.
9896 if (!Context.hasSameType(Adjusted, Method->getType()))
9897 continue;
9898
9899 // Ignore any candidates with unsatisfied constraints.
9900 if (ConstraintSatisfaction Satisfaction;
9901 Method->getTrailingRequiresClause() &&
9902 (CheckFunctionConstraints(Method, Satisfaction,
9903 /*UsageLoc=*/Member->getLocation(),
9904 /*ForOverloadResolution=*/true) ||
9905 !Satisfaction.IsSatisfied))
9906 continue;
9907
9908 Candidates.addDecl(Candidate);
9909 }
9910
9911 // If we have no viable candidates left after filtering, we are done.
9912 if (Candidates.empty())
9913 return false;
9914
9915 // Find the function that is more constrained than every other function it
9916 // has been compared to.
9917 UnresolvedSetIterator Best = Candidates.begin();
9918 CXXMethodDecl *BestMethod = nullptr;
9919 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9920 I != E; ++I) {
9921 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9922 if (I == Best ||
9923 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9924 Best = I;
9925 BestMethod = Method;
9926 }
9927 }
9928
9929 FoundInstantiation = *Best;
9930 Instantiation = BestMethod;
9931 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9932 MSInfo = BestMethod->getMemberSpecializationInfo();
9933
9934 // Make sure the best candidate is more constrained than all of the others.
9935 bool Ambiguous = false;
9936 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9937 I != E; ++I) {
9938 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9939 if (I != Best &&
9940 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9941 Ambiguous = true;
9942 break;
9943 }
9944 }
9945
9946 if (Ambiguous) {
9947 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9948 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9949 for (NamedDecl *Candidate : Candidates) {
9950 Candidate = Candidate->getUnderlyingDecl();
9951 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9952 << Candidate;
9953 }
9954 return true;
9955 }
9956 } else if (isa<VarDecl>(Member)) {
9957 VarDecl *PrevVar;
9958 if (Previous.isSingleResult() &&
9959 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9960 if (PrevVar->isStaticDataMember()) {
9961 FoundInstantiation = Previous.getRepresentativeDecl();
9962 Instantiation = PrevVar;
9963 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9964 MSInfo = PrevVar->getMemberSpecializationInfo();
9965 }
9966 } else if (isa<RecordDecl>(Member)) {
9967 CXXRecordDecl *PrevRecord;
9968 if (Previous.isSingleResult() &&
9969 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9970 FoundInstantiation = Previous.getRepresentativeDecl();
9971 Instantiation = PrevRecord;
9972 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9973 MSInfo = PrevRecord->getMemberSpecializationInfo();
9974 }
9975 } else if (isa<EnumDecl>(Member)) {
9976 EnumDecl *PrevEnum;
9977 if (Previous.isSingleResult() &&
9978 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9979 FoundInstantiation = Previous.getRepresentativeDecl();
9980 Instantiation = PrevEnum;
9981 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9982 MSInfo = PrevEnum->getMemberSpecializationInfo();
9983 }
9984 }
9985
9986 if (!Instantiation) {
9987 // There is no previous declaration that matches. Since member
9988 // specializations are always out-of-line, the caller will complain about
9989 // this mismatch later.
9990 return false;
9991 }
9992
9993 // A member specialization in a friend declaration isn't really declaring
9994 // an explicit specialization, just identifying a specific (possibly implicit)
9995 // specialization. Don't change the template specialization kind.
9996 //
9997 // FIXME: Is this really valid? Other compilers reject.
9998 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9999 // Preserve instantiation information.
10000 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10001 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10002 cast<CXXMethodDecl>(InstantiatedFrom),
10004 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10005 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10006 cast<CXXRecordDecl>(InstantiatedFrom),
10008 }
10009
10010 Previous.clear();
10011 Previous.addDecl(FoundInstantiation);
10012 return false;
10013 }
10014
10015 // Make sure that this is a specialization of a member.
10016 if (!InstantiatedFrom) {
10017 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10018 << Member;
10019 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10020 return true;
10021 }
10022
10023 // C++ [temp.expl.spec]p6:
10024 // If a template, a member template or the member of a class template is
10025 // explicitly specialized then that specialization shall be declared
10026 // before the first use of that specialization that would cause an implicit
10027 // instantiation to take place, in every translation unit in which such a
10028 // use occurs; no diagnostic is required.
10029 assert(MSInfo && "Member specialization info missing?");
10030
10031 bool HasNoEffect = false;
10034 Instantiation,
10036 MSInfo->getPointOfInstantiation(),
10037 HasNoEffect))
10038 return true;
10039
10040 // Check the scope of this explicit specialization.
10042 InstantiatedFrom,
10043 Instantiation, Member->getLocation(),
10044 false))
10045 return true;
10046
10047 // Note that this member specialization is an "instantiation of" the
10048 // corresponding member of the original template.
10049 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10050 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10051 if (InstantiationFunction->getTemplateSpecializationKind() ==
10053 // Explicit specializations of member functions of class templates do not
10054 // inherit '=delete' from the member function they are specializing.
10055 if (InstantiationFunction->isDeleted()) {
10056 // FIXME: This assert will not hold in the presence of modules.
10057 assert(InstantiationFunction->getCanonicalDecl() ==
10058 InstantiationFunction);
10059 // FIXME: We need an update record for this AST mutation.
10060 InstantiationFunction->setDeletedAsWritten(false);
10061 }
10062 }
10063
10064 MemberFunction->setInstantiationOfMemberFunction(
10066 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10067 MemberVar->setInstantiationOfStaticDataMember(
10068 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10069 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10070 MemberClass->setInstantiationOfMemberClass(
10072 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10073 MemberEnum->setInstantiationOfMemberEnum(
10074 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10075 } else {
10076 llvm_unreachable("unknown member specialization kind");
10077 }
10078
10079 // Save the caller the trouble of having to figure out which declaration
10080 // this specialization matches.
10081 Previous.clear();
10082 Previous.addDecl(FoundInstantiation);
10083 return false;
10084}
10085
10086/// Complete the explicit specialization of a member of a class template by
10087/// updating the instantiated member to be marked as an explicit specialization.
10088///
10089/// \param OrigD The member declaration instantiated from the template.
10090/// \param Loc The location of the explicit specialization of the member.
10091template<typename DeclT>
10092static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10093 SourceLocation Loc) {
10094 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10095 return;
10096
10097 // FIXME: Inform AST mutation listeners of this AST mutation.
10098 // FIXME: If there are multiple in-class declarations of the member (from
10099 // multiple modules, or a declaration and later definition of a member type),
10100 // should we update all of them?
10101 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10102 OrigD->setLocation(Loc);
10103}
10104
10107 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10108 if (Instantiation == Member)
10109 return;
10110
10111 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10112 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10113 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10114 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10115 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10116 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10117 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10118 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10119 else
10120 llvm_unreachable("unknown member specialization kind");
10121}
10122
10123/// Check the scope of an explicit instantiation.
10124///
10125/// \returns true if a serious error occurs, false otherwise.
10127 SourceLocation InstLoc,
10128 bool WasQualifiedName) {
10130 DeclContext *CurContext = S.CurContext->getRedeclContext();
10131
10132 if (CurContext->isRecord()) {
10133 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10134 << D;
10135 return true;
10136 }
10137
10138 // C++11 [temp.explicit]p3:
10139 // An explicit instantiation shall appear in an enclosing namespace of its
10140 // template. If the name declared in the explicit instantiation is an
10141 // unqualified name, the explicit instantiation shall appear in the
10142 // namespace where its template is declared or, if that namespace is inline
10143 // (7.3.1), any namespace from its enclosing namespace set.
10144 //
10145 // This is DR275, which we do not retroactively apply to C++98/03.
10146 if (WasQualifiedName) {
10147 if (CurContext->Encloses(OrigContext))
10148 return false;
10149 } else {
10150 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10151 return false;
10152 }
10153
10154 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10155 if (WasQualifiedName)
10156 S.Diag(InstLoc,
10157 S.getLangOpts().CPlusPlus11?
10158 diag::err_explicit_instantiation_out_of_scope :
10159 diag::warn_explicit_instantiation_out_of_scope_0x)
10160 << D << NS;
10161 else
10162 S.Diag(InstLoc,
10163 S.getLangOpts().CPlusPlus11?
10164 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10165 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10166 << D << NS;
10167 } else
10168 S.Diag(InstLoc,
10169 S.getLangOpts().CPlusPlus11?
10170 diag::err_explicit_instantiation_must_be_global :
10171 diag::warn_explicit_instantiation_must_be_global_0x)
10172 << D;
10173 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10174 return false;
10175}
10176
10177/// Common checks for whether an explicit instantiation of \p D is valid.
10179 SourceLocation InstLoc,
10180 bool WasQualifiedName,
10182 // C++ [temp.explicit]p13:
10183 // An explicit instantiation declaration shall not name a specialization of
10184 // a template with internal linkage.
10187 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10188 return true;
10189 }
10190
10191 // C++11 [temp.explicit]p3: [DR 275]
10192 // An explicit instantiation shall appear in an enclosing namespace of its
10193 // template.
10194 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10195 return true;
10196
10197 return false;
10198}
10199
10200/// Determine whether the given scope specifier has a template-id in it.
10202 // C++11 [temp.explicit]p3:
10203 // If the explicit instantiation is for a member function, a member class
10204 // or a static data member of a class template specialization, the name of
10205 // the class template specialization in the qualified-id for the member
10206 // name shall be a simple-template-id.
10207 //
10208 // C++98 has the same restriction, just worded differently.
10209 for (NestedNameSpecifier NNS = SS.getScopeRep();
10211 /**/) {
10212 const Type *T = NNS.getAsType();
10214 return true;
10215 NNS = T->getPrefix();
10216 }
10217 return false;
10218}
10219
10220/// Make a dllexport or dllimport attr on a class template specialization take
10221/// effect.
10224 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10225 assert(A && "dllExportImportClassTemplateSpecialization called "
10226 "on Def without dllexport or dllimport");
10227
10228 // We reject explicit instantiations in class scope, so there should
10229 // never be any delayed exported classes to worry about.
10230 assert(S.DelayedDllExportClasses.empty() &&
10231 "delayed exports present at explicit instantiation");
10233
10234 // Propagate attribute to base class templates.
10235 for (auto &B : Def->bases()) {
10236 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10237 B.getType()->getAsCXXRecordDecl()))
10239 }
10240
10242}
10243
10245 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10246 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10247 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10248 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10249 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10250 // Find the class template we're specializing
10251 TemplateName Name = TemplateD.get();
10252 TemplateDecl *TD = Name.getAsTemplateDecl();
10253 // Check that the specialization uses the same tag kind as the
10254 // original template.
10256 assert(Kind != TagTypeKind::Enum &&
10257 "Invalid enum tag in class template explicit instantiation!");
10258
10259 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10260
10261 if (!ClassTemplate) {
10262 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10263 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10264 Diag(TD->getLocation(), diag::note_previous_use);
10265 return true;
10266 }
10267
10268 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10269 Kind, /*isDefinition*/false, KWLoc,
10270 ClassTemplate->getIdentifier())) {
10271 Diag(KWLoc, diag::err_use_with_wrong_tag)
10272 << ClassTemplate
10274 ClassTemplate->getTemplatedDecl()->getKindName());
10275 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10276 diag::note_previous_use);
10277 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10278 }
10279
10280 // C++0x [temp.explicit]p2:
10281 // There are two forms of explicit instantiation: an explicit instantiation
10282 // definition and an explicit instantiation declaration. An explicit
10283 // instantiation declaration begins with the extern keyword. [...]
10284 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10287
10289 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10290 // Check for dllexport class template instantiation declarations,
10291 // except for MinGW mode.
10292 for (const ParsedAttr &AL : Attr) {
10293 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10294 Diag(ExternLoc,
10295 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10296 Diag(AL.getLoc(), diag::note_attribute);
10297 break;
10298 }
10299 }
10300
10301 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10302 Diag(ExternLoc,
10303 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10304 Diag(A->getLocation(), diag::note_attribute);
10305 }
10306 }
10307
10308 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10309 // instantiation declarations for most purposes.
10310 bool DLLImportExplicitInstantiationDef = false;
10312 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10313 // Check for dllimport class template instantiation definitions.
10314 bool DLLImport =
10315 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10316 for (const ParsedAttr &AL : Attr) {
10317 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10318 DLLImport = true;
10319 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10320 // dllexport trumps dllimport here.
10321 DLLImport = false;
10322 break;
10323 }
10324 }
10325 if (DLLImport) {
10327 DLLImportExplicitInstantiationDef = true;
10328 }
10329 }
10330
10331 // Translate the parser's template argument list in our AST format.
10332 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10333 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10334
10335 // Check that the template argument list is well-formed for this
10336 // template.
10338 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10339 /*DefaultArgs=*/{}, false, CTAI,
10340 /*UpdateArgsWithConversions=*/true,
10341 /*ConstraintsNotSatisfied=*/nullptr))
10342 return true;
10343
10344 // Find the class template specialization declaration that
10345 // corresponds to these arguments.
10346 void *InsertPos = nullptr;
10348 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10349
10350 TemplateSpecializationKind PrevDecl_TSK
10351 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10352
10353 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10354 Context.getTargetInfo().getTriple().isOSCygMing()) {
10355 // Check for dllexport class template instantiation definitions in MinGW
10356 // mode, if a previous declaration of the instantiation was seen.
10357 for (const ParsedAttr &AL : Attr) {
10358 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10359 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10360 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10361 } else {
10362 Diag(AL.getLoc(),
10363 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10364 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10365 }
10366 break;
10367 }
10368 }
10369 }
10370
10371 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10372 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10373 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10374 return AL.getKind() == ParsedAttr::AT_DLLExport;
10375 })) {
10376 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10377 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10378 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10379 }
10380 }
10381
10382 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10383 SS.isSet(), TSK))
10384 return true;
10385
10387
10388 bool HasNoEffect = false;
10389 if (PrevDecl) {
10390 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10391 PrevDecl, PrevDecl_TSK,
10392 PrevDecl->getPointOfInstantiation(),
10393 HasNoEffect))
10394 return PrevDecl;
10395
10396 // Even though HasNoEffect == true means that this explicit instantiation
10397 // has no effect on semantics, we go on to put its syntax in the AST.
10398
10399 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10400 PrevDecl_TSK == TSK_Undeclared) {
10401 // Since the only prior class template specialization with these
10402 // arguments was referenced but not declared, reuse that
10403 // declaration node as our own, updating the source location
10404 // for the template name to reflect our new declaration.
10405 // (Other source locations will be updated later.)
10406 Specialization = PrevDecl;
10407 Specialization->setLocation(TemplateNameLoc);
10408 PrevDecl = nullptr;
10409 }
10410
10411 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10412 DLLImportExplicitInstantiationDef) {
10413 // The new specialization might add a dllimport attribute.
10414 HasNoEffect = false;
10415 }
10416 }
10417
10418 if (!Specialization) {
10419 // Create a new class template specialization declaration node for
10420 // this explicit specialization.
10422 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10423 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10425
10426 // A MSInheritanceAttr attached to the previous declaration must be
10427 // propagated to the new node prior to instantiation.
10428 if (PrevDecl) {
10429 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10430 auto *Clone = A->clone(getASTContext());
10431 Clone->setInherited(true);
10432 Specialization->addAttr(Clone);
10433 Consumer.AssignInheritanceModel(Specialization);
10434 }
10435 }
10436
10437 if (!HasNoEffect && !PrevDecl) {
10438 // Insert the new specialization.
10439 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10440 }
10441 }
10442
10443 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10444
10445 // Set source locations for keywords.
10446 Specialization->setExternKeywordLoc(ExternLoc);
10447 Specialization->setTemplateKeywordLoc(TemplateLoc);
10448 Specialization->setBraceRange(SourceRange());
10449
10450 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10453
10454 // Add the explicit instantiation into its lexical context. However,
10455 // since explicit instantiations are never found by name lookup, we
10456 // just put it into the declaration context directly.
10457 Specialization->setLexicalDeclContext(CurContext);
10458 CurContext->addDecl(Specialization);
10459
10460 // Syntax is now OK, so return if it has no other effect on semantics.
10461 if (HasNoEffect) {
10462 // Set the template specialization kind.
10463 Specialization->setTemplateSpecializationKind(TSK);
10464
10466 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10467 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10468 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10469 Context.getCanonicalTagType(Specialization));
10471 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10472 TemplateNameLoc, TSI, TSK);
10473 return Specialization;
10474 }
10475
10476 // C++ [temp.explicit]p3:
10477 // A definition of a class template or class member template
10478 // shall be in scope at the point of the explicit instantiation of
10479 // the class template or class member template.
10480 //
10481 // This check comes when we actually try to perform the
10482 // instantiation.
10484 = cast_or_null<ClassTemplateSpecializationDecl>(
10485 Specialization->getDefinition());
10486 if (!Def)
10488 /*Complain=*/true,
10489 CTAI.StrictPackMatch);
10490 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10491 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10492 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10493 }
10494
10495 // Instantiate the members of this class template specialization.
10496 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10497 Specialization->getDefinition());
10498 if (Def) {
10500 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10501 // TSK_ExplicitInstantiationDefinition
10502 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10504 DLLImportExplicitInstantiationDef)) {
10505 // FIXME: Need to notify the ASTMutationListener that we did this.
10507
10508 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10509 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10510 // An explicit instantiation definition can add a dll attribute to a
10511 // template with a previous instantiation declaration. MinGW doesn't
10512 // allow this.
10513 auto *A = cast<InheritableAttr>(
10515 A->setInherited(true);
10516 Def->addAttr(A);
10518 }
10519 }
10520
10521 // Fix a TSK_ImplicitInstantiation followed by a
10522 // TSK_ExplicitInstantiationDefinition
10523 bool NewlyDLLExported =
10524 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10525 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10526 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10527 // An explicit instantiation definition can add a dll attribute to a
10528 // template with a previous implicit instantiation. MinGW doesn't allow
10529 // this. We limit clang to only adding dllexport, to avoid potentially
10530 // strange codegen behavior. For example, if we extend this conditional
10531 // to dllimport, and we have a source file calling a method on an
10532 // implicitly instantiated template class instance and then declaring a
10533 // dllimport explicit instantiation definition for the same template
10534 // class, the codegen for the method call will not respect the dllimport,
10535 // while it will with cl. The Def will already have the DLL attribute,
10536 // since the Def and Specialization will be the same in the case of
10537 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10538 // attribute to the Specialization; we just need to make it take effect.
10539 assert(Def == Specialization &&
10540 "Def and Specialization should match for implicit instantiation");
10542 }
10543
10544 // In MinGW mode, export the template instantiation if the declaration
10545 // was marked dllexport.
10546 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10547 Context.getTargetInfo().getTriple().isOSCygMing() &&
10548 PrevDecl->hasAttr<DLLExportAttr>()) {
10550 }
10551
10552 // Set the template specialization kind. Make sure it is set before
10553 // instantiating the members which will trigger ASTConsumer callbacks.
10554 Specialization->setTemplateSpecializationKind(TSK);
10555 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10556 } else {
10557
10558 // Set the template specialization kind.
10559 Specialization->setTemplateSpecializationKind(TSK);
10560 }
10561
10563 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10564 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10565 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10566 Context.getCanonicalTagType(Specialization));
10568 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10569 TemplateNameLoc, TSI, TSK);
10570 return Specialization;
10571}
10572
10575 SourceLocation TemplateLoc, unsigned TagSpec,
10576 SourceLocation KWLoc, CXXScopeSpec &SS,
10577 IdentifierInfo *Name, SourceLocation NameLoc,
10578 const ParsedAttributesView &Attr) {
10579
10580 bool Owned = false;
10581 bool IsDependent = false;
10582 Decl *TagD =
10583 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10584 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10585 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10586 false, TypeResult(), /*IsTypeSpecifier*/ false,
10587 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10588 .get();
10589 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10590
10591 if (!TagD)
10592 return true;
10593
10594 TagDecl *Tag = cast<TagDecl>(TagD);
10595 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10596
10597 if (Tag->isInvalidDecl())
10598 return true;
10599
10601 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10602 if (!Pattern) {
10603 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10604 << Context.getCanonicalTagType(Record);
10605 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10606 return true;
10607 }
10608
10609 // C++0x [temp.explicit]p2:
10610 // If the explicit instantiation is for a class or member class, the
10611 // elaborated-type-specifier in the declaration shall include a
10612 // simple-template-id.
10613 //
10614 // C++98 has the same restriction, just worded differently.
10616 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10617 << Record << SS.getRange();
10618
10619 // C++0x [temp.explicit]p2:
10620 // There are two forms of explicit instantiation: an explicit instantiation
10621 // definition and an explicit instantiation declaration. An explicit
10622 // instantiation declaration begins with the extern keyword. [...]
10626
10627 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10628
10629 // Verify that it is okay to explicitly instantiate here.
10630 CXXRecordDecl *PrevDecl
10631 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10632 if (!PrevDecl && Record->getDefinition())
10633 PrevDecl = Record;
10634 if (PrevDecl) {
10636 bool HasNoEffect = false;
10637 assert(MSInfo && "No member specialization information?");
10638 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10639 PrevDecl,
10641 MSInfo->getPointOfInstantiation(),
10642 HasNoEffect))
10643 return true;
10644 if (HasNoEffect) {
10648 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10649 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10650 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10651 TL.setElaboratedKeywordLoc(KWLoc);
10652 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10653 TL.setNameLoc(NameLoc);
10655 TemplateLoc, NestedNameSpecifierLoc(),
10656 nullptr, NameLoc, TSI, TSK);
10657 return TagD;
10658 }
10659 }
10660
10661 CXXRecordDecl *RecordDef
10662 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10663 if (!RecordDef) {
10664 // C++ [temp.explicit]p3:
10665 // A definition of a member class of a class template shall be in scope
10666 // at the point of an explicit instantiation of the member class.
10667 CXXRecordDecl *Def
10668 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10669 if (!Def) {
10670 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10671 << 0 << Record->getDeclName() << Record->getDeclContext();
10672 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10673 << Pattern;
10674 return true;
10675 } else {
10676 if (InstantiateClass(NameLoc, Record, Def,
10678 TSK))
10679 return true;
10680
10681 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10682 if (!RecordDef)
10683 return true;
10684 }
10685 }
10686
10687 // Instantiate all of the members of the class.
10688 InstantiateClassMembers(NameLoc, RecordDef,
10690
10692 MarkVTableUsed(NameLoc, RecordDef, true);
10693
10696 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10697 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10698 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10699 TL.setElaboratedKeywordLoc(KWLoc);
10700 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10701 TL.setNameLoc(NameLoc);
10703 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10704 NameLoc, TSI, TSK);
10705 return TagD;
10706}
10707
10709 SourceLocation ExternLoc,
10710 SourceLocation TemplateLoc,
10711 Declarator &D) {
10712 // Explicit instantiations always require a name.
10713 // TODO: check if/when DNInfo should replace Name.
10715 DeclarationName Name = NameInfo.getName();
10716 if (!Name) {
10717 if (!D.isInvalidType())
10719 diag::err_explicit_instantiation_requires_name)
10721
10722 return true;
10723 }
10724
10725 // Get the innermost enclosing declaration scope.
10726 S = S->getDeclParent();
10727
10728 // Determine the type of the declaration.
10730 QualType R = T->getType();
10731 if (R.isNull())
10732 return true;
10733
10734 // C++ [dcl.stc]p1:
10735 // A storage-class-specifier shall not be specified in [...] an explicit
10736 // instantiation (14.7.2) directive.
10738 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10739 << Name;
10740 return true;
10741 } else if (D.getDeclSpec().getStorageClassSpec()
10743 // Complain about then remove the storage class specifier.
10744 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10746
10748 }
10749
10750 // C++0x [temp.explicit]p1:
10751 // [...] An explicit instantiation of a function template shall not use the
10752 // inline or constexpr specifiers.
10753 // Presumably, this also applies to member functions of class templates as
10754 // well.
10758 diag::err_explicit_instantiation_inline :
10759 diag::warn_explicit_instantiation_inline_0x)
10761 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10762 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10763 // not already specified.
10765 diag::err_explicit_instantiation_constexpr);
10766
10767 // A deduction guide is not on the list of entities that can be explicitly
10768 // instantiated.
10770 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10771 << /*explicit instantiation*/ 0;
10772 return true;
10773 }
10774
10775 // C++0x [temp.explicit]p2:
10776 // There are two forms of explicit instantiation: an explicit instantiation
10777 // definition and an explicit instantiation declaration. An explicit
10778 // instantiation declaration begins with the extern keyword. [...]
10782
10783 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10785 /*ObjectType=*/QualType());
10786
10787 if (!R->isFunctionType()) {
10788 // C++ [temp.explicit]p1:
10789 // A [...] static data member of a class template can be explicitly
10790 // instantiated from the member definition associated with its class
10791 // template.
10792 // C++1y [temp.explicit]p1:
10793 // A [...] variable [...] template specialization can be explicitly
10794 // instantiated from its template.
10795 if (Previous.isAmbiguous())
10796 return true;
10797
10798 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10799 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10800 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10801
10802 if (!PrevTemplate) {
10803 if (!Prev || !Prev->isStaticDataMember()) {
10804 // We expect to see a static data member here.
10805 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10806 << Name;
10807 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10808 P != PEnd; ++P)
10809 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10810 return true;
10811 }
10812
10814 // FIXME: Check for explicit specialization?
10816 diag::err_explicit_instantiation_data_member_not_instantiated)
10817 << Prev;
10818 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10819 // FIXME: Can we provide a note showing where this was declared?
10820 return true;
10821 }
10822 } else {
10823 // Explicitly instantiate a variable template.
10824
10825 // C++1y [dcl.spec.auto]p6:
10826 // ... A program that uses auto or decltype(auto) in a context not
10827 // explicitly allowed in this section is ill-formed.
10828 //
10829 // This includes auto-typed variable template instantiations.
10830 if (R->isUndeducedType()) {
10831 Diag(T->getTypeLoc().getBeginLoc(),
10832 diag::err_auto_not_allowed_var_inst);
10833 return true;
10834 }
10835
10837 // C++1y [temp.explicit]p3:
10838 // If the explicit instantiation is for a variable, the unqualified-id
10839 // in the declaration shall be a template-id.
10841 diag::err_explicit_instantiation_without_template_id)
10842 << PrevTemplate;
10843 Diag(PrevTemplate->getLocation(),
10844 diag::note_explicit_instantiation_here);
10845 return true;
10846 }
10847
10848 // Translate the parser's template argument list into our AST format.
10849 TemplateArgumentListInfo TemplateArgs =
10851
10852 DeclResult Res =
10853 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10854 TemplateArgs, /*SetWrittenArgs=*/true);
10855 if (Res.isInvalid())
10856 return true;
10857
10858 if (!Res.isUsable()) {
10859 // We somehow specified dependent template arguments in an explicit
10860 // instantiation. This should probably only happen during error
10861 // recovery.
10862 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10863 return true;
10864 }
10865
10866 // Ignore access control bits, we don't need them for redeclaration
10867 // checking.
10868 Prev = cast<VarDecl>(Res.get());
10869 ArgsAsWritten =
10871 }
10872
10873 // C++0x [temp.explicit]p2:
10874 // If the explicit instantiation is for a member function, a member class
10875 // or a static data member of a class template specialization, the name of
10876 // the class template specialization in the qualified-id for the member
10877 // name shall be a simple-template-id.
10878 //
10879 // C++98 has the same restriction, just worded differently.
10880 //
10881 // This does not apply to variable template specializations, where the
10882 // template-id is in the unqualified-id instead.
10883 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10885 diag::ext_explicit_instantiation_without_qualified_id)
10886 << Prev << D.getCXXScopeSpec().getRange();
10887
10888 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10889
10890 // Verify that it is okay to explicitly instantiate here.
10893 bool HasNoEffect = false;
10895 PrevTSK, POI, HasNoEffect))
10896 return true;
10897
10898 if (!HasNoEffect) {
10899 // Instantiate static data member or variable template.
10901 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10902 VTSD->setExternKeywordLoc(ExternLoc);
10903 VTSD->setTemplateKeywordLoc(TemplateLoc);
10904 }
10905
10906 // Merge attributes.
10908 if (PrevTemplate)
10909 ProcessAPINotes(Prev);
10910
10913 }
10914
10915 // Check the new variable specialization against the parsed input.
10916 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10917 Diag(T->getTypeLoc().getBeginLoc(),
10918 diag::err_invalid_var_template_spec_type)
10919 << 0 << PrevTemplate << R << Prev->getType();
10920 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10921 << 2 << PrevTemplate->getDeclName();
10922 return true;
10923 }
10924
10926 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10927 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10928 D.getIdentifierLoc(), T, TSK);
10929 return (Decl *)nullptr;
10930 }
10931
10932 // If the declarator is a template-id, translate the parser's template
10933 // argument list into our AST format.
10934 bool HasExplicitTemplateArgs = false;
10935 TemplateArgumentListInfo TemplateArgs;
10937 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10938 HasExplicitTemplateArgs = true;
10939 }
10940
10941 // C++ [temp.explicit]p1:
10942 // A [...] function [...] can be explicitly instantiated from its template.
10943 // A member function [...] of a class template can be explicitly
10944 // instantiated from the member definition associated with its class
10945 // template.
10946 UnresolvedSet<8> TemplateMatches;
10947 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10949 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10950 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10951 P != PEnd; ++P) {
10952 NamedDecl *Prev = *P;
10953 if (!HasExplicitTemplateArgs) {
10954 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10955 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10956 /*AdjustExceptionSpec*/true);
10957 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10958 if (Method->getPrimaryTemplate()) {
10959 TemplateMatches.addDecl(Method, P.getAccess());
10960 } else {
10961 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10962 C.FoundDecl = P.getPair();
10963 C.Function = Method;
10964 C.Viable = true;
10966 if (Method->getTrailingRequiresClause() &&
10968 /*ForOverloadResolution=*/true) ||
10969 !S.IsSatisfied)) {
10970 C.Viable = false;
10972 }
10973 }
10974 }
10975 }
10976 }
10977
10978 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10979 if (!FunTmpl)
10980 continue;
10981
10982 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10983 FunctionDecl *Specialization = nullptr;
10985 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10986 Specialization, Info);
10988 // Keep track of almost-matches.
10989 FailedTemplateCandidates.addCandidate().set(
10990 P.getPair(), FunTmpl->getTemplatedDecl(),
10991 MakeDeductionFailureInfo(Context, TDK, Info));
10992 (void)TDK;
10993 continue;
10994 }
10995
10996 // Target attributes are part of the cuda function signature, so
10997 // the cuda target of the instantiated function must match that of its
10998 // template. Given that C++ template deduction does not take
10999 // target attributes into account, we reject candidates here that
11000 // have a different target.
11001 if (LangOpts.CUDA &&
11002 CUDA().IdentifyTarget(Specialization,
11003 /* IgnoreImplicitHDAttr = */ true) !=
11004 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11005 FailedTemplateCandidates.addCandidate().set(
11006 P.getPair(), FunTmpl->getTemplatedDecl(),
11009 continue;
11010 }
11011
11012 TemplateMatches.addDecl(Specialization, P.getAccess());
11013 }
11014
11015 FunctionDecl *Specialization = nullptr;
11016 if (!NonTemplateMatches.empty()) {
11017 unsigned Msg = 0;
11018 OverloadCandidateDisplayKind DisplayKind;
11020 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11021 Best)) {
11022 case OR_Success:
11023 case OR_Deleted:
11024 Specialization = cast<FunctionDecl>(Best->Function);
11025 break;
11026 case OR_Ambiguous:
11027 Msg = diag::err_explicit_instantiation_ambiguous;
11028 DisplayKind = OCD_AmbiguousCandidates;
11029 break;
11031 Msg = diag::err_explicit_instantiation_no_candidate;
11032 DisplayKind = OCD_AllCandidates;
11033 break;
11034 }
11035 if (Msg) {
11036 PartialDiagnostic Diag = PDiag(Msg) << Name;
11037 NonTemplateMatches.NoteCandidates(
11038 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11039 {});
11040 return true;
11041 }
11042 }
11043
11044 if (!Specialization) {
11045 // Find the most specialized function template specialization.
11047 TemplateMatches.begin(), TemplateMatches.end(),
11048 FailedTemplateCandidates, D.getIdentifierLoc(),
11049 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11050 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11051 PDiag(diag::note_explicit_instantiation_candidate));
11052
11053 if (Result == TemplateMatches.end())
11054 return true;
11055
11056 // Ignore access control bits, we don't need them for redeclaration checking.
11058 }
11059
11060 // C++11 [except.spec]p4
11061 // In an explicit instantiation an exception-specification may be specified,
11062 // but is not required.
11063 // If an exception-specification is specified in an explicit instantiation
11064 // directive, it shall be compatible with the exception-specifications of
11065 // other declarations of that function.
11066 if (auto *FPT = R->getAs<FunctionProtoType>())
11067 if (FPT->hasExceptionSpec()) {
11068 unsigned DiagID =
11069 diag::err_mismatched_exception_spec_explicit_instantiation;
11070 if (getLangOpts().MicrosoftExt)
11071 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11073 PDiag(DiagID) << Specialization->getType(),
11074 PDiag(diag::note_explicit_instantiation_here),
11075 Specialization->getType()->getAs<FunctionProtoType>(),
11076 Specialization->getLocation(), FPT, D.getBeginLoc());
11077 // In Microsoft mode, mismatching exception specifications just cause a
11078 // warning.
11079 if (!getLangOpts().MicrosoftExt && Result)
11080 return true;
11081 }
11082
11083 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11085 diag::err_explicit_instantiation_member_function_not_instantiated)
11087 << (Specialization->getTemplateSpecializationKind() ==
11089 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11090 return true;
11091 }
11092
11093 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11094 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11095 PrevDecl = Specialization;
11096
11097 if (PrevDecl) {
11098 bool HasNoEffect = false;
11100 PrevDecl,
11102 PrevDecl->getPointOfInstantiation(),
11103 HasNoEffect))
11104 return true;
11105
11106 if (HasNoEffect) {
11107 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11108 if (HasExplicitTemplateArgs)
11109 ArgsAsWritten =
11112 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11113 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11114 D.getIdentifierLoc(), T, TSK);
11115 return (Decl *)nullptr;
11116 }
11117 }
11118
11119 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11120 // functions
11121 // valarray<size_t>::valarray(size_t) and
11122 // valarray<size_t>::~valarray()
11123 // that it declared to have internal linkage with the internal_linkage
11124 // attribute. Ignore the explicit instantiation declaration in this case.
11125 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11127 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11128 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11129 RD->isInStdNamespace())
11130 return (Decl*) nullptr;
11131 }
11132
11135
11136 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11137 // instantiation declarations.
11139 Specialization->hasAttr<DLLImportAttr>() &&
11140 Context.getTargetInfo().getCXXABI().isMicrosoft())
11142
11143 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11144 if (Specialization->isDefined()) {
11145 // Let the ASTConsumer know that this function has been explicitly
11146 // instantiated now, and its linkage might have changed.
11147 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11148 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11149 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11150 // be explicitly instantiated.
11151 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11152 RD && RD->isLambda()) {
11153 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11154 << /*instantiation*/ 1;
11155 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11156 return (Decl *)nullptr;
11157 }
11159 }
11160
11161 // C++0x [temp.explicit]p2:
11162 // If the explicit instantiation is for a member function, a member class
11163 // or a static data member of a class template specialization, the name of
11164 // the class template specialization in the qualified-id for the member
11165 // name shall be a simple-template-id.
11166 //
11167 // C++98 has the same restriction, just worded differently.
11168 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11169 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11170 D.getCXXScopeSpec().isSet() &&
11173 diag::ext_explicit_instantiation_without_qualified_id)
11175
11177 *this,
11178 FunTmpl ? (NamedDecl *)FunTmpl
11179 : Specialization->getInstantiatedFromMemberFunction(),
11180 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11181
11182 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11183 if (HasExplicitTemplateArgs)
11184 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11186 TemplateLoc,
11188 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11189 return (Decl *)nullptr;
11190}
11191
11193 const CXXScopeSpec &SS,
11194 const IdentifierInfo *Name,
11195 SourceLocation TagLoc,
11196 SourceLocation NameLoc) {
11197 // This has to hold, because SS is expected to be defined.
11198 assert(Name && "Expected a name in a dependent tag");
11199
11201 if (!NNS)
11202 return true;
11203
11205
11206 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11207 Diag(NameLoc, diag::err_dependent_tag_decl)
11208 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11209 return true;
11210 }
11211
11212 // Create the resulting type.
11214 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11215
11216 // Create type-source location information for this type.
11217 TypeLocBuilder TLB;
11219 TL.setElaboratedKeywordLoc(TagLoc);
11221 TL.setNameLoc(NameLoc);
11223}
11224
11226 const CXXScopeSpec &SS,
11227 const IdentifierInfo &II,
11228 SourceLocation IdLoc,
11229 ImplicitTypenameContext IsImplicitTypename) {
11230 if (SS.isInvalid())
11231 return true;
11232
11233 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11234 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11235 << FixItHint::CreateRemoval(TypenameLoc);
11236
11238 TypeSourceInfo *TSI = nullptr;
11239 QualType T =
11242 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11243 /*DeducedTSTContext=*/true);
11244 if (T.isNull())
11245 return true;
11246 return CreateParsedType(T, TSI);
11247}
11248
11251 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11252 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11253 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11254 ASTTemplateArgsPtr TemplateArgsIn,
11255 SourceLocation RAngleLoc) {
11256 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11257 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11258 ? diag::compat_cxx11_typename_outside_of_template
11259 : diag::compat_pre_cxx11_typename_outside_of_template)
11260 << FixItHint::CreateRemoval(TypenameLoc);
11261
11262 // Strangely, non-type results are not ignored by this lookup, so the
11263 // program is ill-formed if it finds an injected-class-name.
11264 if (TypenameLoc.isValid()) {
11265 auto *LookupRD =
11266 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11267 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11268 Diag(TemplateIILoc,
11269 diag::ext_out_of_line_qualified_id_type_names_constructor)
11270 << TemplateII << 0 /*injected-class-name used as template name*/
11271 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11272 }
11273 }
11274
11275 // Translate the parser's template argument list in our AST format.
11276 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11277 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11278
11282 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11283 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11284 if (T.isNull())
11285 return true;
11286
11287 // Provide source-location information for the template specialization type.
11288 TypeLocBuilder Builder;
11290 = Builder.push<TemplateSpecializationTypeLoc>(T);
11291 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11292 TemplateIILoc, TemplateArgs);
11293 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11294 return CreateParsedType(T, TSI);
11295}
11296
11297/// Determine whether this failed name lookup should be treated as being
11298/// disabled by a usage of std::enable_if.
11300 SourceRange &CondRange, Expr *&Cond) {
11301 // We must be looking for a ::type...
11302 if (!II.isStr("type"))
11303 return false;
11304
11305 // ... within an explicitly-written template specialization...
11307 return false;
11308
11309 // FIXME: Look through sugar.
11310 auto EnableIfTSTLoc =
11312 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11313 return false;
11314 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11315
11316 // ... which names a complete class template declaration...
11317 const TemplateDecl *EnableIfDecl =
11318 EnableIfTST->getTemplateName().getAsTemplateDecl();
11319 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11320 return false;
11321
11322 // ... called "enable_if".
11323 const IdentifierInfo *EnableIfII =
11324 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11325 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11326 return false;
11327
11328 // Assume the first template argument is the condition.
11329 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11330
11331 // Dig out the condition.
11332 Cond = nullptr;
11333 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11335 return true;
11336
11337 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11338
11339 // Ignore Boolean literals; they add no value.
11340 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11341 Cond = nullptr;
11342
11343 return true;
11344}
11345
11348 SourceLocation KeywordLoc,
11349 NestedNameSpecifierLoc QualifierLoc,
11350 const IdentifierInfo &II,
11351 SourceLocation IILoc,
11352 TypeSourceInfo **TSI,
11353 bool DeducedTSTContext) {
11354 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11355 DeducedTSTContext);
11356 if (T.isNull())
11357 return QualType();
11358
11359 TypeLocBuilder TLB;
11360 if (isa<DependentNameType>(T)) {
11361 auto TL = TLB.push<DependentNameTypeLoc>(T);
11362 TL.setElaboratedKeywordLoc(KeywordLoc);
11363 TL.setQualifierLoc(QualifierLoc);
11364 TL.setNameLoc(IILoc);
11367 TL.setElaboratedKeywordLoc(KeywordLoc);
11368 TL.setQualifierLoc(QualifierLoc);
11369 TL.setNameLoc(IILoc);
11370 } else if (isa<TemplateTypeParmType>(T)) {
11371 // FIXME: There might be a 'typename' keyword here, but we just drop it
11372 // as it can't be represented.
11373 assert(!QualifierLoc);
11374 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11375 } else if (isa<TagType>(T)) {
11376 auto TL = TLB.push<TagTypeLoc>(T);
11377 TL.setElaboratedKeywordLoc(KeywordLoc);
11378 TL.setQualifierLoc(QualifierLoc);
11379 TL.setNameLoc(IILoc);
11380 } else if (isa<TypedefType>(T)) {
11381 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11382 } else {
11383 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11384 }
11385 *TSI = TLB.getTypeSourceInfo(Context, T);
11386 return T;
11387}
11388
11389/// Build the type that describes a C++ typename specifier,
11390/// e.g., "typename T::type".
11393 SourceLocation KeywordLoc,
11394 NestedNameSpecifierLoc QualifierLoc,
11395 const IdentifierInfo &II,
11396 SourceLocation IILoc, bool DeducedTSTContext) {
11397 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11398
11399 CXXScopeSpec SS;
11400 SS.Adopt(QualifierLoc);
11401
11402 DeclContext *Ctx = nullptr;
11403 if (QualifierLoc) {
11404 Ctx = computeDeclContext(SS);
11405 if (!Ctx) {
11406 // If the nested-name-specifier is dependent and couldn't be
11407 // resolved to a type, build a typename type.
11408 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11409 return Context.getDependentNameType(Keyword,
11410 QualifierLoc.getNestedNameSpecifier(),
11411 &II);
11412 }
11413
11414 // If the nested-name-specifier refers to the current instantiation,
11415 // the "typename" keyword itself is superfluous. In C++03, the
11416 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11417 // allows such extraneous "typename" keywords, and we retroactively
11418 // apply this DR to C++03 code with only a warning. In any case we continue.
11419
11420 if (RequireCompleteDeclContext(SS, Ctx))
11421 return QualType();
11422 }
11423
11424 DeclarationName Name(&II);
11425 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11426 if (Ctx)
11427 LookupQualifiedName(Result, Ctx, SS);
11428 else
11429 LookupName(Result, CurScope);
11430 unsigned DiagID = 0;
11431 Decl *Referenced = nullptr;
11432 switch (Result.getResultKind()) {
11434 // If we're looking up 'type' within a template named 'enable_if', produce
11435 // a more specific diagnostic.
11436 SourceRange CondRange;
11437 Expr *Cond = nullptr;
11438 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11439 // If we have a condition, narrow it down to the specific failed
11440 // condition.
11441 if (Cond) {
11442 Expr *FailedCond;
11443 std::string FailedDescription;
11444 std::tie(FailedCond, FailedDescription) =
11446
11447 Diag(FailedCond->getExprLoc(),
11448 diag::err_typename_nested_not_found_requirement)
11449 << FailedDescription
11450 << FailedCond->getSourceRange();
11451 return QualType();
11452 }
11453
11454 Diag(CondRange.getBegin(),
11455 diag::err_typename_nested_not_found_enable_if)
11456 << Ctx << CondRange;
11457 return QualType();
11458 }
11459
11460 DiagID = Ctx ? diag::err_typename_nested_not_found
11461 : diag::err_unknown_typename;
11462 break;
11463 }
11464
11466 // We found a using declaration that is a value. Most likely, the using
11467 // declaration itself is meant to have the 'typename' keyword.
11468 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11469 IILoc);
11470 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11471 << Name << Ctx << FullRange;
11472 if (UnresolvedUsingValueDecl *Using
11473 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11474 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11475 Diag(Loc, diag::note_using_value_decl_missing_typename)
11476 << FixItHint::CreateInsertion(Loc, "typename ");
11477 }
11478 }
11479 // Fall through to create a dependent typename type, from which we can
11480 // recover better.
11481 [[fallthrough]];
11482
11484 // Okay, it's a member of an unknown instantiation.
11485 return Context.getDependentNameType(Keyword,
11486 QualifierLoc.getNestedNameSpecifier(),
11487 &II);
11488
11490 // FXIME: Missing support for UsingShadowDecl on this path?
11491 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11492 // C++ [class.qual]p2:
11493 // In a lookup in which function names are not ignored and the
11494 // nested-name-specifier nominates a class C, if the name specified
11495 // after the nested-name-specifier, when looked up in C, is the
11496 // injected-class-name of C [...] then the name is instead considered
11497 // to name the constructor of class C.
11498 //
11499 // Unlike in an elaborated-type-specifier, function names are not ignored
11500 // in typename-specifier lookup. However, they are ignored in all the
11501 // contexts where we form a typename type with no keyword (that is, in
11502 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11503 //
11504 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11505 // ignore functions, but that appears to be an oversight.
11510 Type, IILoc);
11511 // FIXME: This appears to be the only case where a template type parameter
11512 // can have an elaborated keyword. We should preserve it somehow.
11515 assert(!QualifierLoc);
11517 }
11518 return Context.getTypeDeclType(
11519 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11520 }
11521
11522 // C++ [dcl.type.simple]p2:
11523 // A type-specifier of the form
11524 // typename[opt] nested-name-specifier[opt] template-name
11525 // is a placeholder for a deduced class type [...].
11526 if (getLangOpts().CPlusPlus17) {
11527 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11528 if (!DeducedTSTContext) {
11529 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11530 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11531 Diag(IILoc, diag::err_dependent_deduced_tst)
11533 << QualType(Qualifier.getAsType(), 0);
11534 else
11535 Diag(IILoc, diag::err_deduced_tst)
11538 return QualType();
11539 }
11540 TemplateName Name = Context.getQualifiedTemplateName(
11541 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11542 TemplateName(TD));
11543 return Context.getDeducedTemplateSpecializationType(
11544 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11545 Name);
11546 }
11547 }
11548
11549 DiagID = Ctx ? diag::err_typename_nested_not_type
11550 : diag::err_typename_not_type;
11551 Referenced = Result.getFoundDecl();
11552 break;
11553
11555 DiagID = Ctx ? diag::err_typename_nested_not_type
11556 : diag::err_typename_not_type;
11557 Referenced = *Result.begin();
11558 break;
11559
11561 return QualType();
11562 }
11563
11564 // If we get here, it's because name lookup did not find a
11565 // type. Emit an appropriate diagnostic and return an error.
11566 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11567 IILoc);
11568 if (Ctx)
11569 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11570 else
11571 Diag(IILoc, DiagID) << FullRange << Name;
11572 if (Referenced)
11573 Diag(Referenced->getLocation(),
11574 Ctx ? diag::note_typename_member_refers_here
11575 : diag::note_typename_refers_here)
11576 << Name;
11577 return QualType();
11578}
11579
11580namespace {
11581 // See Sema::RebuildTypeInCurrentInstantiation
11582 class CurrentInstantiationRebuilder
11583 : public TreeTransform<CurrentInstantiationRebuilder> {
11584 SourceLocation Loc;
11585 DeclarationName Entity;
11586
11587 public:
11589
11590 CurrentInstantiationRebuilder(Sema &SemaRef,
11591 SourceLocation Loc,
11592 DeclarationName Entity)
11593 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11594 Loc(Loc), Entity(Entity) { }
11595
11596 /// Determine whether the given type \p T has already been
11597 /// transformed.
11598 ///
11599 /// For the purposes of type reconstruction, a type has already been
11600 /// transformed if it is NULL or if it is not dependent.
11601 bool AlreadyTransformed(QualType T) {
11602 return T.isNull() || !T->isInstantiationDependentType();
11603 }
11604
11605 /// Returns the location of the entity whose type is being
11606 /// rebuilt.
11607 SourceLocation getBaseLocation() { return Loc; }
11608
11609 /// Returns the name of the entity whose type is being rebuilt.
11610 DeclarationName getBaseEntity() { return Entity; }
11611
11612 /// Sets the "base" location and entity when that
11613 /// information is known based on another transformation.
11614 void setBase(SourceLocation Loc, DeclarationName Entity) {
11615 this->Loc = Loc;
11616 this->Entity = Entity;
11617 }
11618
11619 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11620 // Lambdas never need to be transformed.
11621 return E;
11622 }
11623 };
11624} // end anonymous namespace
11625
11627 SourceLocation Loc,
11628 DeclarationName Name) {
11629 if (!T || !T->getType()->isInstantiationDependentType())
11630 return T;
11631
11632 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11633 return Rebuilder.TransformType(T);
11634}
11635
11637 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11638 DeclarationName());
11639 return Rebuilder.TransformExpr(E);
11640}
11641
11643 if (SS.isInvalid())
11644 return true;
11645
11647 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11648 DeclarationName());
11650 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11651 if (!Rebuilt)
11652 return true;
11653
11654 SS.Adopt(Rebuilt);
11655 return false;
11656}
11657
11659 TemplateParameterList *Params) {
11660 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11661 Decl *Param = Params->getParam(I);
11662
11663 // There is nothing to rebuild in a type parameter.
11664 if (isa<TemplateTypeParmDecl>(Param))
11665 continue;
11666
11667 // Rebuild the template parameter list of a template template parameter.
11669 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11671 TTP->getTemplateParameters()))
11672 return true;
11673
11674 continue;
11675 }
11676
11677 // Rebuild the type of a non-type template parameter.
11679 TypeSourceInfo *NewTSI
11681 NTTP->getLocation(),
11682 NTTP->getDeclName());
11683 if (!NewTSI)
11684 return true;
11685
11686 if (NewTSI->getType()->isUndeducedType()) {
11687 // C++17 [temp.dep.expr]p3:
11688 // An id-expression is type-dependent if it contains
11689 // - an identifier associated by name lookup with a non-type
11690 // template-parameter declared with a type that contains a
11691 // placeholder type (7.1.7.4),
11692 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11693 }
11694
11695 if (NewTSI != NTTP->getTypeSourceInfo()) {
11696 NTTP->setTypeSourceInfo(NewTSI);
11697 NTTP->setType(NewTSI->getType());
11698 }
11699 }
11700
11701 return false;
11702}
11703
11704std::string
11706 const TemplateArgumentList &Args) {
11707 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11708}
11709
11710std::string
11712 const TemplateArgument *Args,
11713 unsigned NumArgs) {
11714 SmallString<128> Str;
11715 llvm::raw_svector_ostream Out(Str);
11716
11717 if (!Params || Params->size() == 0 || NumArgs == 0)
11718 return std::string();
11719
11720 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11721 if (I >= NumArgs)
11722 break;
11723
11724 if (I == 0)
11725 Out << "[with ";
11726 else
11727 Out << ", ";
11728
11729 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11730 Out << Id->getName();
11731 } else {
11732 Out << '$' << I;
11733 }
11734
11735 Out << " = ";
11736 Args[I].print(getPrintingPolicy(), Out,
11738 getPrintingPolicy(), Params, I));
11739 }
11740
11741 Out << ']';
11742 return std::string(Out.str());
11743}
11744
11746 CachedTokens &Toks) {
11747 if (!FD)
11748 return;
11749
11750 auto LPT = std::make_unique<LateParsedTemplate>();
11751
11752 // Take tokens to avoid allocations
11753 LPT->Toks.swap(Toks);
11754 LPT->D = FnD;
11755 LPT->FPO = getCurFPFeatures();
11756 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11757
11758 FD->setLateTemplateParsed(true);
11759}
11760
11762 if (!FD)
11763 return;
11764 FD->setLateTemplateParsed(false);
11765}
11766
11768 DeclContext *DC = CurContext;
11769
11770 while (DC) {
11771 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11772 const FunctionDecl *FD = RD->isLocalClass();
11773 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11774 } else if (DC->isTranslationUnit() || DC->isNamespace())
11775 return false;
11776
11777 DC = DC->getParent();
11778 }
11779 return false;
11780}
11781
11782namespace {
11783/// Walk the path from which a declaration was instantiated, and check
11784/// that every explicit specialization along that path is visible. This enforces
11785/// C++ [temp.expl.spec]/6:
11786///
11787/// If a template, a member template or a member of a class template is
11788/// explicitly specialized then that specialization shall be declared before
11789/// the first use of that specialization that would cause an implicit
11790/// instantiation to take place, in every translation unit in which such a
11791/// use occurs; no diagnostic is required.
11792///
11793/// and also C++ [temp.class.spec]/1:
11794///
11795/// A partial specialization shall be declared before the first use of a
11796/// class template specialization that would make use of the partial
11797/// specialization as the result of an implicit or explicit instantiation
11798/// in every translation unit in which such a use occurs; no diagnostic is
11799/// required.
11800class ExplicitSpecializationVisibilityChecker {
11801 Sema &S;
11802 SourceLocation Loc;
11805
11806public:
11807 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11809 : S(S), Loc(Loc), Kind(Kind) {}
11810
11811 void check(NamedDecl *ND) {
11812 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11813 return checkImpl(FD);
11814 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11815 return checkImpl(RD);
11816 if (auto *VD = dyn_cast<VarDecl>(ND))
11817 return checkImpl(VD);
11818 if (auto *ED = dyn_cast<EnumDecl>(ND))
11819 return checkImpl(ED);
11820 }
11821
11822private:
11823 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11824 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11825 : Sema::MissingImportKind::ExplicitSpecialization;
11826 const bool Recover = true;
11827
11828 // If we got a custom set of modules (because only a subset of the
11829 // declarations are interesting), use them, otherwise let
11830 // diagnoseMissingImport intelligently pick some.
11831 if (Modules.empty())
11832 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11833 else
11834 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11835 }
11836
11837 bool CheckMemberSpecialization(const NamedDecl *D) {
11838 return Kind == Sema::AcceptableKind::Visible
11841 }
11842
11843 bool CheckExplicitSpecialization(const NamedDecl *D) {
11844 return Kind == Sema::AcceptableKind::Visible
11847 }
11848
11849 bool CheckDeclaration(const NamedDecl *D) {
11850 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11852 }
11853
11854 // Check a specific declaration. There are three problematic cases:
11855 //
11856 // 1) The declaration is an explicit specialization of a template
11857 // specialization.
11858 // 2) The declaration is an explicit specialization of a member of an
11859 // templated class.
11860 // 3) The declaration is an instantiation of a template, and that template
11861 // is an explicit specialization of a member of a templated class.
11862 //
11863 // We don't need to go any deeper than that, as the instantiation of the
11864 // surrounding class / etc is not triggered by whatever triggered this
11865 // instantiation, and thus should be checked elsewhere.
11866 template<typename SpecDecl>
11867 void checkImpl(SpecDecl *Spec) {
11868 bool IsHiddenExplicitSpecialization = false;
11869 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11870 // Some invalid friend declarations are written as specializations but are
11871 // instantiated implicitly.
11872 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11873 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11874 if (SpecKind == TSK_ExplicitSpecialization) {
11875 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11876 ? !CheckMemberSpecialization(Spec)
11877 : !CheckExplicitSpecialization(Spec);
11878 } else {
11879 checkInstantiated(Spec);
11880 }
11881
11882 if (IsHiddenExplicitSpecialization)
11883 diagnose(Spec->getMostRecentDecl(), false);
11884 }
11885
11886 void checkInstantiated(FunctionDecl *FD) {
11887 if (auto *TD = FD->getPrimaryTemplate())
11888 checkTemplate(TD);
11889 }
11890
11891 void checkInstantiated(CXXRecordDecl *RD) {
11892 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11893 if (!SD)
11894 return;
11895
11896 auto From = SD->getSpecializedTemplateOrPartial();
11897 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11898 checkTemplate(TD);
11899 else if (auto *TD =
11900 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11901 if (!CheckDeclaration(TD))
11902 diagnose(TD, true);
11903 checkTemplate(TD);
11904 }
11905 }
11906
11907 void checkInstantiated(VarDecl *RD) {
11908 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11909 if (!SD)
11910 return;
11911
11912 auto From = SD->getSpecializedTemplateOrPartial();
11913 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11914 checkTemplate(TD);
11915 else if (auto *TD =
11916 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11917 if (!CheckDeclaration(TD))
11918 diagnose(TD, true);
11919 checkTemplate(TD);
11920 }
11921 }
11922
11923 void checkInstantiated(EnumDecl *FD) {}
11924
11925 template<typename TemplDecl>
11926 void checkTemplate(TemplDecl *TD) {
11927 if (TD->isMemberSpecialization()) {
11928 if (!CheckMemberSpecialization(TD))
11929 diagnose(TD->getMostRecentDecl(), false);
11930 }
11931 }
11932};
11933} // end anonymous namespace
11934
11936 if (!getLangOpts().Modules)
11937 return;
11938
11939 ExplicitSpecializationVisibilityChecker(*this, Loc,
11941 .check(Spec);
11942}
11943
11945 NamedDecl *Spec) {
11946 if (!getLangOpts().CPlusPlusModules)
11947 return checkSpecializationVisibility(Loc, Spec);
11948
11949 ExplicitSpecializationVisibilityChecker(*this, Loc,
11951 .check(Spec);
11952}
11953
11956 return N->getLocation();
11957 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11959 return FD->getLocation();
11962 return N->getLocation();
11963 }
11964 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11965 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11966 continue;
11967 return CSC.PointOfInstantiation;
11968 }
11969 return N->getLocation();
11970}
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:1020
APSInt & getInt()
Definition APValue.h:511
APSInt & getComplexIntImag()
Definition APValue.h:549
ValueKind getKind() const
Definition APValue.h:482
APFixedPoint & getFixedPoint()
Definition APValue.h:533
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1103
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
bool isMemberPointer() const
Definition APValue.h:499
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
@ 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:1056
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
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:2032
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:2062
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2039
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2073
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:704
void ClearStorageClassSpecs()
Definition DeclSpec.h:546
bool isNoreturnSpecified() const
Definition DeclSpec.h:717
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:541
SCS getStorageClassSpec() const
Definition DeclSpec.h:532
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:609
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:608
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:718
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:710
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:533
ParsedAttributes & getAttributes()
Definition DeclSpec.h:929
bool isInlineSpecified() const
Definition DeclSpec.h:693
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:542
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:705
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:892
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:696
bool hasExplicitSpecifier() const
Definition DeclSpec.h:707
bool hasConstexprSpecifier() const
Definition DeclSpec.h:893
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:2001
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2148
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2437
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2827
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2184
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2163
bool hasEllipsis() const
Definition DeclSpec.h:2826
bool isInvalidType() const
Definition DeclSpec.h:2815
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2183
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2155
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2431
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:377
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:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
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:13793
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8535
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:11536
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11544
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12595
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12629
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7804
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:13740
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13191
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2678
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:9417
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9421
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9429
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9424
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:9733
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:4211
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:11507
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12106
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12109
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12113
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:769
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:12285
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12303
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12293
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12313
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:11557
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11564
@ None
This is not assumed to be a template name.
Definition Sema.h:11559
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11561
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:11493
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:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
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:14582
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14570
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14579
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14573
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14597
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:647
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:13831
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:15597
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:4709
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:6824
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6803
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:14093
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:11534
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:523
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:11717
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11727
@ TPC_FriendFunctionTemplate
Definition Sema.h:11725
@ TPC_ClassTemplateMember
Definition Sema.h:11723
@ TPC_FunctionTemplate
Definition Sema.h:11722
@ TPC_FriendClassTemplate
Definition Sema.h:11724
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11726
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:6374
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:6511
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:11499
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:9742
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13034
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:8749
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13828
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:1088
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1300
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1297
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1116
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1170
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1140
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:1984
@ 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:1080
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1072
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1066
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1068
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:1305
@ 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:12144
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12140
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12133
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12130
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12130
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13242
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13346
A stack object to be created when performing template instantiation.
Definition Sema.h:13436
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13589
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:1099