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"
16#include "clang/AST/DeclCXX.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
24#include "clang/AST/Type.h"
33#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/Overload.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/Template.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SmallBitVector.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/SaveAndRestore.h"
49
50#include <optional>
51using namespace clang;
52using namespace sema;
53
54// Exported for use by Parser.
57 unsigned N) {
58 if (!N) return SourceRange();
59 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
60}
61
62unsigned Sema::getTemplateDepth(Scope *S) const {
63 unsigned Depth = 0;
64
65 // Each template parameter scope represents one level of template parameter
66 // depth.
67 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
68 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
69 ++Depth;
70 }
71
72 // Note that there are template parameters with the given depth.
73 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
74
75 // Look for parameters of an enclosing generic lambda. We don't create a
76 // template parameter scope for these.
78 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
79 if (!LSI->TemplateParams.empty()) {
80 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
81 break;
82 }
83 if (LSI->GLTemplateParameterList) {
84 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
85 break;
86 }
87 }
88 }
89
90 // Look for parameters of an enclosing terse function template. We don't
91 // create a template parameter scope for these either.
92 for (const InventedTemplateParameterInfo &Info :
94 if (!Info.TemplateParams.empty()) {
95 ParamsAtDepth(Info.AutoTemplateParameterDepth);
96 break;
97 }
98 }
99
100 return Depth;
101}
102
103/// \brief Determine whether the declaration found is acceptable as the name
104/// of a template and, if so, return that template declaration. Otherwise,
105/// returns null.
106///
107/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
108/// is true. In all other cases it will return a TemplateDecl (or null).
110 bool AllowFunctionTemplates,
111 bool AllowDependent) {
112 D = D->getUnderlyingDecl();
113
114 if (isa<TemplateDecl>(D)) {
115 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
116 return nullptr;
117
118 return D;
119 }
120
121 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
122 // C++ [temp.local]p1:
123 // Like normal (non-template) classes, class templates have an
124 // injected-class-name (Clause 9). The injected-class-name
125 // can be used with or without a template-argument-list. When
126 // it is used without a template-argument-list, it is
127 // equivalent to the injected-class-name followed by the
128 // template-parameters of the class template enclosed in
129 // <>. When it is used with a template-argument-list, it
130 // refers to the specified class template specialization,
131 // which could be the current specialization or another
132 // specialization.
133 if (Record->isInjectedClassName()) {
134 Record = cast<CXXRecordDecl>(Record->getDeclContext());
135 if (Record->getDescribedClassTemplate())
136 return Record->getDescribedClassTemplate();
137
138 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
139 return Spec->getSpecializedTemplate();
140 }
141
142 return nullptr;
143 }
144
145 // 'using Dependent::foo;' can resolve to a template name.
146 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
147 // injected-class-name).
148 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
149 return D;
150
151 return nullptr;
152}
153
155 bool AllowFunctionTemplates,
156 bool AllowDependent) {
157 LookupResult::Filter filter = R.makeFilter();
158 while (filter.hasNext()) {
159 NamedDecl *Orig = filter.next();
160 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
161 filter.erase();
162 }
163 filter.done();
164}
165
167 bool AllowFunctionTemplates,
168 bool AllowDependent,
169 bool AllowNonTemplateFunctions) {
170 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
171 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
172 return true;
173 if (AllowNonTemplateFunctions &&
174 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
175 return true;
176 }
177
178 return false;
179}
180
182Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
183 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
184 bool EnteringContext, TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool AllowTypoCorrection) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate, AllowTypoCorrection))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241 if (isa<FunctionTemplateDecl>(FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
279 R.suppressDiagnostics();
280 } else {
281 if (!D) {
282 D = getAsTemplateNameDecl(*R.begin());
283 assert(D && "unambiguous result is not a template name");
284 }
285
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299 Template);
300 }
301
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
306 R.suppressDiagnostics();
307 } else {
311 TemplateKind =
313 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
317 }
318 }
319
321 S->getTemplateParamParent() == nullptr)
322 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
323 // Recover by returning the template, even though we would never be able to
324 // substitute it.
325
326 TemplateResult = TemplateTy::make(Template);
327 return TemplateKind;
328}
329
331 SourceLocation NameLoc, CXXScopeSpec &SS,
332 ParsedTemplateTy *Template /*=nullptr*/) {
333 // We could use redeclaration lookup here, but we don't need to: the
334 // syntactic form of a deduction guide is enough to identify it even
335 // if we can't look up the template name at all.
336 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
337 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
338 /*EnteringContext*/ false))
339 return false;
340
341 if (R.empty()) return false;
342 if (R.isAmbiguous()) {
343 // FIXME: Diagnose an ambiguity if we find at least one template.
344 R.suppressDiagnostics();
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
350 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
351 if (!TD || !getAsTypeTemplateDecl(TD))
352 return false;
353
354 if (Template) {
355 TemplateName Name = Context.getQualifiedTemplateName(
356 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
357 *Template = TemplateTy::make(Name);
358 }
359 return true;
360}
361
363 SourceLocation IILoc,
364 Scope *S,
365 const CXXScopeSpec *SS,
366 TemplateTy &SuggestedTemplate,
367 TemplateNameKind &SuggestedKind) {
368 // We can't recover unless there's a dependent scope specifier preceding the
369 // template name.
370 // FIXME: Typo correction?
371 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
373 return false;
374
375 // The code is missing a 'template' keyword prior to the dependent template
376 // name.
377 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
378 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
379 Diag(IILoc, diag::err_template_kw_missing)
380 << SuggestedTemplate.get()
381 << FixItHint::CreateInsertion(IILoc, "template ");
382 SuggestedKind = TNK_Dependent_template_name;
383 return true;
384}
385
387 QualType ObjectType, bool EnteringContext,
388 RequiredTemplateKind RequiredTemplate,
390 bool AllowTypoCorrection) {
391 if (ATK)
393
394 if (SS.isInvalid())
395 return true;
396
397 Found.setTemplateNameLookup(true);
398
399 // Determine where to perform name lookup
400 DeclContext *LookupCtx = nullptr;
401 bool IsDependent = false;
402 if (!ObjectType.isNull()) {
403 // This nested-name-specifier occurs in a member access expression, e.g.,
404 // x->B::f, and we are looking into the type of the object.
405 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
406 LookupCtx = computeDeclContext(ObjectType);
407 IsDependent = !LookupCtx && ObjectType->isDependentType();
408 assert((IsDependent || !ObjectType->isIncompleteType() ||
409 !ObjectType->getAs<TagType>() ||
410 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
411 "Caller should have completed object type");
412
413 // Template names cannot appear inside an Objective-C class or object type
414 // or a vector type.
415 //
416 // FIXME: This is wrong. For example:
417 //
418 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
419 // Vec<int> vi;
420 // vi.Vec<int>::~Vec<int>();
421 //
422 // ... should be accepted but we will not treat 'Vec' as a template name
423 // here. The right thing to do would be to check if the name is a valid
424 // vector component name, and look up a template name if not. And similarly
425 // for lookups into Objective-C class and object types, where the same
426 // problem can arise.
427 if (ObjectType->isObjCObjectOrInterfaceType() ||
428 ObjectType->isVectorType()) {
429 Found.clear();
430 return false;
431 }
432 } else if (SS.isNotEmpty()) {
433 // This nested-name-specifier occurs after another nested-name-specifier,
434 // so long into the context associated with the prior nested-name-specifier.
435 LookupCtx = computeDeclContext(SS, EnteringContext);
436 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
437
438 // The declaration context must be complete.
439 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
440 return true;
441 }
442
443 bool ObjectTypeSearchedInScope = false;
444 bool AllowFunctionTemplatesInLookup = true;
445 if (LookupCtx) {
446 // Perform "qualified" name lookup into the declaration context we
447 // computed, which is either the type of the base of a member access
448 // expression or the declaration context associated with a prior
449 // nested-name-specifier.
450 LookupQualifiedName(Found, LookupCtx);
451
452 // FIXME: The C++ standard does not clearly specify what happens in the
453 // case where the object type is dependent, and implementations vary. In
454 // Clang, we treat a name after a . or -> as a template-name if lookup
455 // finds a non-dependent member or member of the current instantiation that
456 // is a type template, or finds no such members and lookup in the context
457 // of the postfix-expression finds a type template. In the latter case, the
458 // name is nonetheless dependent, and we may resolve it to a member of an
459 // unknown specialization when we come to instantiate the template.
460 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
461 }
462
463 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
464 // C++ [basic.lookup.classref]p1:
465 // In a class member access expression (5.2.5), if the . or -> token is
466 // immediately followed by an identifier followed by a <, the
467 // identifier must be looked up to determine whether the < is the
468 // beginning of a template argument list (14.2) or a less-than operator.
469 // The identifier is first looked up in the class of the object
470 // expression. If the identifier is not found, it is then looked up in
471 // the context of the entire postfix-expression and shall name a class
472 // template.
473 if (S)
474 LookupName(Found, S);
475
476 if (!ObjectType.isNull()) {
477 // FIXME: We should filter out all non-type templates here, particularly
478 // variable templates and concepts. But the exclusion of alias templates
479 // and template template parameters is a wording defect.
480 AllowFunctionTemplatesInLookup = false;
481 ObjectTypeSearchedInScope = true;
482 }
483
484 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
485 }
486
487 if (Found.isAmbiguous())
488 return false;
489
490 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
491 !RequiredTemplate.hasTemplateKeyword()) {
492 // C++2a [temp.names]p2:
493 // A name is also considered to refer to a template if it is an
494 // unqualified-id followed by a < and name lookup finds either one or more
495 // functions or finds nothing.
496 //
497 // To keep our behavior consistent, we apply the "finds nothing" part in
498 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
499 // successfully form a call to an undeclared template-id.
500 bool AllFunctions =
501 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
503 });
504 if (AllFunctions || (Found.empty() && !IsDependent)) {
505 // If lookup found any functions, or if this is a name that can only be
506 // used for a function, then strongly assume this is a function
507 // template-id.
508 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
511 Found.clear();
512 return false;
513 }
514 }
515
516 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
517 // If we did not find any names, and this is not a disambiguation, attempt
518 // to correct any typos.
519 DeclarationName Name = Found.getLookupName();
520 Found.clear();
521
522 class TemplateNameLookupValidatorCCC final
524 public:
526
527 bool ValidateCandidate(const TypoCorrection &Candidate) final {
528 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
529 !ND || !isa<TemplateDecl>(ND))
530 return false;
532 }
533
534 std::unique_ptr<CorrectionCandidateCallback> clone() final {
535 return std::make_unique<TemplateNameLookupValidatorCCC>(*this);
536 }
537 };
538
539 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
540 FilterCCC.WantTypeSpecifiers = false;
541 FilterCCC.WantExpressionKeywords = false;
542 FilterCCC.WantRemainingKeywords = false;
543 FilterCCC.WantCXXNamedCasts = true;
544 if (TypoCorrection Corrected = CorrectTypo(
545 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
546 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
547 if (auto *ND = Corrected.getFoundDecl())
548 Found.addDecl(ND);
550 if (Found.isAmbiguous()) {
551 Found.clear();
552 } else if (!Found.empty()) {
553 // Do not erase the typo-corrected result to avoid duplicated
554 // diagnostics.
555 AllowFunctionTemplatesInLookup = true;
556 Found.setLookupName(Corrected.getCorrection());
557 if (LookupCtx) {
558 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
559 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
560 Name.getAsString() == CorrectedStr;
561 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
562 << Name << LookupCtx << DroppedSpecifier
563 << SS.getRange());
564 } else {
565 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
566 }
567
568 if (Corrected.WillReplaceSpecifier()) {
569 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
570 // In order to be valid, a non-empty CXXScopeSpec needs a source
571 // range.
572 SS.MakeTrivial(Context, NNS,
573 NNS ? Found.getNameLoc() : SourceRange());
574 }
575 }
576 }
577 }
578
579 NamedDecl *ExampleLookupResult =
580 Found.empty() ? nullptr : Found.getRepresentativeDecl();
581 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
582 if (Found.empty()) {
583 if (IsDependent) {
584 Found.setNotFoundInCurrentInstantiation();
585 return false;
586 }
587
588 // If a 'template' keyword was used, a lookup that finds only non-template
589 // names is an error.
590 if (ExampleLookupResult && RequiredTemplate) {
591 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
592 << Found.getLookupName() << SS.getRange()
593 << RequiredTemplate.hasTemplateKeyword()
594 << RequiredTemplate.getTemplateKeywordLoc();
595 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
596 diag::note_template_kw_refers_to_non_template)
597 << Found.getLookupName();
598 return true;
599 }
600
601 return false;
602 }
603
604 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
606 // C++03 [basic.lookup.classref]p1:
607 // [...] If the lookup in the class of the object expression finds a
608 // template, the name is also looked up in the context of the entire
609 // postfix-expression and [...]
610 //
611 // Note: C++11 does not perform this second lookup.
612 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
614 FoundOuter.setTemplateNameLookup(true);
615 LookupName(FoundOuter, S);
616 // FIXME: We silently accept an ambiguous lookup here, in violation of
617 // [basic.lookup]/1.
618 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
619
620 NamedDecl *OuterTemplate;
621 if (FoundOuter.empty()) {
622 // - if the name is not found, the name found in the class of the
623 // object expression is used, otherwise
624 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
625 !(OuterTemplate =
626 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
627 // - if the name is found in the context of the entire
628 // postfix-expression and does not name a class template, the name
629 // found in the class of the object expression is used, otherwise
630 FoundOuter.clear();
631 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
632 // - if the name found is a class template, it must refer to the same
633 // entity as the one found in the class of the object expression,
634 // otherwise the program is ill-formed.
635 if (!Found.isSingleResult() ||
636 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
637 OuterTemplate->getCanonicalDecl()) {
638 Diag(Found.getNameLoc(),
639 diag::ext_nested_name_member_ref_lookup_ambiguous)
640 << Found.getLookupName()
641 << ObjectType;
642 Diag(Found.getRepresentativeDecl()->getLocation(),
643 diag::note_ambig_member_ref_object_type)
644 << ObjectType;
645 Diag(FoundOuter.getFoundDecl()->getLocation(),
646 diag::note_ambig_member_ref_scope);
647
648 // Recover by taking the template that we found in the object
649 // expression's type.
650 }
651 }
652 }
653
654 return false;
655}
656
660 if (TemplateName.isInvalid())
661 return;
662
663 DeclarationNameInfo NameInfo;
664 CXXScopeSpec SS;
665 LookupNameKind LookupKind;
666
667 DeclContext *LookupCtx = nullptr;
668 NamedDecl *Found = nullptr;
669 bool MissingTemplateKeyword = false;
670
671 // Figure out what name we looked up.
672 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
673 NameInfo = DRE->getNameInfo();
674 SS.Adopt(DRE->getQualifierLoc());
675 LookupKind = LookupOrdinaryName;
676 Found = DRE->getFoundDecl();
677 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
678 NameInfo = ME->getMemberNameInfo();
679 SS.Adopt(ME->getQualifierLoc());
680 LookupKind = LookupMemberName;
681 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
682 Found = ME->getMemberDecl();
683 } else if (auto *DSDRE =
684 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
685 NameInfo = DSDRE->getNameInfo();
686 SS.Adopt(DSDRE->getQualifierLoc());
687 MissingTemplateKeyword = true;
688 } else if (auto *DSME =
689 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
690 NameInfo = DSME->getMemberNameInfo();
691 SS.Adopt(DSME->getQualifierLoc());
692 MissingTemplateKeyword = true;
693 } else {
694 llvm_unreachable("unexpected kind of potential template name");
695 }
696
697 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
698 // was missing.
699 if (MissingTemplateKeyword) {
700 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
701 << NameInfo.getName() << SourceRange(Less, Greater);
702 return;
703 }
704
705 // Try to correct the name by looking for templates and C++ named casts.
706 struct TemplateCandidateFilter : CorrectionCandidateCallback {
707 Sema &S;
708 TemplateCandidateFilter(Sema &S) : S(S) {
709 WantTypeSpecifiers = false;
710 WantExpressionKeywords = false;
711 WantRemainingKeywords = false;
712 WantCXXNamedCasts = true;
713 };
714 bool ValidateCandidate(const TypoCorrection &Candidate) override {
715 if (auto *ND = Candidate.getCorrectionDecl())
716 return S.getAsTemplateNameDecl(ND);
717 return Candidate.isKeyword();
718 }
719
720 std::unique_ptr<CorrectionCandidateCallback> clone() override {
721 return std::make_unique<TemplateCandidateFilter>(*this);
722 }
723 };
724
725 DeclarationName Name = NameInfo.getName();
726 TemplateCandidateFilter CCC(*this);
727 if (TypoCorrection Corrected =
728 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
729 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
730 auto *ND = Corrected.getFoundDecl();
731 if (ND)
732 ND = getAsTemplateNameDecl(ND);
733 if (ND || Corrected.isKeyword()) {
734 if (LookupCtx) {
735 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
736 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
737 Name.getAsString() == CorrectedStr;
738 diagnoseTypo(Corrected,
739 PDiag(diag::err_non_template_in_member_template_id_suggest)
740 << Name << LookupCtx << DroppedSpecifier
741 << SS.getRange(), false);
742 } else {
743 diagnoseTypo(Corrected,
744 PDiag(diag::err_non_template_in_template_id_suggest)
745 << Name, false);
746 }
747 if (Found)
748 Diag(Found->getLocation(),
749 diag::note_non_template_in_template_id_found);
750 return;
751 }
752 }
753
754 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
755 << Name << SourceRange(Less, Greater);
756 if (Found)
757 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
758}
759
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 bool isAddressOfOperand,
765 const TemplateArgumentListInfo *TemplateArgs) {
766 if (SS.isEmpty()) {
767 // FIXME: This codepath is only used by dependent unqualified names
768 // (e.g. a dependent conversion-function-id, or operator= once we support
769 // it). It doesn't quite do the right thing, and it will silently fail if
770 // getCurrentThisType() returns null.
771 QualType ThisType = getCurrentThisType();
772 if (ThisType.isNull())
773 return ExprError();
774
776 Context, /*Base=*/nullptr, ThisType,
777 /*IsArrow=*/!Context.getLangOpts().HLSL,
778 /*OperatorLoc=*/SourceLocation(),
779 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
780 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
781 }
782 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
783}
784
787 SourceLocation TemplateKWLoc,
788 const DeclarationNameInfo &NameInfo,
789 const TemplateArgumentListInfo *TemplateArgs) {
790 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
791 if (!SS.isValid())
792 return CreateRecoveryExpr(
793 SS.getBeginLoc(),
794 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
795
797 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
798 TemplateArgs);
799}
800
802Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
803 QualType ParamType, SourceLocation Loc,
805 UnsignedOrNone PackIndex, bool Final) {
806 // The template argument itself might be an expression, in which case we just
807 // return that expression. This happens when substituting into an alias
808 // template.
809 Expr *Replacement;
811 Replacement = Arg.getAsExpr();
812 } else {
813 ExprResult result =
814 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
815 if (result.isInvalid())
816 return ExprError();
817 Replacement = result.get();
818 }
819 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
820 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
821 AssociatedDecl, ParamType, Index, PackIndex, Final);
822}
823
825 NamedDecl *Instantiation,
826 bool InstantiatedFromMember,
827 const NamedDecl *Pattern,
828 const NamedDecl *PatternDef,
830 bool Complain, bool *Unreachable) {
831 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
832 isa<VarDecl>(Instantiation));
833
834 bool IsEntityBeingDefined = false;
835 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
836 IsEntityBeingDefined = TD->isBeingDefined();
837
838 if (PatternDef && !IsEntityBeingDefined) {
839 NamedDecl *SuggestedDef = nullptr;
840 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
841 &SuggestedDef,
842 /*OnlyNeedComplete*/ false)) {
843 if (Unreachable)
844 *Unreachable = true;
845 // If we're allowed to diagnose this and recover, do so.
846 bool Recover = Complain && !isSFINAEContext();
847 if (Complain)
848 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
850 return !Recover;
851 }
852 return false;
853 }
854
855 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
856 return true;
857
858 CanQualType InstantiationTy;
859 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
860 InstantiationTy = Context.getCanonicalTagType(TD);
861 if (PatternDef) {
862 Diag(PointOfInstantiation,
863 diag::err_template_instantiate_within_definition)
864 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
865 << InstantiationTy;
866 // Not much point in noting the template declaration here, since
867 // we're lexically inside it.
868 Instantiation->setInvalidDecl();
869 } else if (InstantiatedFromMember) {
870 if (isa<FunctionDecl>(Instantiation)) {
871 Diag(PointOfInstantiation,
872 diag::err_explicit_instantiation_undefined_member)
873 << /*member function*/ 1 << Instantiation->getDeclName()
874 << Instantiation->getDeclContext();
875 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
876 } else {
877 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
878 Diag(PointOfInstantiation,
879 diag::err_implicit_instantiate_member_undefined)
880 << InstantiationTy;
881 Diag(Pattern->getLocation(), diag::note_member_declared_at);
882 }
883 } else {
884 if (isa<FunctionDecl>(Instantiation)) {
885 Diag(PointOfInstantiation,
886 diag::err_explicit_instantiation_undefined_func_template)
887 << Pattern;
888 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
889 } else if (isa<TagDecl>(Instantiation)) {
890 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
891 << (TSK != TSK_ImplicitInstantiation)
892 << InstantiationTy;
893 NoteTemplateLocation(*Pattern);
894 } else {
895 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
896 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
897 Diag(PointOfInstantiation,
898 diag::err_explicit_instantiation_undefined_var_template)
899 << Instantiation;
900 Instantiation->setInvalidDecl();
901 } else
902 Diag(PointOfInstantiation,
903 diag::err_explicit_instantiation_undefined_member)
904 << /*static data member*/ 2 << Instantiation->getDeclName()
905 << Instantiation->getDeclContext();
906 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
907 }
908 }
909
910 // In general, Instantiation isn't marked invalid to get more than one
911 // error for multiple undefined instantiations. But the code that does
912 // explicit declaration -> explicit definition conversion can't handle
913 // invalid declarations, so mark as invalid in that case.
915 Instantiation->setInvalidDecl();
916 return true;
917}
918
920 bool SupportedForCompatibility) {
921 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
922
923 // C++23 [temp.local]p6:
924 // The name of a template-parameter shall not be bound to any following.
925 // declaration whose locus is contained by the scope to which the
926 // template-parameter belongs.
927 //
928 // When MSVC compatibility is enabled, the diagnostic is always a warning
929 // by default. Otherwise, it an error unless SupportedForCompatibility is
930 // true, in which case it is a default-to-error warning.
931 unsigned DiagId =
932 getLangOpts().MSVCCompat
933 ? diag::ext_template_param_shadow
934 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
935 : diag::err_template_param_shadow);
936 const auto *ND = cast<NamedDecl>(PrevDecl);
937 Diag(Loc, DiagId) << ND->getDeclName();
939}
940
942 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
943 D = Temp->getTemplatedDecl();
944 return Temp;
945 }
946 return nullptr;
947}
948
950 SourceLocation EllipsisLoc) const {
951 assert(Kind == Template &&
952 "Only template template arguments can be pack expansions here");
953 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
954 "Template template argument pack expansion without packs");
956 Result.EllipsisLoc = EllipsisLoc;
957 return Result;
958}
959
961 const ParsedTemplateArgument &Arg) {
962
963 switch (Arg.getKind()) {
965 TypeSourceInfo *TSI;
966 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
967 if (!TSI)
968 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
970 }
971
973 Expr *E = Arg.getAsExpr();
974 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
975 }
976
979 TemplateArgument TArg;
980 if (Arg.getEllipsisLoc().isValid())
981 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
982 else
983 TArg = Template;
984 return TemplateArgumentLoc(
985 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
987 Arg.getNameLoc(), Arg.getEllipsisLoc());
988 }
989 }
990
991 llvm_unreachable("Unhandled parsed template argument");
992}
993
995 TemplateArgumentListInfo &TemplateArgs) {
996 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
997 TemplateArgs.addArgument(translateTemplateArgument(*this,
998 TemplateArgsIn[I]));
999}
1000
1002 SourceLocation Loc,
1003 const IdentifierInfo *Name) {
1004 NamedDecl *PrevDecl =
1005 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
1007 if (PrevDecl && PrevDecl->isTemplateParameter())
1008 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1009}
1010
1012 TypeSourceInfo *TInfo;
1013 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1014 if (T.isNull())
1015 return ParsedTemplateArgument();
1016 assert(TInfo && "template argument with no location");
1017
1018 // If we might have formed a deduced template specialization type, convert
1019 // it to a template template argument.
1020 if (getLangOpts().CPlusPlus17) {
1021 TypeLoc TL = TInfo->getTypeLoc();
1022 SourceLocation EllipsisLoc;
1023 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1024 EllipsisLoc = PET.getEllipsisLoc();
1025 TL = PET.getPatternLoc();
1026 }
1027
1028 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1029 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1030 CXXScopeSpec SS;
1031 SS.Adopt(DTST.getQualifierLoc());
1032 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1033 TemplateTy::make(Name),
1034 DTST.getTemplateNameLoc());
1035 if (EllipsisLoc.isValid())
1036 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1037 return Result;
1038 }
1039 }
1040
1041 // This is a normal type template argument. Note, if the type template
1042 // argument is an injected-class-name for a template, it has a dual nature
1043 // and can be used as either a type or a template. We handle that in
1044 // convertTypeTemplateArgumentToTemplate.
1046 ParsedType.get().getAsOpaquePtr(),
1047 TInfo->getTypeLoc().getBeginLoc());
1048}
1049
1051 SourceLocation EllipsisLoc,
1052 SourceLocation KeyLoc,
1053 IdentifierInfo *ParamName,
1054 SourceLocation ParamNameLoc,
1055 unsigned Depth, unsigned Position,
1056 SourceLocation EqualLoc,
1057 ParsedType DefaultArg,
1058 bool HasTypeConstraint) {
1059 assert(S->isTemplateParamScope() &&
1060 "Template type parameter not in template parameter scope!");
1061
1062 bool IsParameterPack = EllipsisLoc.isValid();
1064 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1065 KeyLoc, ParamNameLoc, Depth, Position,
1066 ParamName, Typename, IsParameterPack,
1067 HasTypeConstraint);
1068 Param->setAccess(AS_public);
1069
1070 if (Param->isParameterPack())
1071 if (auto *CSI = getEnclosingLambdaOrBlock())
1072 CSI->LocalPacks.push_back(Param);
1073
1074 if (ParamName) {
1075 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1076
1077 // Add the template parameter into the current scope.
1078 S->AddDecl(Param);
1079 IdResolver.AddDecl(Param);
1080 }
1081
1082 // C++0x [temp.param]p9:
1083 // A default template-argument may be specified for any kind of
1084 // template-parameter that is not a template parameter pack.
1085 if (DefaultArg && IsParameterPack) {
1086 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1087 DefaultArg = nullptr;
1088 }
1089
1090 // Handle the default argument, if provided.
1091 if (DefaultArg) {
1092 TypeSourceInfo *DefaultTInfo;
1093 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1094
1095 assert(DefaultTInfo && "expected source information for type");
1096
1097 // Check for unexpanded parameter packs.
1098 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1100 return Param;
1101
1102 // Check the template argument itself.
1103 if (CheckTemplateArgument(DefaultTInfo)) {
1104 Param->setInvalidDecl();
1105 return Param;
1106 }
1107
1108 Param->setDefaultArgument(
1109 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1110 }
1111
1112 return Param;
1113}
1114
1115/// Convert the parser's template argument list representation into our form.
1118 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1119 TemplateId.RAngleLoc);
1120 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1121 TemplateId.NumArgs);
1122 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1123 return TemplateArgs;
1124}
1125
1127
1128 TemplateName TN = TypeConstr->Template.get();
1129 NamedDecl *CD = nullptr;
1130 bool IsTypeConcept = false;
1131 bool RequiresArguments = false;
1132 if (auto *TTP = TN.getAsTemplateTemplateParmDecl()) {
1133 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1134 RequiresArguments =
1135 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1136 CD = TTP;
1137 } else {
1138 CD = TN.getAsTemplateDecl();
1139 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1140 RequiresArguments = cast<ConceptDecl>(CD)
1141 ->getTemplateParameters()
1142 ->getMinRequiredArguments() > 1;
1143 }
1144
1145 // C++2a [temp.param]p4:
1146 // [...] The concept designated by a type-constraint shall be a type
1147 // concept ([temp.concept]).
1148 if (!IsTypeConcept) {
1149 Diag(TypeConstr->TemplateNameLoc,
1150 diag::err_type_constraint_non_type_concept);
1151 return true;
1152 }
1153
1154 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1155 return true;
1156
1157 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1158
1159 if (!WereArgsSpecified && RequiresArguments) {
1160 Diag(TypeConstr->TemplateNameLoc,
1161 diag::err_type_constraint_missing_arguments)
1162 << CD;
1163 return true;
1164 }
1165 return false;
1166}
1167
1169 TemplateIdAnnotation *TypeConstr,
1170 TemplateTypeParmDecl *ConstrainedParameter,
1171 SourceLocation EllipsisLoc) {
1172 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1173 false);
1174}
1175
1177 TemplateIdAnnotation *TypeConstr,
1178 TemplateTypeParmDecl *ConstrainedParameter,
1179 SourceLocation EllipsisLoc,
1180 bool AllowUnexpandedPack) {
1181
1182 if (CheckTypeConstraint(TypeConstr))
1183 return true;
1184
1185 TemplateName TN = TypeConstr->Template.get();
1188
1189 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1190 TypeConstr->TemplateNameLoc);
1191
1192 TemplateArgumentListInfo TemplateArgs;
1193 if (TypeConstr->LAngleLoc.isValid()) {
1194 TemplateArgs =
1195 makeTemplateArgumentListInfo(*this, *TypeConstr);
1196
1197 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1198 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1200 return true;
1201 }
1202 }
1203 }
1204 return AttachTypeConstraint(
1206 ConceptName, TN,
1207 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : cast_if_present<NamedDecl>(CD),
1208 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1209 ConstrainedParameter, EllipsisLoc);
1210}
1211
1212template <typename ArgumentLocAppender>
1215 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1216 SourceLocation RAngleLoc, QualType ConstrainedType,
1217 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1218 SourceLocation EllipsisLoc) {
1219
1220 TemplateArgumentListInfo ConstraintArgs;
1221 ConstraintArgs.addArgument(
1223 /*NTTPType=*/QualType(), ParamNameLoc));
1224
1225 ConstraintArgs.setRAngleLoc(RAngleLoc);
1226 ConstraintArgs.setLAngleLoc(LAngleLoc);
1227 Appender(ConstraintArgs);
1228
1229 // C++2a [temp.param]p4:
1230 // [...] This constraint-expression E is called the immediately-declared
1231 // constraint of T. [...]
1232 CXXScopeSpec SS;
1233 SS.Adopt(NS);
1234 ExprResult ImmediatelyDeclaredConstraint;
1235 if (auto *CD =
1236 dyn_cast_if_present<ConceptDecl>(NamedConcept.getAsTemplateDecl())) {
1237 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1238 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1239 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1240 /*DoCheckConstraintSatisfaction=*/
1242 }
1243 // We have a template template parameter
1244 else {
1245 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1246 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1247 NameInfo, NamedConcept, &ConstraintArgs);
1248 }
1249 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1250 return ImmediatelyDeclaredConstraint;
1251
1252 // C++2a [temp.param]p4:
1253 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1254 //
1255 // We have the following case:
1256 //
1257 // template<typename T> concept C1 = true;
1258 // template<C1... T> struct s1;
1259 //
1260 // The constraint: (C1<T> && ...)
1261 //
1262 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1263 // any unqualified lookups for 'operator&&' here.
1264 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1265 /*LParenLoc=*/SourceLocation(),
1266 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1267 EllipsisLoc, /*RHS=*/nullptr,
1268 /*RParenLoc=*/SourceLocation(),
1269 /*NumExpansions=*/std::nullopt);
1270}
1271
1273 DeclarationNameInfo NameInfo,
1274 TemplateName NamedConcept, NamedDecl *FoundDecl,
1275 const TemplateArgumentListInfo *TemplateArgs,
1276 TemplateTypeParmDecl *ConstrainedParameter,
1277 SourceLocation EllipsisLoc) {
1278 // C++2a [temp.param]p4:
1279 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1280 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1281 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1283 *TemplateArgs) : nullptr;
1284
1285 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1286
1287 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1288 *this, NS, NameInfo, NamedConcept, FoundDecl,
1289 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1290 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1291 ParamAsArgument, ConstrainedParameter->getLocation(),
1292 [&](TemplateArgumentListInfo &ConstraintArgs) {
1293 if (TemplateArgs)
1294 for (const auto &ArgLoc : TemplateArgs->arguments())
1295 ConstraintArgs.addArgument(ArgLoc);
1296 },
1297 EllipsisLoc);
1298 if (ImmediatelyDeclaredConstraint.isInvalid())
1299 return true;
1300
1301 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1302 /*TemplateKWLoc=*/SourceLocation{},
1303 /*ConceptNameInfo=*/NameInfo,
1304 /*FoundDecl=*/FoundDecl,
1305 /*NamedConcept=*/NamedConcept,
1306 /*ArgsWritten=*/ArgsAsWritten);
1307 ConstrainedParameter->setTypeConstraint(
1308 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1309 return false;
1310}
1311
1313 NonTypeTemplateParmDecl *NewConstrainedParm,
1314 NonTypeTemplateParmDecl *OrigConstrainedParm,
1315 SourceLocation EllipsisLoc) {
1316 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1318 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1319 diag::err_unsupported_placeholder_constraint)
1320 << NewConstrainedParm->getTypeSourceInfo()
1321 ->getTypeLoc()
1322 .getSourceRange();
1323 NewConstrainedParm->setType(TL.getType());
1324 return true;
1325 }
1326 // FIXME: Concepts: This should be the type of the placeholder, but this is
1327 // unclear in the wording right now.
1328 DeclRefExpr *Ref =
1329 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1330 VK_PRValue, OrigConstrainedParm->getLocation());
1331 if (!Ref)
1332 return true;
1333 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1335 TL.getNamedConcept(),
1336 /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1337 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1338 [&](TemplateArgumentListInfo &ConstraintArgs) {
1339 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1340 ConstraintArgs.addArgument(TL.getArgLoc(I));
1341 },
1342 EllipsisLoc);
1343 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1344 !ImmediatelyDeclaredConstraint.isUsable())
1345 return true;
1346
1347 NewConstrainedParm->setPlaceholderTypeConstraint(
1348 ImmediatelyDeclaredConstraint.get());
1349 return false;
1350}
1351
1353 SourceLocation Loc) {
1354 if (TSI->getType()->isUndeducedType()) {
1355 // C++17 [temp.dep.expr]p3:
1356 // An id-expression is type-dependent if it contains
1357 // - an identifier associated by name lookup with a non-type
1358 // template-parameter declared with a type that contains a
1359 // placeholder type (7.1.7.4),
1361 if (!NewTSI)
1362 return QualType();
1363 TSI = NewTSI;
1364 }
1365
1366 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1367}
1368
1370 if (T->isDependentType())
1371 return false;
1372
1373 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1374 return true;
1375
1376 if (T->isStructuralType())
1377 return false;
1378
1379 // Structural types are required to be object types or lvalue references.
1380 if (T->isRValueReferenceType()) {
1381 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1382 return true;
1383 }
1384
1385 // Don't mention structural types in our diagnostic prior to C++20. Also,
1386 // there's not much more we can say about non-scalar non-class types --
1387 // because we can't see functions or arrays here, those can only be language
1388 // extensions.
1389 if (!getLangOpts().CPlusPlus20 ||
1390 (!T->isScalarType() && !T->isRecordType())) {
1391 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1392 return true;
1393 }
1394
1395 // Structural types are required to be literal types.
1396 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1397 return true;
1398
1399 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1400
1401 // Drill down into the reason why the class is non-structural.
1402 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1403 // All members are required to be public and non-mutable, and can't be of
1404 // rvalue reference type. Check these conditions first to prefer a "local"
1405 // reason over a more distant one.
1406 for (const FieldDecl *FD : RD->fields()) {
1407 if (FD->getAccess() != AS_public) {
1408 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1409 return true;
1410 }
1411 if (FD->isMutable()) {
1412 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1413 return true;
1414 }
1415 if (FD->getType()->isRValueReferenceType()) {
1416 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1417 << T;
1418 return true;
1419 }
1420 }
1421
1422 // All bases are required to be public.
1423 for (const auto &BaseSpec : RD->bases()) {
1424 if (BaseSpec.getAccessSpecifier() != AS_public) {
1425 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1426 << T << 1;
1427 return true;
1428 }
1429 }
1430
1431 // All subobjects are required to be of structural types.
1432 SourceLocation SubLoc;
1433 QualType SubType;
1434 int Kind = -1;
1435
1436 for (const FieldDecl *FD : RD->fields()) {
1437 QualType T = Context.getBaseElementType(FD->getType());
1438 if (!T->isStructuralType()) {
1439 SubLoc = FD->getLocation();
1440 SubType = T;
1441 Kind = 0;
1442 break;
1443 }
1444 }
1445
1446 if (Kind == -1) {
1447 for (const auto &BaseSpec : RD->bases()) {
1448 QualType T = BaseSpec.getType();
1449 if (!T->isStructuralType()) {
1450 SubLoc = BaseSpec.getBaseTypeLoc();
1451 SubType = T;
1452 Kind = 1;
1453 break;
1454 }
1455 }
1456 }
1457
1458 assert(Kind != -1 && "couldn't find reason why type is not structural");
1459 Diag(SubLoc, diag::note_not_structural_subobject)
1460 << T << Kind << SubType;
1461 T = SubType;
1462 RD = T->getAsCXXRecordDecl();
1463 }
1464
1465 return true;
1466}
1467
1469 SourceLocation Loc) {
1470 // We don't allow variably-modified types as the type of non-type template
1471 // parameters.
1472 if (T->isVariablyModifiedType()) {
1473 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1474 << T;
1475 return QualType();
1476 }
1477
1478 if (T->isBlockPointerType()) {
1479 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1480 return QualType();
1481 }
1482
1483 // C++ [temp.param]p4:
1484 //
1485 // A non-type template-parameter shall have one of the following
1486 // (optionally cv-qualified) types:
1487 //
1488 // -- integral or enumeration type,
1489 if (T->isIntegralOrEnumerationType() ||
1490 // -- pointer to object or pointer to function,
1491 T->isPointerType() ||
1492 // -- lvalue reference to object or lvalue reference to function,
1493 T->isLValueReferenceType() ||
1494 // -- pointer to member,
1495 T->isMemberPointerType() ||
1496 // -- std::nullptr_t, or
1497 T->isNullPtrType() ||
1498 // -- a type that contains a placeholder type.
1499 T->isUndeducedType()) {
1500 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1501 // are ignored when determining its type.
1502 return T.getUnqualifiedType();
1503 }
1504
1505 // C++ [temp.param]p8:
1506 //
1507 // A non-type template-parameter of type "array of T" or
1508 // "function returning T" is adjusted to be of type "pointer to
1509 // T" or "pointer to function returning T", respectively.
1510 if (T->isArrayType() || T->isFunctionType())
1511 return Context.getDecayedType(T);
1512
1513 // If T is a dependent type, we can't do the check now, so we
1514 // assume that it is well-formed. Note that stripping off the
1515 // qualifiers here is not really correct if T turns out to be
1516 // an array type, but we'll recompute the type everywhere it's
1517 // used during instantiation, so that should be OK. (Using the
1518 // qualified type is equally wrong.)
1519 if (T->isDependentType())
1520 return T.getUnqualifiedType();
1521
1522 // C++20 [temp.param]p6:
1523 // -- a structural type
1524 if (RequireStructuralType(T, Loc))
1525 return QualType();
1526
1527 if (!getLangOpts().CPlusPlus20) {
1528 // FIXME: Consider allowing structural types as an extension in C++17. (In
1529 // earlier language modes, the template argument evaluation rules are too
1530 // inflexible.)
1531 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1532 return QualType();
1533 }
1534
1535 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1536 return T.getUnqualifiedType();
1537}
1538
1540 unsigned Depth,
1541 unsigned Position,
1542 SourceLocation EqualLoc,
1543 Expr *Default) {
1545
1546 // Check that we have valid decl-specifiers specified.
1547 auto CheckValidDeclSpecifiers = [this, &D] {
1548 // C++ [temp.param]
1549 // p1
1550 // template-parameter:
1551 // ...
1552 // parameter-declaration
1553 // p2
1554 // ... A storage class shall not be specified in a template-parameter
1555 // declaration.
1556 // [dcl.typedef]p1:
1557 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1558 // of a parameter-declaration
1559 const DeclSpec &DS = D.getDeclSpec();
1560 auto EmitDiag = [this](SourceLocation Loc) {
1561 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1563 };
1565 EmitDiag(DS.getStorageClassSpecLoc());
1566
1568 EmitDiag(DS.getThreadStorageClassSpecLoc());
1569
1570 // [dcl.inline]p1:
1571 // The inline specifier can be applied only to the declaration or
1572 // definition of a variable or function.
1573
1574 if (DS.isInlineSpecified())
1575 EmitDiag(DS.getInlineSpecLoc());
1576
1577 // [dcl.constexpr]p1:
1578 // The constexpr specifier shall be applied only to the definition of a
1579 // variable or variable template or the declaration of a function or
1580 // function template.
1581
1582 if (DS.hasConstexprSpecifier())
1583 EmitDiag(DS.getConstexprSpecLoc());
1584
1585 // [dcl.fct.spec]p1:
1586 // Function-specifiers can be used only in function declarations.
1587
1588 if (DS.isVirtualSpecified())
1589 EmitDiag(DS.getVirtualSpecLoc());
1590
1591 if (DS.hasExplicitSpecifier())
1592 EmitDiag(DS.getExplicitSpecLoc());
1593
1594 if (DS.isNoreturnSpecified())
1595 EmitDiag(DS.getNoreturnSpecLoc());
1596 };
1597
1598 CheckValidDeclSpecifiers();
1599
1600 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1601 if (isa<AutoType>(T))
1603 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1604 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1605
1606 assert(S->isTemplateParamScope() &&
1607 "Non-type template parameter not in template parameter scope!");
1608 bool Invalid = false;
1609
1611 if (T.isNull()) {
1612 T = Context.IntTy; // Recover with an 'int' type.
1613 Invalid = true;
1614 }
1615
1617
1618 const IdentifierInfo *ParamName = D.getIdentifier();
1619 bool IsParameterPack = D.hasEllipsis();
1621 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1622 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1623 TInfo);
1624 Param->setAccess(AS_public);
1625
1627 if (TL.isConstrained()) {
1628 if (D.getEllipsisLoc().isInvalid() &&
1629 T->containsUnexpandedParameterPack()) {
1630 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1631 for (auto &Loc :
1632 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1635 }
1636 if (!Invalid &&
1637 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1638 Invalid = true;
1639 }
1640
1641 if (Invalid)
1642 Param->setInvalidDecl();
1643
1644 if (Param->isParameterPack())
1645 if (auto *CSI = getEnclosingLambdaOrBlock())
1646 CSI->LocalPacks.push_back(Param);
1647
1648 if (ParamName) {
1650 ParamName);
1651
1652 // Add the template parameter into the current scope.
1653 S->AddDecl(Param);
1654 IdResolver.AddDecl(Param);
1655 }
1656
1657 // C++0x [temp.param]p9:
1658 // A default template-argument may be specified for any kind of
1659 // template-parameter that is not a template parameter pack.
1660 if (Default && IsParameterPack) {
1661 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1662 Default = nullptr;
1663 }
1664
1665 // Check the well-formedness of the default template argument, if provided.
1666 if (Default) {
1667 // Check for unexpanded parameter packs.
1669 return Param;
1670
1671 Param->setDefaultArgument(
1673 TemplateArgument(Default, /*IsCanonical=*/false),
1674 QualType(), SourceLocation()));
1675 }
1676
1677 return Param;
1678}
1679
1680/// ActOnTemplateTemplateParameter - Called when a C++ template template
1681/// parameter (e.g. T in template <template <typename> class T> class array)
1682/// has been parsed. S is the current scope.
1684 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1685 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1686 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1687 unsigned Position, SourceLocation EqualLoc,
1689 assert(S->isTemplateParamScope() &&
1690 "Template template parameter not in template parameter scope!");
1691
1692 bool IsParameterPack = EllipsisLoc.isValid();
1693
1694 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1695 if (Params->size() == 0) {
1696 Diag(Loc, diag::err_template_template_parm_no_parms)
1697 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1698
1699 // Recover as if there was a type template parameter pack.
1700 SmallVector<NamedDecl *, 4> ParamDecls;
1701 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1702 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1703 Depth + 1, 0, /*Id=*/nullptr,
1704 /*Typename=*/false, /*ParameterPack=*/true));
1706 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1707 Params->getRAngleLoc(), Params->getRequiresClause());
1708 }
1709
1710 bool Invalid = false;
1712 Params,
1713 /*OldParams=*/nullptr,
1714 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1715 Invalid = true;
1716
1717 // Construct the parameter object.
1719 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1720 IsParameterPack, Name, Kind, Typename, Params);
1721 Param->setAccess(AS_public);
1722
1723 if (Param->isParameterPack())
1724 if (auto *LSI = getEnclosingLambdaOrBlock())
1725 LSI->LocalPacks.push_back(Param);
1726
1727 // If the template template parameter has a name, then link the identifier
1728 // into the scope and lookup mechanisms.
1729 if (Name) {
1730 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1731
1732 S->AddDecl(Param);
1733 IdResolver.AddDecl(Param);
1734 }
1735
1736 if (Invalid)
1737 Param->setInvalidDecl();
1738
1739 // C++0x [temp.param]p9:
1740 // A default template-argument may be specified for any kind of
1741 // template-parameter that is not a template parameter pack.
1742 if (IsParameterPack && !Default.isInvalid()) {
1743 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1745 }
1746
1747 if (!Default.isInvalid()) {
1748 // Check only that we have a template template argument. We don't want to
1749 // try to check well-formedness now, because our template template parameter
1750 // might have dependent types in its template parameters, which we wouldn't
1751 // be able to match now.
1752 //
1753 // If none of the template template parameter's template arguments mention
1754 // other template parameters, we could actually perform more checking here.
1755 // However, it isn't worth doing.
1757 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1758 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1759 << DefaultArg.getSourceRange();
1760 return Param;
1761 }
1762
1763 TemplateName Name =
1766 if (Template &&
1768 return Param;
1769 }
1770
1771 // Check for unexpanded parameter packs.
1773 DefaultArg.getArgument().getAsTemplate(),
1775 return Param;
1776
1777 Param->setDefaultArgument(Context, DefaultArg);
1778 }
1779
1780 return Param;
1781}
1782
1783namespace {
1784class ConstraintRefersToContainingTemplateChecker
1786 using inherited = ConstDynamicRecursiveASTVisitor;
1787 bool Result = false;
1788 const FunctionDecl *Friend = nullptr;
1789 unsigned TemplateDepth = 0;
1790
1791 // Check a record-decl that we've seen to see if it is a lexical parent of the
1792 // Friend, likely because it was referred to without its template arguments.
1793 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1794 CheckingRD = CheckingRD->getMostRecentDecl();
1795 if (!CheckingRD->isTemplated())
1796 return true;
1797
1798 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1799 DC && !DC->isFileContext(); DC = DC->getParent())
1800 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1801 if (CheckingRD == RD->getMostRecentDecl()) {
1802 Result = true;
1803 return false;
1804 }
1805
1806 return true;
1807 }
1808
1809 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1810 if (D->getDepth() < TemplateDepth)
1811 Result = true;
1812
1813 // Necessary because the type of the NTTP might be what refers to the parent
1814 // constriant.
1815 return TraverseType(D->getType());
1816 }
1817
1818public:
1819 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1820 unsigned TemplateDepth)
1821 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1822
1823 bool getResult() const { return Result; }
1824
1825 // This should be the only template parm type that we have to deal with.
1826 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1827 // FunctionParmPackExpr are all partially substituted, which cannot happen
1828 // with concepts at this point in translation.
1829 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1830 if (Type->getDecl()->getDepth() < TemplateDepth) {
1831 Result = true;
1832 return false;
1833 }
1834 return true;
1835 }
1836
1837 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1838 return TraverseDecl(E->getDecl());
1839 }
1840
1841 bool TraverseTypedefType(const TypedefType *TT,
1842 bool /*TraverseQualifier*/) override {
1843 return TraverseType(TT->desugar());
1844 }
1845
1846 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1847 // We don't care about TypeLocs. So traverse Types instead.
1848 return TraverseType(TL.getType(), TraverseQualifier);
1849 }
1850
1851 bool VisitTagType(const TagType *T) override {
1852 return TraverseDecl(T->getDecl());
1853 }
1854
1855 bool TraverseDecl(const Decl *D) override {
1856 assert(D);
1857 // FIXME : This is possibly an incomplete list, but it is unclear what other
1858 // Decl kinds could be used to refer to the template parameters. This is a
1859 // best guess so far based on examples currently available, but the
1860 // unreachable should catch future instances/cases.
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1862 return TraverseType(TD->getUnderlyingType());
1863 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1864 return CheckNonTypeTemplateParmDecl(NTTPD);
1865 if (auto *VD = dyn_cast<ValueDecl>(D))
1866 return TraverseType(VD->getType());
1867 if (isa<TemplateDecl>(D))
1868 return true;
1869 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1870 return CheckIfContainingRecord(RD);
1871
1873 // No direct types to visit here I believe.
1874 } else
1875 llvm_unreachable("Don't know how to handle this declaration type yet");
1876 return true;
1877 }
1878};
1879} // namespace
1880
1882 const FunctionDecl *Friend, unsigned TemplateDepth,
1883 const Expr *Constraint) {
1884 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1885 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1886 Checker.TraverseStmt(Constraint);
1887 return Checker.getResult();
1888}
1889
1892 SourceLocation ExportLoc,
1893 SourceLocation TemplateLoc,
1894 SourceLocation LAngleLoc,
1895 ArrayRef<NamedDecl *> Params,
1896 SourceLocation RAngleLoc,
1897 Expr *RequiresClause) {
1898 if (ExportLoc.isValid())
1899 Diag(ExportLoc, diag::warn_template_export_unsupported);
1900
1901 for (NamedDecl *P : Params)
1903
1904 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1905 llvm::ArrayRef(Params), RAngleLoc,
1906 RequiresClause);
1907}
1908
1910 const CXXScopeSpec &SS) {
1911 if (SS.isSet())
1912 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1913}
1914
1915// Returns the template parameter list with all default template argument
1916// information.
1918 // Make sure we get the template parameter list from the most
1919 // recent declaration, since that is the only one that is guaranteed to
1920 // have all the default template argument information.
1921 Decl *D = TD->getMostRecentDecl();
1922 // C++11 N3337 [temp.param]p12:
1923 // A default template argument shall not be specified in a friend class
1924 // template declaration.
1925 //
1926 // Skip past friend *declarations* because they are not supposed to contain
1927 // default template arguments. Moreover, these declarations may introduce
1928 // template parameters living in different template depths than the
1929 // corresponding template parameters in TD, causing unmatched constraint
1930 // substitution.
1931 //
1932 // FIXME: Diagnose such cases within a class template:
1933 // template <class T>
1934 // struct S {
1935 // template <class = void> friend struct C;
1936 // };
1937 // template struct S<int>;
1939 D->getPreviousDecl())
1940 D = D->getPreviousDecl();
1941 return cast<TemplateDecl>(D)->getTemplateParameters();
1942}
1943
1945 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1946 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1947 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1948 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1949 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1950 TemplateParameterList **OuterTemplateParamLists,
1951 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1952 assert(TemplateParams && TemplateParams->size() > 0 &&
1953 "No template parameters");
1954 assert(TUK != TagUseKind::Reference &&
1955 "Can only declare or define class templates");
1956 bool Invalid = false;
1957
1958 // Check that we can declare a template here.
1959 if (CheckTemplateDeclScope(S, TemplateParams))
1960 return true;
1961
1963 assert(Kind != TagTypeKind::Enum &&
1964 "can't build template of enumerated type");
1965
1966 // There is no such thing as an unnamed class template.
1967 if (!Name) {
1968 Diag(KWLoc, diag::err_template_unnamed_class);
1969 return true;
1970 }
1971
1972 // Find any previous declaration with this name. For a friend with no
1973 // scope explicitly specified, we only look for tag declarations (per
1974 // C++11 [basic.lookup.elab]p2).
1975 DeclContext *SemanticContext;
1976 LookupResult Previous(*this, Name, NameLoc,
1977 (SS.isEmpty() && TUK == TagUseKind::Friend)
1981 if (SS.isNotEmpty() && !SS.isInvalid()) {
1982 SemanticContext = computeDeclContext(SS, true);
1983 if (!SemanticContext) {
1984 Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
1985 << SS.getScopeRep() << SS.getRange();
1986 return true;
1987 }
1988
1989 if (RequireCompleteDeclContext(SS, SemanticContext))
1990 return true;
1991
1992 // If we're adding a template to a dependent context, we may need to
1993 // rebuilding some of the types used within the template parameter list,
1994 // now that we know what the current instantiation is.
1995 if (SemanticContext->isDependentContext()) {
1996 ContextRAII SavedContext(*this, SemanticContext);
1998 Invalid = true;
1999 }
2000
2001 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2002 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2003 /*TemplateId=*/nullptr,
2004 IsMemberSpecialization))
2005 return true;
2006
2007 LookupQualifiedName(Previous, SemanticContext);
2008 } else {
2009 SemanticContext = CurContext;
2010
2011 // C++14 [class.mem]p14:
2012 // If T is the name of a class, then each of the following shall have a
2013 // name different from T:
2014 // -- every member template of class T
2015 if (TUK != TagUseKind::Friend &&
2016 DiagnoseClassNameShadow(SemanticContext,
2017 DeclarationNameInfo(Name, NameLoc)))
2018 return true;
2019
2020 LookupName(Previous, S);
2021 }
2022
2023 if (Previous.isAmbiguous())
2024 return true;
2025
2026 // Let the template parameter scope enter the lookup chain of the current
2027 // class template. For example, given
2028 //
2029 // namespace ns {
2030 // template <class> bool Param = false;
2031 // template <class T> struct N;
2032 // }
2033 //
2034 // template <class Param> struct ns::N { void foo(Param); };
2035 //
2036 // When we reference Param inside the function parameter list, our name lookup
2037 // chain for it should be like:
2038 // FunctionScope foo
2039 // -> RecordScope N
2040 // -> TemplateParamScope (where we will find Param)
2041 // -> NamespaceScope ns
2042 //
2043 // See also CppLookupName().
2044 if (S->isTemplateParamScope())
2045 EnterTemplatedContext(S, SemanticContext);
2046
2047 NamedDecl *PrevDecl = nullptr;
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050
2051 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2052 // Maybe we will complain about the shadowed template parameter.
2053 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2054 // Just pretend that we didn't see the previous declaration.
2055 PrevDecl = nullptr;
2056 }
2057
2058 // If there is a previous declaration with the same name, check
2059 // whether this is a valid redeclaration.
2060 ClassTemplateDecl *PrevClassTemplate =
2061 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2062
2063 // We may have found the injected-class-name of a class template,
2064 // class template partial specialization, or class template specialization.
2065 // In these cases, grab the template that is being defined or specialized.
2066 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2067 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2068 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2069 PrevClassTemplate
2070 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2071 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2072 PrevClassTemplate
2074 ->getSpecializedTemplate();
2075 }
2076 }
2077
2078 if (TUK == TagUseKind::Friend) {
2079 // C++ [namespace.memdef]p3:
2080 // [...] When looking for a prior declaration of a class or a function
2081 // declared as a friend, and when the name of the friend class or
2082 // function is neither a qualified name nor a template-id, scopes outside
2083 // the innermost enclosing namespace scope are not considered.
2084 if (!SS.isSet()) {
2085 DeclContext *OutermostContext = CurContext;
2086 while (!OutermostContext->isFileContext())
2087 OutermostContext = OutermostContext->getLookupParent();
2088
2089 if (PrevDecl &&
2090 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2091 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2092 SemanticContext = PrevDecl->getDeclContext();
2093 } else {
2094 // Declarations in outer scopes don't matter. However, the outermost
2095 // context we computed is the semantic context for our new
2096 // declaration.
2097 PrevDecl = PrevClassTemplate = nullptr;
2098 SemanticContext = OutermostContext;
2099
2100 // Check that the chosen semantic context doesn't already contain a
2101 // declaration of this name as a non-tag type.
2103 DeclContext *LookupContext = SemanticContext;
2104 while (LookupContext->isTransparentContext())
2105 LookupContext = LookupContext->getLookupParent();
2106 LookupQualifiedName(Previous, LookupContext);
2107
2108 if (Previous.isAmbiguous())
2109 return true;
2110
2111 if (Previous.begin() != Previous.end())
2112 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2113 }
2114 }
2115 } else if (PrevDecl &&
2116 !isTagRedeclarationInScope(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, NameLoc, &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(NewTemplate, PrevClassTemplate);
2294 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2295 }
2296
2300
2301 if (TUK != TagUseKind::Friend) {
2302 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2303 Scope *Outer = S;
2304 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2305 Outer = Outer->getParent();
2306 PushOnScopeChains(NewTemplate, Outer);
2307 } else {
2308 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2309 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2310 NewClass->setAccess(PrevClassTemplate->getAccess());
2311 }
2312
2313 NewTemplate->setObjectOfFriendDecl();
2314
2315 // Friend templates are visible in fairly strange ways.
2316 if (!CurContext->isDependentContext()) {
2317 DeclContext *DC = SemanticContext->getRedeclContext();
2318 DC->makeDeclVisibleInContext(NewTemplate);
2319 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2320 PushOnScopeChains(NewTemplate, EnclosingScope,
2321 /* AddToContext = */ false);
2322 }
2323
2325 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2326 Friend->setAccess(AS_public);
2327 CurContext->addDecl(Friend);
2328 }
2329
2330 if (PrevClassTemplate)
2331 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2332
2333 if (Invalid) {
2334 NewTemplate->setInvalidDecl();
2335 NewClass->setInvalidDecl();
2336 }
2337
2338 ActOnDocumentableDecl(NewTemplate);
2339
2340 if (SkipBody && SkipBody->ShouldSkip)
2341 return SkipBody->Previous;
2342
2343 return NewTemplate;
2344}
2345
2346/// Diagnose the presence of a default template argument on a
2347/// template parameter, which is ill-formed in certain contexts.
2348///
2349/// \returns true if the default template argument should be dropped.
2352 SourceLocation ParamLoc,
2353 SourceRange DefArgRange) {
2354 switch (TPC) {
2355 case Sema::TPC_Other:
2357 return false;
2358
2361 // C++ [temp.param]p9:
2362 // A default template-argument shall not be specified in a
2363 // function template declaration or a function template
2364 // definition [...]
2365 // If a friend function template declaration specifies a default
2366 // template-argument, that declaration shall be a definition and shall be
2367 // the only declaration of the function template in the translation unit.
2368 // (C++98/03 doesn't have this wording; see DR226).
2369 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2370 << DefArgRange;
2371 return false;
2372
2374 // C++0x [temp.param]p9:
2375 // A default template-argument shall not be specified in the
2376 // template-parameter-lists of the definition of a member of a
2377 // class template that appears outside of the member's class.
2378 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2379 << DefArgRange;
2380 return true;
2381
2384 // C++ [temp.param]p9:
2385 // A default template-argument shall not be specified in a
2386 // friend template declaration.
2387 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2388 << DefArgRange;
2389 return true;
2390
2391 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2392 // for friend function templates if there is only a single
2393 // declaration (and it is a definition). Strange!
2394 }
2395
2396 llvm_unreachable("Invalid TemplateParamListContext!");
2397}
2398
2399/// Check for unexpanded parameter packs within the template parameters
2400/// of a template template parameter, recursively.
2403 // A template template parameter which is a parameter pack is also a pack
2404 // expansion.
2405 if (TTP->isParameterPack())
2406 return false;
2407
2409 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2410 NamedDecl *P = Params->getParam(I);
2411 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2412 if (!TTP->isParameterPack())
2413 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2414 if (TC->hasExplicitTemplateArgs())
2415 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2418 return true;
2419 continue;
2420 }
2421
2422 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2423 if (!NTTP->isParameterPack() &&
2424 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2425 NTTP->getTypeSourceInfo(),
2427 return true;
2428
2429 continue;
2430 }
2431
2432 if (TemplateTemplateParmDecl *InnerTTP
2433 = dyn_cast<TemplateTemplateParmDecl>(P))
2434 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2435 return true;
2436 }
2437
2438 return false;
2439}
2440
2442 TemplateParameterList *OldParams,
2444 SkipBodyInfo *SkipBody) {
2445 bool Invalid = false;
2446
2447 // C++ [temp.param]p10:
2448 // The set of default template-arguments available for use with a
2449 // template declaration or definition is obtained by merging the
2450 // default arguments from the definition (if in scope) and all
2451 // declarations in scope in the same way default function
2452 // arguments are (8.3.6).
2453 bool SawDefaultArgument = false;
2454 SourceLocation PreviousDefaultArgLoc;
2455
2456 // Dummy initialization to avoid warnings.
2457 TemplateParameterList::iterator OldParam = NewParams->end();
2458 if (OldParams)
2459 OldParam = OldParams->begin();
2460
2461 bool RemoveDefaultArguments = false;
2462 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2463 NewParamEnd = NewParams->end();
2464 NewParam != NewParamEnd; ++NewParam) {
2465 // Whether we've seen a duplicate default argument in the same translation
2466 // unit.
2467 bool RedundantDefaultArg = false;
2468 // Whether we've found inconsis inconsitent default arguments in different
2469 // translation unit.
2470 bool InconsistentDefaultArg = false;
2471 // The name of the module which contains the inconsistent default argument.
2472 std::string PrevModuleName;
2473
2474 SourceLocation OldDefaultLoc;
2475 SourceLocation NewDefaultLoc;
2476
2477 // Variable used to diagnose missing default arguments
2478 bool MissingDefaultArg = false;
2479
2480 // Variable used to diagnose non-final parameter packs
2481 bool SawParameterPack = false;
2482
2483 if (TemplateTypeParmDecl *NewTypeParm
2484 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2485 // Check the presence of a default argument here.
2486 if (NewTypeParm->hasDefaultArgument() &&
2488 *this, TPC, NewTypeParm->getLocation(),
2489 NewTypeParm->getDefaultArgument().getSourceRange()))
2490 NewTypeParm->removeDefaultArgument();
2491
2492 // Merge default arguments for template type parameters.
2493 TemplateTypeParmDecl *OldTypeParm
2494 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2495 if (NewTypeParm->isParameterPack()) {
2496 assert(!NewTypeParm->hasDefaultArgument() &&
2497 "Parameter packs can't have a default argument!");
2498 SawParameterPack = true;
2499 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2500 NewTypeParm->hasDefaultArgument() &&
2501 (!SkipBody || !SkipBody->ShouldSkip)) {
2502 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2503 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2504 SawDefaultArgument = true;
2505
2506 if (!OldTypeParm->getOwningModule())
2507 RedundantDefaultArg = true;
2508 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2509 NewTypeParm)) {
2510 InconsistentDefaultArg = true;
2511 PrevModuleName =
2513 }
2514 PreviousDefaultArgLoc = NewDefaultLoc;
2515 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2516 // Merge the default argument from the old declaration to the
2517 // new declaration.
2518 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2519 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2520 } else if (NewTypeParm->hasDefaultArgument()) {
2521 SawDefaultArgument = true;
2522 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2523 } else if (SawDefaultArgument)
2524 MissingDefaultArg = true;
2525 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2526 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2527 // Check for unexpanded parameter packs, except in a template template
2528 // parameter pack, as in those any unexpanded packs should be expanded
2529 // along with the parameter itself.
2531 !NewNonTypeParm->isParameterPack() &&
2532 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2533 NewNonTypeParm->getTypeSourceInfo(),
2535 Invalid = true;
2536 continue;
2537 }
2538
2539 // Check the presence of a default argument here.
2540 if (NewNonTypeParm->hasDefaultArgument() &&
2542 *this, TPC, NewNonTypeParm->getLocation(),
2543 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2544 NewNonTypeParm->removeDefaultArgument();
2545 }
2546
2547 // Merge default arguments for non-type template parameters
2548 NonTypeTemplateParmDecl *OldNonTypeParm
2549 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2550 if (NewNonTypeParm->isParameterPack()) {
2551 assert(!NewNonTypeParm->hasDefaultArgument() &&
2552 "Parameter packs can't have a default argument!");
2553 if (!NewNonTypeParm->isPackExpansion())
2554 SawParameterPack = true;
2555 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2556 NewNonTypeParm->hasDefaultArgument() &&
2557 (!SkipBody || !SkipBody->ShouldSkip)) {
2558 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2559 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2560 SawDefaultArgument = true;
2561 if (!OldNonTypeParm->getOwningModule())
2562 RedundantDefaultArg = true;
2563 else if (!getASTContext().isSameDefaultTemplateArgument(
2564 OldNonTypeParm, NewNonTypeParm)) {
2565 InconsistentDefaultArg = true;
2566 PrevModuleName =
2567 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2568 }
2569 PreviousDefaultArgLoc = NewDefaultLoc;
2570 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2571 // Merge the default argument from the old declaration to the
2572 // new declaration.
2573 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2574 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2575 } else if (NewNonTypeParm->hasDefaultArgument()) {
2576 SawDefaultArgument = true;
2577 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2578 } else if (SawDefaultArgument)
2579 MissingDefaultArg = true;
2580 } else {
2581 TemplateTemplateParmDecl *NewTemplateParm
2582 = cast<TemplateTemplateParmDecl>(*NewParam);
2583
2584 // Check for unexpanded parameter packs, recursively.
2585 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2586 Invalid = true;
2587 continue;
2588 }
2589
2590 // Check the presence of a default argument here.
2591 if (NewTemplateParm->hasDefaultArgument() &&
2593 NewTemplateParm->getLocation(),
2594 NewTemplateParm->getDefaultArgument().getSourceRange()))
2595 NewTemplateParm->removeDefaultArgument();
2596
2597 // Merge default arguments for template template parameters
2598 TemplateTemplateParmDecl *OldTemplateParm
2599 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2600 if (NewTemplateParm->isParameterPack()) {
2601 assert(!NewTemplateParm->hasDefaultArgument() &&
2602 "Parameter packs can't have a default argument!");
2603 if (!NewTemplateParm->isPackExpansion())
2604 SawParameterPack = true;
2605 } else if (OldTemplateParm &&
2606 hasVisibleDefaultArgument(OldTemplateParm) &&
2607 NewTemplateParm->hasDefaultArgument() &&
2608 (!SkipBody || !SkipBody->ShouldSkip)) {
2609 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2610 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2611 SawDefaultArgument = true;
2612 if (!OldTemplateParm->getOwningModule())
2613 RedundantDefaultArg = true;
2614 else if (!getASTContext().isSameDefaultTemplateArgument(
2615 OldTemplateParm, NewTemplateParm)) {
2616 InconsistentDefaultArg = true;
2617 PrevModuleName =
2618 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2619 }
2620 PreviousDefaultArgLoc = NewDefaultLoc;
2621 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2622 // Merge the default argument from the old declaration to the
2623 // new declaration.
2624 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2625 PreviousDefaultArgLoc
2626 = OldTemplateParm->getDefaultArgument().getLocation();
2627 } else if (NewTemplateParm->hasDefaultArgument()) {
2628 SawDefaultArgument = true;
2629 PreviousDefaultArgLoc
2630 = NewTemplateParm->getDefaultArgument().getLocation();
2631 } else if (SawDefaultArgument)
2632 MissingDefaultArg = true;
2633 }
2634
2635 // C++11 [temp.param]p11:
2636 // If a template parameter of a primary class template or alias template
2637 // is a template parameter pack, it shall be the last template parameter.
2638 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2639 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2640 Diag((*NewParam)->getLocation(),
2641 diag::err_template_param_pack_must_be_last_template_parameter);
2642 Invalid = true;
2643 }
2644
2645 // [basic.def.odr]/13:
2646 // There can be more than one definition of a
2647 // ...
2648 // default template argument
2649 // ...
2650 // in a program provided that each definition appears in a different
2651 // translation unit and the definitions satisfy the [same-meaning
2652 // criteria of the ODR].
2653 //
2654 // Simply, the design of modules allows the definition of template default
2655 // argument to be repeated across translation unit. Note that the ODR is
2656 // checked elsewhere. But it is still not allowed to repeat template default
2657 // argument in the same translation unit.
2658 if (RedundantDefaultArg) {
2659 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2660 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2661 Invalid = true;
2662 } else if (InconsistentDefaultArg) {
2663 // We could only diagnose about the case that the OldParam is imported.
2664 // The case NewParam is imported should be handled in ASTReader.
2665 Diag(NewDefaultLoc,
2666 diag::err_template_param_default_arg_inconsistent_redefinition);
2667 Diag(OldDefaultLoc,
2668 diag::note_template_param_prev_default_arg_in_other_module)
2669 << PrevModuleName;
2670 Invalid = true;
2671 } else if (MissingDefaultArg &&
2672 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2673 TPC == TPC_FriendClassTemplate)) {
2674 // C++ 23[temp.param]p14:
2675 // If a template-parameter of a class template, variable template, or
2676 // alias template has a default template argument, each subsequent
2677 // template-parameter shall either have a default template argument
2678 // supplied or be a template parameter pack.
2679 Diag((*NewParam)->getLocation(),
2680 diag::err_template_param_default_arg_missing);
2681 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2682 Invalid = true;
2683 RemoveDefaultArguments = true;
2684 }
2685
2686 // If we have an old template parameter list that we're merging
2687 // in, move on to the next parameter.
2688 if (OldParams)
2689 ++OldParam;
2690 }
2691
2692 // We were missing some default arguments at the end of the list, so remove
2693 // all of the default arguments.
2694 if (RemoveDefaultArguments) {
2695 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2696 NewParamEnd = NewParams->end();
2697 NewParam != NewParamEnd; ++NewParam) {
2698 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2699 TTP->removeDefaultArgument();
2700 else if (NonTypeTemplateParmDecl *NTTP
2701 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2702 NTTP->removeDefaultArgument();
2703 else
2704 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2705 }
2706 }
2707
2708 return Invalid;
2709}
2710
2711namespace {
2712
2713/// A class which looks for a use of a certain level of template
2714/// parameter.
2715struct DependencyChecker : DynamicRecursiveASTVisitor {
2716 unsigned Depth;
2717
2718 // Whether we're looking for a use of a template parameter that makes the
2719 // overall construct type-dependent / a dependent type. This is strictly
2720 // best-effort for now; we may fail to match at all for a dependent type
2721 // in some cases if this is set.
2722 bool IgnoreNonTypeDependent;
2723
2724 bool Match;
2725 SourceLocation MatchLoc;
2726
2727 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2728 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2729 Match(false) {}
2730
2731 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2732 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2733 NamedDecl *ND = Params->getParam(0);
2734 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2735 Depth = PD->getDepth();
2736 } else if (NonTypeTemplateParmDecl *PD =
2737 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2738 Depth = PD->getDepth();
2739 } else {
2740 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2741 }
2742 }
2743
2744 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2745 if (ParmDepth >= Depth) {
2746 Match = true;
2747 MatchLoc = Loc;
2748 return true;
2749 }
2750 return false;
2751 }
2752
2753 bool TraverseStmt(Stmt *S) override {
2754 // Prune out non-type-dependent expressions if requested. This can
2755 // sometimes result in us failing to find a template parameter reference
2756 // (if a value-dependent expression creates a dependent type), but this
2757 // mode is best-effort only.
2758 if (auto *E = dyn_cast_or_null<Expr>(S))
2759 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2760 return true;
2762 }
2763
2764 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2765 if (IgnoreNonTypeDependent && !TL.isNull() &&
2766 !TL.getType()->isDependentType())
2767 return true;
2768 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2769 }
2770
2771 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2772 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2773 }
2774
2775 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2776 // For a best-effort search, keep looking until we find a location.
2777 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2778 }
2779
2780 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2781 if (TemplateTemplateParmDecl *PD =
2782 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2783 if (Matches(PD->getDepth()))
2784 return false;
2786 TraverseQualifier);
2787 }
2788
2789 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2790 if (NonTypeTemplateParmDecl *PD =
2791 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2792 if (Matches(PD->getDepth(), E->getExprLoc()))
2793 return false;
2794 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2795 }
2796
2797 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2798 if (Matches(E->getParameter()->getDepth(), E->getExprLoc()))
2799 return false;
2800 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(E);
2801 }
2802
2803 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2804 return TraverseType(T->getReplacementType());
2805 }
2806
2807 bool VisitSubstTemplateTypeParmPackType(
2808 SubstTemplateTypeParmPackType *T) override {
2809 return TraverseTemplateArgument(T->getArgumentPack());
2810 }
2811
2812 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2813 bool TraverseQualifier) override {
2814 // An InjectedClassNameType will never have a dependent template name,
2815 // so no need to traverse it.
2816 return TraverseTemplateArguments(
2817 T->getTemplateArgs(T->getDecl()->getASTContext()));
2818 }
2819};
2820} // end anonymous namespace
2821
2822/// Determines whether a given type depends on the given parameter
2823/// list.
2824static bool
2826 if (!Params->size())
2827 return false;
2828
2829 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2830 Checker.TraverseType(T);
2831 return Checker.Match;
2832}
2833
2834// Find the source range corresponding to the named type in the given
2835// nested-name-specifier, if any.
2837 QualType T,
2838 const CXXScopeSpec &SS) {
2840 for (;;) {
2843 break;
2844 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2845 return NNSLoc.castAsTypeLoc().getSourceRange();
2846 // FIXME: This will always be empty.
2847 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2848 }
2849
2850 return SourceRange();
2851}
2852
2854 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2855 TemplateIdAnnotation *TemplateId,
2856 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2857 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2858 IsMemberSpecialization = false;
2859 Invalid = false;
2860
2861 // The sequence of nested types to which we will match up the template
2862 // parameter lists. We first build this list by starting with the type named
2863 // by the nested-name-specifier and walking out until we run out of types.
2864 SmallVector<QualType, 4> NestedTypes;
2865 QualType T;
2866 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2867 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2868 if (CXXRecordDecl *Record =
2869 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2870 T = Context.getCanonicalTagType(Record);
2871 else
2872 T = QualType(Qualifier.getAsType(), 0);
2873 }
2874
2875 // If we found an explicit specialization that prevents us from needing
2876 // 'template<>' headers, this will be set to the location of that
2877 // explicit specialization.
2878 SourceLocation ExplicitSpecLoc;
2879
2880 while (!T.isNull()) {
2881 NestedTypes.push_back(T);
2882
2883 // Retrieve the parent of a record type.
2884 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2885 // If this type is an explicit specialization, we're done.
2887 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2889 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2890 ExplicitSpecLoc = Spec->getLocation();
2891 break;
2892 }
2893 } else if (Record->getTemplateSpecializationKind()
2895 ExplicitSpecLoc = Record->getLocation();
2896 break;
2897 }
2898
2899 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2900 T = Context.getTypeDeclType(Parent);
2901 else
2902 T = QualType();
2903 continue;
2904 }
2905
2906 if (const TemplateSpecializationType *TST
2907 = T->getAs<TemplateSpecializationType>()) {
2908 TemplateName Name = TST->getTemplateName();
2909 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2910 // Look one step prior in a dependent template specialization type.
2911 if (NestedNameSpecifier NNS = DTS->getQualifier();
2913 T = QualType(NNS.getAsType(), 0);
2914 else
2915 T = QualType();
2916 continue;
2917 }
2918 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2919 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2920 T = Context.getTypeDeclType(Parent);
2921 else
2922 T = QualType();
2923 continue;
2924 }
2925 }
2926
2927 // Look one step prior in a dependent name type.
2928 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2929 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2931 T = QualType(NNS.getAsType(), 0);
2932 else
2933 T = QualType();
2934 continue;
2935 }
2936
2937 // Retrieve the parent of an enumeration type.
2938 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2939 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2940 // check here.
2941 EnumDecl *Enum = EnumT->getDecl();
2942
2943 // Get to the parent type.
2944 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2945 T = Context.getCanonicalTypeDeclType(Parent);
2946 else
2947 T = QualType();
2948 continue;
2949 }
2950
2951 T = QualType();
2952 }
2953 // Reverse the nested types list, since we want to traverse from the outermost
2954 // to the innermost while checking template-parameter-lists.
2955 std::reverse(NestedTypes.begin(), NestedTypes.end());
2956
2957 // C++0x [temp.expl.spec]p17:
2958 // A member or a member template may be nested within many
2959 // enclosing class templates. In an explicit specialization for
2960 // such a member, the member declaration shall be preceded by a
2961 // template<> for each enclosing class template that is
2962 // explicitly specialized.
2963 bool SawNonEmptyTemplateParameterList = false;
2964
2965 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2966 if (SawNonEmptyTemplateParameterList) {
2967 if (!SuppressDiagnostic)
2968 Diag(DeclLoc, diag::err_specialize_member_of_template)
2969 << !Recovery << Range;
2970 Invalid = true;
2971 IsMemberSpecialization = false;
2972 return true;
2973 }
2974
2975 return false;
2976 };
2977
2978 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2979 // Check that we can have an explicit specialization here.
2980 if (CheckExplicitSpecialization(Range, true))
2981 return true;
2982
2983 // We don't have a template header, but we should.
2984 SourceLocation ExpectedTemplateLoc;
2985 if (!ParamLists.empty())
2986 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2987 else
2988 ExpectedTemplateLoc = DeclStartLoc;
2989
2990 if (!SuppressDiagnostic)
2991 Diag(DeclLoc, diag::err_template_spec_needs_header)
2992 << Range
2993 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2994 return false;
2995 };
2996
2997 unsigned ParamIdx = 0;
2998 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2999 ++TypeIdx) {
3000 T = NestedTypes[TypeIdx];
3001
3002 // Whether we expect a 'template<>' header.
3003 bool NeedEmptyTemplateHeader = false;
3004
3005 // Whether we expect a template header with parameters.
3006 bool NeedNonemptyTemplateHeader = false;
3007
3008 // For a dependent type, the set of template parameters that we
3009 // expect to see.
3010 TemplateParameterList *ExpectedTemplateParams = nullptr;
3011
3012 // C++0x [temp.expl.spec]p15:
3013 // A member or a member template may be nested within many enclosing
3014 // class templates. In an explicit specialization for such a member, the
3015 // member declaration shall be preceded by a template<> for each
3016 // enclosing class template that is explicitly specialized.
3017 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3019 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3020 ExpectedTemplateParams = Partial->getTemplateParameters();
3021 NeedNonemptyTemplateHeader = true;
3022 } else if (Record->isDependentType()) {
3023 if (Record->getDescribedClassTemplate()) {
3024 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3025 ->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 }
3028 } else if (ClassTemplateSpecializationDecl *Spec
3029 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3030 // C++0x [temp.expl.spec]p4:
3031 // Members of an explicitly specialized class template are defined
3032 // in the same manner as members of normal classes, and not using
3033 // the template<> syntax.
3034 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3035 NeedEmptyTemplateHeader = true;
3036 else
3037 continue;
3038 } else if (Record->getTemplateSpecializationKind()) {
3039 if (Record->getTemplateSpecializationKind()
3041 TypeIdx == NumTypes - 1)
3042 IsMemberSpecialization = true;
3043
3044 continue;
3045 }
3046 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3047 TemplateName Name = TST->getTemplateName();
3048 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3049 ExpectedTemplateParams = Template->getTemplateParameters();
3050 NeedNonemptyTemplateHeader = true;
3051 } else if (Name.getAsDependentTemplateName()) {
3052 NeedNonemptyTemplateHeader = true;
3053 } else if (Name.getAsDeducedTemplateName()) {
3054 // FIXME: We actually could/should check the template arguments here
3055 // against the corresponding template parameter list.
3056 NeedNonemptyTemplateHeader = false;
3057 }
3058 }
3059
3060 // C++ [temp.expl.spec]p16:
3061 // In an explicit specialization declaration for a member of a class
3062 // template or a member template that appears in namespace scope, the
3063 // member template and some of its enclosing class templates may remain
3064 // unspecialized, except that the declaration shall not explicitly
3065 // specialize a class member template if its enclosing class templates
3066 // are not explicitly specialized as well.
3067 if (ParamIdx < ParamLists.size()) {
3068 if (ParamLists[ParamIdx]->size() == 0) {
3069 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072 } else
3073 SawNonEmptyTemplateParameterList = true;
3074 }
3075
3076 if (NeedEmptyTemplateHeader) {
3077 // If we're on the last of the types, and we need a 'template<>' header
3078 // here, then it's a member specialization.
3079 if (TypeIdx == NumTypes - 1)
3080 IsMemberSpecialization = true;
3081
3082 if (ParamIdx < ParamLists.size()) {
3083 if (ParamLists[ParamIdx]->size() > 0) {
3084 // The header has template parameters when it shouldn't. Complain.
3085 if (!SuppressDiagnostic)
3086 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3087 diag::err_template_param_list_matches_nontemplate)
3088 << T
3089 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3090 ParamLists[ParamIdx]->getRAngleLoc())
3092 Invalid = true;
3093 return nullptr;
3094 }
3095
3096 // Consume this template header.
3097 ++ParamIdx;
3098 continue;
3099 }
3100
3101 if (!IsFriend)
3102 if (DiagnoseMissingExplicitSpecialization(
3104 return nullptr;
3105
3106 continue;
3107 }
3108
3109 if (NeedNonemptyTemplateHeader) {
3110 // In friend declarations we can have template-ids which don't
3111 // depend on the corresponding template parameter lists. But
3112 // assume that empty parameter lists are supposed to match this
3113 // template-id.
3114 if (IsFriend && T->isDependentType()) {
3115 if (ParamIdx < ParamLists.size() &&
3117 ExpectedTemplateParams = nullptr;
3118 else
3119 continue;
3120 }
3121
3122 if (ParamIdx < ParamLists.size()) {
3123 // Check the template parameter list, if we can.
3124 if (ExpectedTemplateParams &&
3126 ExpectedTemplateParams,
3127 !SuppressDiagnostic, TPL_TemplateMatch))
3128 Invalid = true;
3129
3130 if (!Invalid &&
3131 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3133 Invalid = true;
3134
3135 ++ParamIdx;
3136 continue;
3137 }
3138
3139 if (!SuppressDiagnostic)
3140 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3141 << T
3143 Invalid = true;
3144 continue;
3145 }
3146 }
3147
3148 // If there were at least as many template-ids as there were template
3149 // parameter lists, then there are no template parameter lists remaining for
3150 // the declaration itself.
3151 if (ParamIdx >= ParamLists.size()) {
3152 if (TemplateId && !IsFriend) {
3153 // We don't have a template header for the declaration itself, but we
3154 // should.
3155 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3156 TemplateId->RAngleLoc));
3157
3158 // Fabricate an empty template parameter list for the invented header.
3160 SourceLocation(), {},
3161 SourceLocation(), nullptr);
3162 }
3163
3164 return nullptr;
3165 }
3166
3167 // If there were too many template parameter lists, complain about that now.
3168 if (ParamIdx < ParamLists.size() - 1) {
3169 bool HasAnyExplicitSpecHeader = false;
3170 bool AllExplicitSpecHeaders = true;
3171 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3172 if (ParamLists[I]->size() == 0)
3173 HasAnyExplicitSpecHeader = true;
3174 else
3175 AllExplicitSpecHeaders = false;
3176 }
3177
3178 if (!SuppressDiagnostic)
3179 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3180 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3181 : diag::err_template_spec_extra_headers)
3182 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3183 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3184
3185 // If there was a specialization somewhere, such that 'template<>' is
3186 // not required, and there were any 'template<>' headers, note where the
3187 // specialization occurred.
3188 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3189 !SuppressDiagnostic)
3190 Diag(ExplicitSpecLoc,
3191 diag::note_explicit_template_spec_does_not_need_header)
3192 << NestedTypes.back();
3193
3194 // We have a template parameter list with no corresponding scope, which
3195 // means that the resulting template declaration can't be instantiated
3196 // properly (we'll end up with dependent nodes when we shouldn't).
3197 if (!AllExplicitSpecHeaders)
3198 Invalid = true;
3199 }
3200
3201 // C++ [temp.expl.spec]p16:
3202 // In an explicit specialization declaration for a member of a class
3203 // template or a member template that ap- pears in namespace scope, the
3204 // member template and some of its enclosing class templates may remain
3205 // unspecialized, except that the declaration shall not explicitly
3206 // specialize a class member template if its en- closing class templates
3207 // are not explicitly specialized as well.
3208 if (ParamLists.back()->size() == 0 &&
3209 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3210 false))
3211 return nullptr;
3212
3213 // Return the last template parameter list, which corresponds to the
3214 // entity being declared.
3215 return ParamLists.back();
3216}
3217
3219 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3220 Diag(Template->getLocation(), diag::note_template_declared_here)
3222 ? 0
3224 ? 1
3226 ? 2
3228 << Template->getDeclName();
3229 return;
3230 }
3231
3233 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3234 IEnd = OST->end();
3235 I != IEnd; ++I)
3236 Diag((*I)->getLocation(), diag::note_template_declared_here)
3237 << 0 << (*I)->getDeclName();
3238
3239 return;
3240 }
3241}
3242
3244 TemplateName BaseTemplate,
3245 SourceLocation TemplateLoc,
3247 auto lookUpCommonType = [&](TemplateArgument T1,
3248 TemplateArgument T2) -> QualType {
3249 // Don't bother looking for other specializations if both types are
3250 // builtins - users aren't allowed to specialize for them
3251 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3252 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3253 {T1, T2});
3254
3258 Args.addArgument(TemplateArgumentLoc(
3259 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3260
3261 EnterExpressionEvaluationContext UnevaluatedContext(
3263 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3265
3266 QualType BaseTemplateInst = S.CheckTemplateIdType(
3267 Keyword, BaseTemplate, TemplateLoc, Args,
3268 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3269
3270 if (SFINAE.hasErrorOccurred())
3271 return QualType();
3272
3273 return BaseTemplateInst;
3274 };
3275
3276 // Note A: For the common_type trait applied to a template parameter pack T of
3277 // types, the member type shall be either defined or not present as follows:
3278 switch (Ts.size()) {
3279
3280 // If sizeof...(T) is zero, there shall be no member type.
3281 case 0:
3282 return QualType();
3283
3284 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3285 // pack T. The member typedef-name type shall denote the same type, if any, as
3286 // common_type_t<T0, T0>; otherwise there shall be no member type.
3287 case 1:
3288 return lookUpCommonType(Ts[0], Ts[0]);
3289
3290 // If sizeof...(T) is two, let the first and second types constituting T be
3291 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3292 // as decay_t<T1> and decay_t<T2>, respectively.
3293 case 2: {
3294 QualType T1 = Ts[0].getAsType();
3295 QualType T2 = Ts[1].getAsType();
3296 QualType D1 = S.BuiltinDecay(T1, {});
3297 QualType D2 = S.BuiltinDecay(T2, {});
3298
3299 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3300 // the same type, if any, as common_type_t<D1, D2>.
3301 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3302 return lookUpCommonType(D1, D2);
3303
3304 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3305 // denotes a valid type, let C denote that type.
3306 {
3307 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3308 EnterExpressionEvaluationContext UnevaluatedContext(
3310 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3312
3313 // false
3315 VK_PRValue);
3316 ExprResult Cond = &CondExpr;
3317
3318 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3319 if (ConstRefQual) {
3320 D1.addConst();
3321 D2.addConst();
3322 }
3323
3324 // declval<D1>()
3325 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3326 ExprResult LHS = &LHSExpr;
3327
3328 // declval<D2>()
3329 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3330 ExprResult RHS = &RHSExpr;
3331
3334
3335 // decltype(false ? declval<D1>() : declval<D2>())
3337 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3338
3339 if (Result.isNull() || SFINAE.hasErrorOccurred())
3340 return QualType();
3341
3342 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3343 return S.BuiltinDecay(Result, TemplateLoc);
3344 };
3345
3346 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3347 return Res;
3348
3349 // Let:
3350 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3351 // COND-RES(X, Y) be
3352 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3353
3354 // C++20 only
3355 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3356 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3357 if (!S.Context.getLangOpts().CPlusPlus20)
3358 return QualType();
3359 return CheckConditionalOperands(true);
3360 }
3361 }
3362
3363 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3364 // denote the first, second, and (pack of) remaining types constituting T. Let
3365 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3366 // a type C, the member typedef-name type shall denote the same type, if any,
3367 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3368 default: {
3369 QualType Result = Ts.front().getAsType();
3370 for (auto T : llvm::drop_begin(Ts)) {
3371 Result = lookUpCommonType(Result, T.getAsType());
3372 if (Result.isNull())
3373 return QualType();
3374 }
3375 return Result;
3376 }
3377 }
3378}
3379
3380static bool isInVkNamespace(const RecordType *RT) {
3381 DeclContext *DC = RT->getDecl()->getDeclContext();
3382 if (!DC)
3383 return false;
3384
3385 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3386 if (!ND)
3387 return false;
3388
3389 return ND->getQualifiedNameAsString() == "hlsl::vk";
3390}
3391
3392static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3393 QualType OperandArg,
3394 SourceLocation Loc) {
3395 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3396 bool Literal = false;
3397 SourceLocation LiteralLoc;
3398 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3399 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3400 assert(SpecDecl);
3401
3402 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3403 QualType ConstantType = LiteralArgs[0].getAsType();
3404 RT = ConstantType->getAsCanonical<RecordType>();
3405 Literal = true;
3406 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3407 }
3408
3409 if (RT && isInVkNamespace(RT) &&
3410 RT->getDecl()->getName() == "integral_constant") {
3411 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3412 assert(SpecDecl);
3413
3414 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3415
3416 QualType ConstantType = ConstantArgs[0].getAsType();
3417 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3418
3419 if (Literal)
3420 return SpirvOperand::createLiteral(Value);
3421 return SpirvOperand::createConstant(ConstantType, Value);
3422 } else if (Literal) {
3423 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3424 return SpirvOperand();
3425 }
3426 }
3427 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3428 diag::err_call_incomplete_argument))
3429 return SpirvOperand();
3430 return SpirvOperand::createType(OperandArg);
3431}
3432
3434 ArrayRef<TemplateArgument> InputArgs) {
3435 // FIXME: cache mangling globally?
3436 std::unique_ptr<MangleContext> MC(Context.createMangleContext());
3438 InputArgs.size());
3439 llvm::transform(InputArgs, SortedArgs.begin(),
3440 [&](const TemplateArgument &Arg) {
3441 assert(Arg.getKind() == TemplateArgument::Type);
3442 std::string MangledName;
3443 llvm::raw_string_ostream OS(MangledName);
3444 MC->mangleCanonicalTypeName(Arg.getAsType(), OS);
3445 return std::pair<std::string, TemplateArgument>(
3446 std::move(MangledName), Arg);
3447 });
3448 llvm::stable_sort(SortedArgs, llvm::less_first());
3449
3450 auto OutArgs = llvm::to_vector(llvm::make_second_range(SortedArgs));
3451 return Context.getSubstBuiltinTemplatePack(
3452 TemplateArgument::CreatePackCopy(Context, OutArgs));
3453}
3454
3457 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3458 TemplateArgumentListInfo &TemplateArgs) {
3459 ASTContext &Context = SemaRef.getASTContext();
3460
3461 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3462 "Builtin template arguments do not match its parameters");
3463
3464 switch (BTD->getBuiltinTemplateKind()) {
3465 case BTK__make_integer_seq: {
3466 // Specializations of __make_integer_seq<S, T, N> are treated like
3467 // S<T, 0, ..., N-1>.
3468
3469 QualType OrigType = Converted[1].getAsType();
3470 // C++14 [inteseq.intseq]p1:
3471 // T shall be an integer type.
3472 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3473 SemaRef.Diag(TemplateArgs[1].getLocation(),
3474 diag::err_integer_sequence_integral_element_type);
3475 return QualType();
3476 }
3477
3478 TemplateArgument NumArgsArg = Converted[2];
3479 if (NumArgsArg.isDependent())
3480 return QualType();
3481
3482 TemplateArgumentListInfo SyntheticTemplateArgs;
3483 // The type argument, wrapped in substitution sugar, gets reused as the
3484 // first template argument in the synthetic template argument list.
3485 SyntheticTemplateArgs.addArgument(
3488 OrigType, TemplateArgs[1].getLocation())));
3489
3490 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3491 // Expand N into 0 ... N-1.
3492 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3493 I < NumArgs; ++I) {
3494 TemplateArgument TA(Context, I, OrigType);
3495 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3496 TA, OrigType, TemplateArgs[2].getLocation()));
3497 }
3498 } else {
3499 // C++14 [inteseq.make]p1:
3500 // If N is negative the program is ill-formed.
3501 SemaRef.Diag(TemplateArgs[2].getLocation(),
3502 diag::err_integer_sequence_negative_length);
3503 return QualType();
3504 }
3505
3506 // The first template argument will be reused as the template decl that
3507 // our synthetic template arguments will be applied to.
3508 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3509 TemplateLoc, SyntheticTemplateArgs,
3510 /*Scope=*/nullptr,
3511 /*ForNestedNameSpecifier=*/false);
3512 }
3513
3514 case BTK__type_pack_element: {
3515 // Specializations of
3516 // __type_pack_element<Index, T_1, ..., T_N>
3517 // are treated like T_Index.
3518 assert(Converted.size() == 2 &&
3519 "__type_pack_element should be given an index and a parameter pack");
3520
3521 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3522 if (IndexArg.isDependent() || Ts.isDependent())
3523 return QualType();
3524
3525 llvm::APSInt Index = IndexArg.getAsIntegral();
3526 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3527 "type std::size_t, and hence be non-negative");
3528 // If the Index is out of bounds, the program is ill-formed.
3529 if (Index >= Ts.pack_size()) {
3530 SemaRef.Diag(TemplateArgs[0].getLocation(),
3531 diag::err_type_pack_element_out_of_bounds);
3532 return QualType();
3533 }
3534
3535 // We simply return the type at index `Index`.
3536 int64_t N = Index.getExtValue();
3537 return Ts.getPackAsArray()[N].getAsType();
3538 }
3539
3540 case BTK__builtin_common_type: {
3541 assert(Converted.size() == 4);
3542 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3543 return QualType();
3544
3545 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3546 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3547 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3548 TemplateLoc, Ts);
3549 !CT.isNull()) {
3553 CT, TemplateArgs[1].getLocation())));
3554 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3555 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3556 TAs, /*Scope=*/nullptr,
3557 /*ForNestedNameSpecifier=*/false);
3558 }
3559 QualType HasNoTypeMember = Converted[2].getAsType();
3560 return HasNoTypeMember;
3561 }
3562
3563 case BTK__hlsl_spirv_type: {
3564 assert(Converted.size() == 4);
3565
3566 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3567 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3568 }
3569
3570 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3571 return QualType();
3572
3573 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3574 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3575 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3576
3577 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3578
3580
3581 for (auto &OperandTA : OperandArgs) {
3582 QualType OperandArg = OperandTA.getAsType();
3583 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3584 TemplateArgs[3].getLocation());
3585 if (!Operand.isValid())
3586 return QualType();
3587 Operands.push_back(Operand);
3588 }
3589
3590 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3591 }
3592 case BTK__builtin_dedup_pack: {
3593 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3594 "a parameter pack");
3595 TemplateArgument Ts = Converted[0];
3596 // Delay the computation until we can compute the final result. We choose
3597 // not to remove the duplicates upfront before substitution to keep the code
3598 // simple.
3599 if (Ts.isDependent())
3600 return QualType();
3601 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3603 llvm::SmallDenseSet<QualType> Seen;
3604 // Synthesize a new template argument list, removing duplicates.
3605 for (auto T : Ts.getPackAsArray()) {
3606 assert(T.getKind() == clang::TemplateArgument::Type);
3607 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3608 continue;
3609 OutArgs.push_back(T);
3610 }
3611 return Context.getSubstBuiltinTemplatePack(
3612 TemplateArgument::CreatePackCopy(Context, OutArgs));
3613 }
3614 case BTK__builtin_sort_pack: {
3615 assert(Converted.size() == 1 &&
3616 "__builtin_sort_pack should be given a parameter pack");
3617 TemplateArgument Ts = Converted[0];
3618 if (Ts.isDependent())
3619 return QualType();
3620 assert(Ts.getKind() == TemplateArgument::Pack);
3621 return sortBuiltinTemplatePack(Context, Ts.getPackAsArray());
3622 }
3623 }
3624 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3625}
3626
3627/// Determine whether this alias template is "enable_if_t".
3628/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3630 return AliasTemplate->getName() == "enable_if_t" ||
3631 AliasTemplate->getName() == "__enable_if_t";
3632}
3633
3634/// Collect all of the separable terms in the given condition, which
3635/// might be a conjunction.
3636///
3637/// FIXME: The right answer is to convert the logical expression into
3638/// disjunctive normal form, so we can find the first failed term
3639/// within each possible clause.
3640static void collectConjunctionTerms(Expr *Clause,
3641 SmallVectorImpl<Expr *> &Terms) {
3642 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3643 if (BinOp->getOpcode() == BO_LAnd) {
3644 collectConjunctionTerms(BinOp->getLHS(), Terms);
3645 collectConjunctionTerms(BinOp->getRHS(), Terms);
3646 return;
3647 }
3648 }
3649
3650 Terms.push_back(Clause);
3651}
3652
3653// The ranges-v3 library uses an odd pattern of a top-level "||" with
3654// a left-hand side that is value-dependent but never true. Identify
3655// the idiom and ignore that term.
3657 // Top-level '||'.
3658 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3659 if (!BinOp) return Cond;
3660
3661 if (BinOp->getOpcode() != BO_LOr) return Cond;
3662
3663 // With an inner '==' that has a literal on the right-hand side.
3664 Expr *LHS = BinOp->getLHS();
3665 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3666 if (!InnerBinOp) return Cond;
3667
3668 if (InnerBinOp->getOpcode() != BO_EQ ||
3669 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3670 return Cond;
3671
3672 // If the inner binary operation came from a macro expansion named
3673 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3674 // of the '||', which is the real, user-provided condition.
3675 SourceLocation Loc = InnerBinOp->getExprLoc();
3676 if (!Loc.isMacroID()) return Cond;
3677
3678 StringRef MacroName = PP.getImmediateMacroName(Loc);
3679 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3680 return BinOp->getRHS();
3681
3682 return Cond;
3683}
3684
3685namespace {
3686
3687// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3688// within failing boolean expression, such as substituting template parameters
3689// for actual types.
3690class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3691public:
3692 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3693 : Policy(P) {}
3694
3695 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3696 const auto *DR = dyn_cast<DeclRefExpr>(E);
3697 if (DR && DR->getQualifier()) {
3698 // If this is a qualified name, expand the template arguments in nested
3699 // qualifiers.
3700 DR->getQualifier().print(OS, Policy, true);
3701 // Then print the decl itself.
3702 const ValueDecl *VD = DR->getDecl();
3703 OS << *VD;
3704 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3705 // This is a template variable, print the expanded template arguments.
3706 printTemplateArgumentList(
3707 OS, IV->getTemplateArgs().asArray(), Policy,
3708 IV->getSpecializedTemplate()->getTemplateParameters());
3709 }
3710 return true;
3711 }
3712 return false;
3713 }
3714
3715private:
3716 const PrintingPolicy Policy;
3717};
3718
3719} // end anonymous namespace
3720
3721std::pair<Expr *, std::string>
3723 Cond = lookThroughRangesV3Condition(PP, Cond);
3724
3725 // Separate out all of the terms in a conjunction.
3727 collectConjunctionTerms(Cond, Terms);
3728
3729 // Determine which term failed.
3730 Expr *FailedCond = nullptr;
3731 for (Expr *Term : Terms) {
3732 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3733
3734 // Literals are uninteresting.
3735 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3736 isa<IntegerLiteral>(TermAsWritten))
3737 continue;
3738
3739 // The initialization of the parameter from the argument is
3740 // a constant-evaluated context.
3743
3744 bool Succeeded;
3745 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3746 !Succeeded) {
3747 FailedCond = TermAsWritten;
3748 break;
3749 }
3750 }
3751 if (!FailedCond)
3752 FailedCond = Cond->IgnoreParenImpCasts();
3753
3754 std::string Description;
3755 {
3756 llvm::raw_string_ostream Out(Description);
3758 Policy.PrintAsCanonical = true;
3759 FailedBooleanConditionPrinterHelper Helper(Policy);
3760 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3761 }
3762 return { FailedCond, Description };
3763}
3764
3765static TemplateName
3767 const AssumedTemplateStorage *ATN,
3768 SourceLocation NameLoc) {
3769 // We assumed this undeclared identifier to be an (ADL-only) function
3770 // template name, but it was used in a context where a type was required.
3771 // Try to typo-correct it now.
3772 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3773 struct CandidateCallback : CorrectionCandidateCallback {
3774 bool ValidateCandidate(const TypoCorrection &TC) override {
3775 return TC.getCorrectionDecl() &&
3777 }
3778 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3779 return std::make_unique<CandidateCallback>(*this);
3780 }
3781 } FilterCCC;
3782
3783 TypoCorrection Corrected =
3784 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3785 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3786 if (Corrected && Corrected.getFoundDecl()) {
3787 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3788 << ATN->getDeclName());
3790 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3792 }
3793
3794 return TemplateName();
3795}
3796
3798 TemplateName Name,
3799 SourceLocation TemplateLoc,
3800 TemplateArgumentListInfo &TemplateArgs,
3801 Scope *Scope, bool ForNestedNameSpecifier) {
3802 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3803
3804 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3805 if (!Template) {
3806 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3807 Template = S->getParameterPack();
3808 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3809 Template = PI->getParameterPack();
3810 if (!Template)
3811 Template = PI->getPattern().getAsTemplateDecl();
3812 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3813 if (DTN->getName().getIdentifier())
3814 // When building a template-id where the template-name is dependent,
3815 // assume the template is a type template. Either our assumption is
3816 // correct, or the code is ill-formed and will be diagnosed when the
3817 // dependent name is substituted.
3818 return Context.getTemplateSpecializationType(Keyword, Name,
3819 TemplateArgs.arguments(),
3820 /*CanonicalArgs=*/{});
3821 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3823 *this, Scope, ATN, TemplateLoc);
3824 CorrectedName.isNull()) {
3825 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3826 return QualType();
3827 } else {
3828 Name = CorrectedName;
3829 Template = Name.getAsTemplateDecl();
3830 }
3831 }
3832 }
3833 if (!Template ||
3835 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3836 if (ForNestedNameSpecifier)
3837 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3838 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3839 else
3840 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3842 return QualType();
3843 }
3844
3845 // Check that the template argument list is well-formed for this
3846 // template.
3848 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3849 DefaultArgs, /*PartialTemplateArgs=*/false,
3850 CTAI,
3851 /*UpdateArgsWithConversions=*/true))
3852 return QualType();
3853
3854 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3855 // and there are no diagnsotics currently implemented for TemplateDecls,
3856 // so avoid doing it for now.
3857 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3858
3859 QualType CanonType;
3860
3862 // We might have a substituted template template parameter pack. If so,
3863 // build a template specialization type for it.
3865 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3866
3867 // C++0x [dcl.type.elab]p2:
3868 // If the identifier resolves to a typedef-name or the simple-template-id
3869 // resolves to an alias template specialization, the
3870 // elaborated-type-specifier is ill-formed.
3873 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3876 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3877 }
3878
3879 // Find the canonical type for this type alias template specialization.
3880 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3881
3882 // Diagnose uses of the pattern of this template.
3883 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3884 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3885
3886 if (Pattern->isInvalidDecl())
3887 return QualType();
3888
3889 // Only substitute for the innermost template argument list.
3890 MultiLevelTemplateArgumentList TemplateArgLists;
3892 /*Final=*/true);
3893 TemplateArgLists.addOuterRetainedLevels(
3894 AliasTemplate->getTemplateParameters()->getDepth());
3895
3897
3898 // FIXME: The TemplateArgs passed here are not used for the context note,
3899 // nor they should, because this note will be pointing to the specialization
3900 // anyway. These arguments are needed for a hack for instantiating lambdas
3901 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3902 // arguments will be used for collating the template arguments needed to
3903 // instantiate the lambda.
3904 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3905 /*Entity=*/AliasTemplate,
3906 /*TemplateArgs=*/CTAI.SugaredConverted);
3907 if (Inst.isInvalid())
3908 return QualType();
3909
3910 std::optional<ContextRAII> SavedContext;
3911 if (!AliasTemplate->getDeclContext()->isFileContext())
3912 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3913
3914 CanonType =
3915 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3916 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3917 if (CanonType.isNull()) {
3918 // If this was enable_if and we failed to find the nested type
3919 // within enable_if in a SFINAE context, dig out the specific
3920 // enable_if condition that failed and present that instead.
3922 if (SFINAETrap *Trap = getSFINAEContext();
3923 TemplateDeductionInfo *DeductionInfo =
3924 Trap ? Trap->getDeductionInfo() : nullptr) {
3925 if (DeductionInfo->hasSFINAEDiagnostic() &&
3926 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3927 diag::err_typename_nested_not_found_enable_if &&
3928 TemplateArgs[0].getArgument().getKind() ==
3930 Expr *FailedCond;
3931 std::string FailedDescription;
3932 std::tie(FailedCond, FailedDescription) =
3933 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3934
3935 // Remove the old SFINAE diagnostic.
3936 PartialDiagnosticAt OldDiag =
3938 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3939
3940 // Add a new SFINAE diagnostic specifying which condition
3941 // failed.
3942 DeductionInfo->addSFINAEDiagnostic(
3943 OldDiag.first,
3944 PDiag(diag::err_typename_nested_not_found_requirement)
3945 << FailedDescription << FailedCond->getSourceRange());
3946 }
3947 }
3948 }
3949
3950 return QualType();
3951 }
3952 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3953 CanonType = checkBuiltinTemplateIdType(
3954 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3955 } else if (Name.isDependent() ||
3956 TemplateSpecializationType::anyDependentTemplateArguments(
3957 TemplateArgs, CTAI.CanonicalConverted)) {
3958 // This class template specialization is a dependent
3959 // type. Therefore, its canonical type is another class template
3960 // specialization type that contains all of the converted
3961 // arguments in canonical form. This ensures that, e.g., A<T> and
3962 // A<T, T> have identical types when A is declared as:
3963 //
3964 // template<typename T, typename U = T> struct A;
3965 CanonType = Context.getCanonicalTemplateSpecializationType(
3967 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3968 CTAI.CanonicalConverted);
3969 assert(CanonType->isCanonicalUnqualified());
3970
3971 // This might work out to be a current instantiation, in which
3972 // case the canonical type needs to be the InjectedClassNameType.
3973 //
3974 // TODO: in theory this could be a simple hashtable lookup; most
3975 // changes to CurContext don't change the set of current
3976 // instantiations.
3978 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3979 // If we get out to a namespace, we're done.
3980 if (Ctx->isFileContext()) break;
3981
3982 // If this isn't a record, keep looking.
3983 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3984 if (!Record) continue;
3985
3986 // Look for one of the two cases with InjectedClassNameTypes
3987 // and check whether it's the same template.
3989 !Record->getDescribedClassTemplate())
3990 continue;
3991
3992 // Fetch the injected class name type and check whether its
3993 // injected type is equal to the type we just built.
3994 CanQualType ICNT = Context.getCanonicalTagType(Record);
3995 CanQualType Injected =
3996 Record->getCanonicalTemplateSpecializationType(Context);
3997
3998 if (CanonType != Injected)
3999 continue;
4000
4001 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
4002 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
4003
4004 // If so, the canonical type of this TST is the injected
4005 // class name type of the record we just found.
4006 CanonType = ICNT;
4007 break;
4008 }
4009 }
4010 } else if (ClassTemplateDecl *ClassTemplate =
4011 dyn_cast<ClassTemplateDecl>(Template)) {
4012 // Find the class template specialization declaration that
4013 // corresponds to these arguments.
4014 llvm::FoldingSetInsertToken InsertToken;
4016 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4017 if (!Decl) {
4018 // This is the first time we have referenced this class template
4019 // specialization. Create the canonical declaration and add it to
4020 // the set of specializations.
4022 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4023 ClassTemplate->getDeclContext(),
4024 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4025 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
4026 CTAI.StrictPackMatch, nullptr);
4027 ClassTemplate->AddSpecialization(Decl, InsertToken);
4028 if (ClassTemplate->isOutOfLine())
4029 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4030 }
4031
4032 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4033 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4034 NonSFINAEContext _(*this);
4035 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4036 if (!Inst.isInvalid()) {
4038 CTAI.CanonicalConverted,
4039 /*Final=*/false);
4040 InstantiateAttrsForDecl(TemplateArgLists,
4041 ClassTemplate->getTemplatedDecl(), Decl);
4042 }
4043 }
4044
4045 // Diagnose uses of this specialization.
4046 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4047 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4048
4049 CanonType = Context.getCanonicalTagType(Decl);
4050 assert(isa<RecordType>(CanonType) &&
4051 "type of non-dependent specialization is not a RecordType");
4052 } else {
4053 llvm_unreachable("Unhandled template kind");
4054 }
4055
4056 // Build the fully-sugared type for this class template
4057 // specialization, which refers back to the class template
4058 // specialization we created or found.
4059 return Context.getTemplateSpecializationType(
4060 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4061 CanonType);
4062}
4063
4065 TemplateNameKind &TNK,
4066 SourceLocation NameLoc,
4067 IdentifierInfo *&II) {
4068 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4069
4070 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4071 assert(ATN && "not an assumed template name");
4072 II = ATN->getDeclName().getAsIdentifierInfo();
4073
4074 if (TemplateName Name =
4075 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4076 !Name.isNull()) {
4077 // Resolved to a type template name.
4078 ParsedName = TemplateTy::make(Name);
4079 TNK = TNK_Type_template;
4080 }
4081}
4082
4084 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4085 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4086 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4087 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4088 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4089 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4090 ImplicitTypenameContext AllowImplicitTypename) {
4091 if (SS.isInvalid())
4092 return true;
4093
4094 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4095 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4096
4097 // C++ [temp.res]p3:
4098 // A qualified-id that refers to a type and in which the
4099 // nested-name-specifier depends on a template-parameter (14.6.2)
4100 // shall be prefixed by the keyword typename to indicate that the
4101 // qualified-id denotes a type, forming an
4102 // elaborated-type-specifier (7.1.5.3).
4103 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4104 // C++2a relaxes some of those restrictions in [temp.res]p5.
4105 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4106 SS.getScopeRep(), TemplateII);
4108 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4109 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4110 << NNS;
4111 if (!getLangOpts().CPlusPlus20)
4112 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4113 } else
4114 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4115
4116 // FIXME: This is not quite correct recovery as we don't transform SS
4117 // into the corresponding dependent form (and we don't diagnose missing
4118 // 'template' keywords within SS as a result).
4119 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4120 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4121 TemplateArgsIn, RAngleLoc);
4122 }
4123
4124 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4125 // it's not actually allowed to be used as a type in most cases. Because
4126 // we annotate it before we know whether it's valid, we have to check for
4127 // this case here.
4128 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4129 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4130 Diag(TemplateIILoc,
4131 TemplateKWLoc.isInvalid()
4132 ? diag::err_out_of_line_qualified_id_type_names_constructor
4133 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4134 << TemplateII << 0 /*injected-class-name used as template name*/
4135 << 1 /*if any keyword was present, it was 'template'*/;
4136 }
4137 }
4138
4139 // Translate the parser's template argument list in our AST format.
4140 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4141 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4142
4144 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4145 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4146 if (SpecTy.isNull())
4147 return true;
4148
4149 // Build type-source information.
4150 TypeLocBuilder TLB;
4151 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4152 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4153 TemplateIILoc, TemplateArgs);
4154 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4155}
4156
4158 TypeSpecifierType TagSpec,
4159 SourceLocation TagLoc,
4160 CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 TemplateTy TemplateD,
4163 SourceLocation TemplateLoc,
4164 SourceLocation LAngleLoc,
4165 ASTTemplateArgsPtr TemplateArgsIn,
4166 SourceLocation RAngleLoc) {
4167 if (SS.isInvalid())
4168 return TypeResult(true);
4169
4170 // Translate the parser's template argument list in our AST format.
4171 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4172 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4173
4174 // Determine the tag kind
4178
4180 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4181 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4182 if (Result.isNull())
4183 return TypeResult(true);
4184
4185 // Check the tag kind
4186 if (const RecordType *RT = Result->getAs<RecordType>()) {
4187 RecordDecl *D = RT->getDecl();
4188
4189 IdentifierInfo *Id = D->getIdentifier();
4190 assert(Id && "templated class must have an identifier");
4191
4193 TagLoc, Id)) {
4194 Diag(TagLoc, diag::err_use_with_wrong_tag)
4195 << Result
4197 Diag(D->getLocation(), diag::note_previous_use);
4198 }
4199 }
4200
4201 // Provide source-location information for the template specialization.
4202 TypeLocBuilder TLB;
4204 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4205 TemplateArgs);
4207}
4208
4209static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4210 NamedDecl *PrevDecl,
4211 SourceLocation Loc,
4213
4215
4217 unsigned Depth,
4218 unsigned Index) {
4219 switch (Arg.getKind()) {
4227 return false;
4228
4230 QualType Type = Arg.getAsType();
4231 const TemplateTypeParmType *TPT =
4232 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4233 return TPT && !Type.hasQualifiers() &&
4234 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4235 }
4236
4238 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4239 if (!DRE || !DRE->getDecl())
4240 return false;
4241 const NonTypeTemplateParmDecl *NTTP =
4242 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4243 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4244 }
4245
4247 const TemplateTemplateParmDecl *TTP =
4248 dyn_cast_or_null<TemplateTemplateParmDecl>(
4250 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4251 }
4252 llvm_unreachable("unexpected kind of template argument");
4253}
4254
4256 TemplateParameterList *SpecParams,
4258 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4259 return false;
4260
4261 unsigned Depth = Params->getDepth();
4262
4263 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4264 TemplateArgument Arg = Args[I];
4265
4266 // If the parameter is a pack expansion, the argument must be a pack
4267 // whose only element is a pack expansion.
4268 if (Params->getParam(I)->isParameterPack()) {
4269 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4270 !Arg.pack_begin()->isPackExpansion())
4271 return false;
4272 Arg = Arg.pack_begin()->getPackExpansionPattern();
4273 }
4274
4275 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4276 return false;
4277
4278 // For NTTPs further specialization is allowed via deduced types, so
4279 // we need to make sure to only reject here if primary template and
4280 // specialization use the same type for the NTTP.
4281 if (auto *SpecNTTP =
4282 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4283 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4284 if (!NTTP || NTTP->getType().getCanonicalType() !=
4285 SpecNTTP->getType().getCanonicalType())
4286 return false;
4287 }
4288 }
4289
4290 return true;
4291}
4292
4293template<typename PartialSpecDecl>
4294static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4295 if (Partial->getDeclContext()->isDependentContext())
4296 return;
4297
4298 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4299 // for non-substitution-failure issues?
4300 TemplateDeductionInfo Info(Partial->getLocation());
4301 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4302 return;
4303
4304 auto *Template = Partial->getSpecializedTemplate();
4305 S.Diag(Partial->getLocation(),
4306 diag::ext_partial_spec_not_more_specialized_than_primary)
4308
4309 if (Info.hasSFINAEDiagnostic()) {
4313 SmallString<128> SFINAEArgString;
4314 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4315 S.Diag(Diag.first,
4316 diag::note_partial_spec_not_more_specialized_than_primary)
4317 << SFINAEArgString;
4318 }
4319
4321 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4322 Template->getAssociatedConstraints(TemplateAC);
4323 Partial->getAssociatedConstraints(PartialAC);
4325 TemplateAC);
4326}
4327
4328static void
4330 const llvm::SmallBitVector &DeducibleParams) {
4331 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4332 if (!DeducibleParams[I]) {
4333 NamedDecl *Param = TemplateParams->getParam(I);
4334 if (Param->getDeclName())
4335 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4336 << Param->getDeclName();
4337 else
4338 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4339 << "(anonymous)";
4340 }
4341 }
4342}
4343
4344
4345template<typename PartialSpecDecl>
4347 PartialSpecDecl *Partial) {
4348 // C++1z [temp.class.spec]p8: (DR1495)
4349 // - The specialization shall be more specialized than the primary
4350 // template (14.5.5.2).
4352
4353 // C++ [temp.class.spec]p8: (DR1315)
4354 // - Each template-parameter shall appear at least once in the
4355 // template-id outside a non-deduced context.
4356 // C++1z [temp.class.spec.match]p3 (P0127R2)
4357 // If the template arguments of a partial specialization cannot be
4358 // deduced because of the structure of its template-parameter-list
4359 // and the template-id, the program is ill-formed.
4360 auto *TemplateParams = Partial->getTemplateParameters();
4361 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4362 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4363 TemplateParams->getDepth(), DeducibleParams);
4364
4365 if (!DeducibleParams.all()) {
4366 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4367 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4369 << (NumNonDeducible > 1)
4370 << SourceRange(Partial->getLocation(),
4371 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4372 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4373 }
4374}
4375
4380
4385
4387 // C++1z [temp.param]p11:
4388 // A template parameter of a deduction guide template that does not have a
4389 // default-argument shall be deducible from the parameter-type-list of the
4390 // deduction guide template.
4391 auto *TemplateParams = TD->getTemplateParameters();
4392 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4393 MarkDeducedTemplateParameters(TD, DeducibleParams);
4394 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4395 // A parameter pack is deducible (to an empty pack).
4396 auto *Param = TemplateParams->getParam(I);
4397 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4398 DeducibleParams[I] = true;
4399 }
4400
4401 if (!DeducibleParams.all()) {
4402 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4403 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4404 << (NumNonDeducible > 1);
4405 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4406 }
4407}
4408
4411 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4413 // D must be variable template id.
4415 "Variable template specialization is declared with a template id.");
4416
4417 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4418 TemplateArgumentListInfo TemplateArgs =
4419 makeTemplateArgumentListInfo(*this, *TemplateId);
4420 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4421 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4422 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4423
4424 TemplateName Name = TemplateId->Template.get();
4425
4426 // The template-id must name a variable template.
4428 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4429 if (!VarTemplate) {
4430 NamedDecl *FnTemplate;
4431 if (auto *OTS = Name.getAsOverloadedTemplate())
4432 FnTemplate = *OTS->begin();
4433 else
4434 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4435 if (FnTemplate)
4436 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4437 << FnTemplate->getDeclName();
4438 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4440 }
4441
4442 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4443 auto Message = DSA->getMessage();
4444 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4445 << VarTemplate << !Message.empty() << Message;
4446 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4447 }
4448
4449 // Check for unexpanded parameter packs in any of the template arguments.
4450 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4451 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4455 return true;
4456
4457 // Check that the template argument list is well-formed for this
4458 // template.
4460 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4461 /*DefaultArgs=*/{},
4462 /*PartialTemplateArgs=*/false, CTAI,
4463 /*UpdateArgsWithConversions=*/true))
4464 return true;
4465
4466 // Find the variable template (partial) specialization declaration that
4467 // corresponds to these arguments.
4470 TemplateArgs.size(),
4471 CTAI.CanonicalConverted))
4472 return true;
4473
4474 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4475 // we also do them during instantiation.
4476 if (!Name.isDependent() &&
4477 !TemplateSpecializationType::anyDependentTemplateArguments(
4478 TemplateArgs, CTAI.CanonicalConverted)) {
4479 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4480 << VarTemplate->getDeclName();
4482 }
4483
4484 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4485 TemplateParams, CTAI.CanonicalConverted) &&
4486 (!Context.getLangOpts().CPlusPlus20 ||
4487 !TemplateParams->hasAssociatedConstraints())) {
4488 // C++ [temp.class.spec]p9b3:
4489 //
4490 // -- The argument list of the specialization shall not be identical
4491 // to the implicit argument list of the primary template.
4492 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4493 << /*variable template*/ 1
4494 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4495 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4496 // FIXME: Recover from this by treating the declaration as a
4497 // redeclaration of the primary template.
4498 return true;
4499 }
4500 }
4501
4502 llvm::FoldingSetInsertToken InsertToken;
4503 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4504
4506 PrevDecl = VarTemplate->findPartialSpecialization(
4507 CTAI.CanonicalConverted, TemplateParams, InsertToken);
4508 else
4509 PrevDecl =
4510 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4511
4513
4514 // Check whether we can declare a variable template specialization in
4515 // the current scope.
4516 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4517 TemplateNameLoc,
4519 return true;
4520
4521 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4522 // Since the only prior variable template specialization with these
4523 // arguments was referenced but not declared, reuse that
4524 // declaration node as our own, updating its source location and
4525 // the list of outer template parameters to reflect our new declaration.
4526 Specialization = PrevDecl;
4527 Specialization->setLocation(TemplateNameLoc);
4528 PrevDecl = nullptr;
4529 } else if (IsPartialSpecialization) {
4530 // Create a new class template partial specialization declaration node.
4532 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4535 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4536 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4537 SC, CTAI.CanonicalConverted);
4538 Partial->setTemplateArgsAsWritten(TemplateArgs);
4539
4540 if (!PrevPartial)
4541 VarTemplate->AddPartialSpecialization(Partial, InsertToken);
4542 Specialization = Partial;
4543
4545 } else {
4546 // Create a new class template specialization declaration node for
4547 // this explicit specialization or friend declaration.
4549 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4550 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4551 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4552
4553 if (!PrevDecl)
4554 VarTemplate->AddSpecialization(Specialization, InsertToken);
4555 }
4556
4557 // C++ [temp.expl.spec]p6:
4558 // If a template, a member template or the member of a class template is
4559 // explicitly specialized then that specialization shall be declared
4560 // before the first use of that specialization that would cause an implicit
4561 // instantiation to take place, in every translation unit in which such a
4562 // use occurs; no diagnostic is required.
4563 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4564 bool Okay = false;
4565 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4566 // Is there any previous explicit specialization declaration?
4568 Okay = true;
4569 break;
4570 }
4571 }
4572
4573 if (!Okay) {
4574 SourceRange Range(TemplateNameLoc, RAngleLoc);
4575 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4576 << Name << Range;
4577
4578 Diag(PrevDecl->getPointOfInstantiation(),
4579 diag::note_instantiation_required_here)
4580 << (PrevDecl->getTemplateSpecializationKind() !=
4582 return true;
4583 }
4584 }
4585
4586 Specialization->setLexicalDeclContext(CurContext);
4587
4588 // Add the specialization into its lexical context, so that it can
4589 // be seen when iterating through the list of declarations in that
4590 // context. However, specializations are not found by name lookup.
4591 CurContext->addDecl(Specialization);
4592
4593 // Note that this is an explicit specialization.
4594 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4595
4596 Previous.clear();
4597 if (PrevDecl)
4598 Previous.addDecl(PrevDecl);
4599 else if (Specialization->isStaticDataMember() &&
4600 Specialization->isOutOfLine())
4601 Specialization->setAccess(VarTemplate->getAccess());
4602
4603 return Specialization;
4604}
4605
4606namespace {
4607/// A partial specialization whose template arguments have matched
4608/// a given template-id.
4609struct PartialSpecMatchResult {
4612};
4613
4614// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4615// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4616static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4617 if (Var->getName() != "format_kind" ||
4618 !Var->getDeclContext()->isStdNamespace())
4619 return false;
4620
4621 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4622 // release in which users can access std::format_kind.
4623 // We can use 20250520 as the final date, see the following commits.
4624 // GCC releases/gcc-15 branch:
4625 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4626 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4627 // GCC master branch:
4628 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4629 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4630 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4631}
4632} // end anonymous namespace
4633
4636 SourceLocation TemplateNameLoc,
4637 const TemplateArgumentListInfo &TemplateArgs,
4638 bool SetWrittenArgs) {
4639 assert(Template && "A variable template id without template?");
4640
4641 // Check that the template argument list is well-formed for this template.
4644 Template, TemplateNameLoc,
4645 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4646 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4647 /*UpdateArgsWithConversions=*/true))
4648 return true;
4649
4650 // Produce a placeholder value if the specialization is dependent.
4651 if (Template->getDeclContext()->isDependentContext() ||
4652 TemplateSpecializationType::anyDependentTemplateArguments(
4653 TemplateArgs, CTAI.CanonicalConverted)) {
4654 if (ParsingInitForAutoVars.empty())
4655 return DeclResult();
4656
4657 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4658 const TemplateArgument &Arg2) {
4659 return Context.isSameTemplateArgument(Arg1, Arg2);
4660 };
4661
4662 if (VarDecl *Var = Template->getTemplatedDecl();
4663 ParsingInitForAutoVars.count(Var) &&
4664 // See comments on this function definition
4665 !IsLibstdcxxStdFormatKind(PP, Var) &&
4666 llvm::equal(
4667 CTAI.CanonicalConverted,
4668 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4669 IsSameTemplateArg)) {
4670 Diag(TemplateNameLoc,
4671 diag::err_auto_variable_cannot_appear_in_own_initializer)
4672 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4673 return true;
4674 }
4675
4677 Template->getPartialSpecializations(PartialSpecs);
4678 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4679 if (ParsingInitForAutoVars.count(Partial) &&
4680 llvm::equal(CTAI.CanonicalConverted,
4681 Partial->getTemplateArgs().asArray(),
4682 IsSameTemplateArg)) {
4683 Diag(TemplateNameLoc,
4684 diag::err_auto_variable_cannot_appear_in_own_initializer)
4685 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4686 << Partial->getType();
4687 return true;
4688 }
4689
4690 return DeclResult();
4691 }
4692
4693 // Find the variable template specialization declaration that
4694 // corresponds to these arguments.
4695 llvm::FoldingSetInsertToken InsertToken;
4697 Template->findSpecialization(CTAI.CanonicalConverted, InsertToken)) {
4698 checkSpecializationReachability(TemplateNameLoc, Spec);
4699 if (Spec->getType()->isUndeducedType()) {
4700 if (ParsingInitForAutoVars.count(Spec))
4701 Diag(TemplateNameLoc,
4702 diag::err_auto_variable_cannot_appear_in_own_initializer)
4703 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4704 << Spec->getType();
4705 else
4706 // We are substituting the initializer of this variable template
4707 // specialization.
4708 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4709 << Spec << Spec->getType();
4710
4711 return true;
4712 }
4713 // If we already have a variable template specialization, return it.
4714 return Spec;
4715 }
4716
4717 // This is the first time we have referenced this variable template
4718 // specialization. Create the canonical declaration and add it to
4719 // the set of specializations, based on the closest partial specialization
4720 // that it represents. That is,
4721 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4722 const TemplateArgumentList *PartialSpecArgs = nullptr;
4723 bool AmbiguousPartialSpec = false;
4724 typedef PartialSpecMatchResult MatchResult;
4726 SourceLocation PointOfInstantiation = TemplateNameLoc;
4727 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4728 /*ForTakingAddress=*/false);
4729
4730 // 1. Attempt to find the closest partial specialization that this
4731 // specializes, if any.
4732 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4733 // Perhaps better after unification of DeduceTemplateArguments() and
4734 // getMoreSpecializedPartialSpecialization().
4736 Template->getPartialSpecializations(PartialSpecs);
4737
4738 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4739 // C++ [temp.spec.partial.member]p2:
4740 // If the primary member template is explicitly specialized for a given
4741 // (implicit) specialization of the enclosing class template, the partial
4742 // specializations of the member template are ignored for this
4743 // specialization of the enclosing class template. If a partial
4744 // specialization of the member template is explicitly specialized for a
4745 // given (implicit) specialization of the enclosing class template, the
4746 // primary member template and its other partial specializations are still
4747 // considered for this specialization of the enclosing class template.
4748 if (Template->isMemberSpecialization() &&
4749 !Partial->isMemberSpecialization())
4750 continue;
4751
4752 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4753
4755 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4757 // Store the failed-deduction information for use in diagnostics, later.
4758 // TODO: Actually use the failed-deduction info?
4759 FailedCandidates.addCandidate().set(
4762 (void)Result;
4763 } else {
4764 Matched.push_back(PartialSpecMatchResult());
4765 Matched.back().Partial = Partial;
4766 Matched.back().Args = Info.takeSugared();
4767 }
4768 }
4769
4770 if (Matched.size() >= 1) {
4771 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4772 if (Matched.size() == 1) {
4773 // -- If exactly one matching specialization is found, the
4774 // instantiation is generated from that specialization.
4775 // We don't need to do anything for this.
4776 } else {
4777 // -- If more than one matching specialization is found, the
4778 // partial order rules (14.5.4.2) are used to determine
4779 // whether one of the specializations is more specialized
4780 // than the others. If none of the specializations is more
4781 // specialized than all of the other matching
4782 // specializations, then the use of the variable template is
4783 // ambiguous and the program is ill-formed.
4784 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4785 PEnd = Matched.end();
4786 P != PEnd; ++P) {
4787 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4788 PointOfInstantiation) ==
4789 P->Partial)
4790 Best = P;
4791 }
4792
4793 // Determine if the best partial specialization is more specialized than
4794 // the others.
4795 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4796 PEnd = Matched.end();
4797 P != PEnd; ++P) {
4799 P->Partial, Best->Partial,
4800 PointOfInstantiation) != Best->Partial) {
4801 AmbiguousPartialSpec = true;
4802 break;
4803 }
4804 }
4805 }
4806
4807 // Instantiate using the best variable template partial specialization.
4808 InstantiationPattern = Best->Partial;
4809 PartialSpecArgs = Best->Args;
4810 } else {
4811 // -- If no match is found, the instantiation is generated
4812 // from the primary template.
4813 // InstantiationPattern = Template->getTemplatedDecl();
4814 }
4815
4816 // 2. Create the canonical declaration.
4817 // Note that we do not instantiate a definition until we see an odr-use
4818 // in DoMarkVarDeclReferenced().
4819 // FIXME: LateAttrs et al.?
4820 if (AmbiguousPartialSpec) {
4821 // Partial ordering did not produce a clear winner. Complain.
4822 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4823 << Template;
4824 // Print the matching partial specializations.
4825 for (MatchResult P : Matched)
4826 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4827 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4828 *P.Args);
4829 return true;
4830 }
4831
4833 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4834 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4835 if (!Decl)
4836 return true;
4837 if (SetWrittenArgs)
4838 Decl->setTemplateArgsAsWritten(TemplateArgs);
4839
4841 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4842 Decl->setInstantiationOf(D, PartialSpecArgs);
4843
4844 checkSpecializationReachability(TemplateNameLoc, Decl);
4845
4846 assert(Decl && "No variable template specialization?");
4847 return Decl;
4848}
4849
4851 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4852 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4853 const TemplateArgumentListInfo *TemplateArgs) {
4854
4855 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4856 *TemplateArgs, /*SetWrittenArgs=*/false);
4857 if (Decl.isInvalid())
4858 return ExprError();
4859
4860 if (!Decl.get())
4861 return ExprResult();
4862
4863 VarDecl *Var = cast<VarDecl>(Decl.get());
4866 NameInfo.getLoc());
4867
4868 // Build an ordinary singleton decl ref.
4869 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4870}
4871
4873 const DeclarationNameInfo &NameInfo, TemplateName Template,
4874 const TemplateArgumentListInfo *TemplateArgs) {
4876 Template.getAsTemplateTemplateParmDecl();
4877 assert(Parameter && "A variable template id without template?");
4878
4879 if (Parameter->templateParameterKind() !=
4881 Parameter->templateParameterKind() !=
4883 return ExprResult();
4884
4885 // Check that the template argument list is well-formed for this template.
4888 Parameter, /*Template kw loc=*/{},
4889 // FIXME: TemplateArgs will not be modified because
4890 // UpdateArgsWithConversions is false, however, we should
4891 // CheckTemplateArgumentList to be const-correct.
4892 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4893 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4894 /*UpdateArgsWithConversions=*/false))
4895 return true;
4896
4898 *TemplateArgs);
4899}
4900
4902 SourceLocation Loc) {
4903 Diag(Loc, diag::err_template_missing_args)
4904 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4905 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4906 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4907 }
4908}
4909
4911 bool TemplateKeyword,
4912 TemplateDecl *TD,
4913 SourceLocation Loc) {
4914 TemplateName Name = Context.getQualifiedTemplateName(
4915 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4917}
4918
4920 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4921 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4922 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4923 bool DoCheckConstraintSatisfaction) {
4924 assert(NamedConcept && "A concept template id without a template?");
4925
4926 if (NamedConcept->isInvalidDecl())
4927 return ExprError();
4928
4931 NamedConcept, ConceptNameInfo.getLoc(),
4932 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4933 /*DefaultArgs=*/{},
4934 /*PartialTemplateArgs=*/false, CTAI,
4935 /*UpdateArgsWithConversions=*/false))
4936 return ExprError();
4937
4938 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4939
4940 // There's a bug with CTAI.CanonicalConverted.
4941 // If the template argument contains a DependentDecltypeType that includes a
4942 // TypeAliasType, and the same written type had occurred previously in the
4943 // source, then the DependentDecltypeType would be canonicalized to that
4944 // previous type which would mess up the substitution.
4945 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4947 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4948 CTAI.SugaredConverted);
4949 ConstraintSatisfaction Satisfaction;
4950 bool AreArgsDependent =
4951 TemplateSpecializationType::anyDependentTemplateArguments(
4952 *TemplateArgs, CTAI.SugaredConverted);
4953 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4954 /*Final=*/false);
4956 Context,
4958 TemplateKWLoc, ConceptNameInfo, FoundDecl, TemplateName(NamedConcept),
4960
4961 bool Error = false;
4962 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4963 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4964 DoCheckConstraintSatisfaction) {
4965
4967
4970
4972 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4973 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4974 TemplateArgs->getRAngleLoc()),
4975 Satisfaction, CL);
4976 Satisfaction.ContainsErrors = Error;
4977 }
4978
4979 if (Error)
4980 return ExprError();
4981
4983 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4984}
4985
4987 SourceLocation TemplateKWLoc,
4988 LookupResult &R,
4989 bool RequiresADL,
4990 const TemplateArgumentListInfo *TemplateArgs) {
4991 // FIXME: Can we do any checking at this point? I guess we could check the
4992 // template arguments that we have against the template name, if the template
4993 // name refers to a single template. That's not a terribly common case,
4994 // though.
4995 // foo<int> could identify a single function unambiguously
4996 // This approach does NOT work, since f<int>(1);
4997 // gets resolved prior to resorting to overload resolution
4998 // i.e., template<class T> void f(double);
4999 // vs template<class T, class U> void f(U);
5000
5001 // These should be filtered out by our callers.
5002 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5003
5004 // Non-function templates require a template argument list.
5005 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5006 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5008 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
5009 return ExprError();
5010 }
5011 }
5012 bool KnownDependent = false;
5013 // In C++1y, check variable template ids.
5014 if (R.getAsSingle<VarTemplateDecl>()) {
5016 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
5017 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5018 if (Res.isInvalid() || Res.isUsable())
5019 return Res;
5020 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
5021 KnownDependent = true;
5022 }
5023
5024 // We don't want lookup warnings at this point.
5025 R.suppressDiagnostics();
5026
5027 if (R.getAsSingle<ConceptDecl>()) {
5028 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5029 R.getRepresentativeDecl(),
5030 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5031 }
5032
5033 // Check variable template ids (C++17) and concept template parameters
5034 // (C++26).
5036 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5037 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5038 assert(TemplateKWLoc.isInvalid() &&
5039 "template keyword in front of a template parameter?");
5041 R.getLookupNameInfo(),
5042 TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5043 }
5044
5045 // Function templates
5047 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5048 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5049 R.begin(), R.end(), KnownDependent,
5050 /*KnownInstantiationDependent=*/false);
5051 // Model the templates with UnresolvedTemplateTy. The expression should then
5052 // either be transformed in an instantiation or be diagnosed in
5053 // CheckPlaceholderExpr.
5054 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5055 !R.getFoundDecl()->getAsFunction())
5056 ULE->setType(Context.UnresolvedTemplateTy);
5057
5058 return ULE;
5059}
5060
5062 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5063 const DeclarationNameInfo &NameInfo,
5064 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5065 assert(TemplateArgs || TemplateKWLoc.isValid());
5066
5067 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5068 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5069 /*EnteringContext=*/false, TemplateKWLoc))
5070 return ExprError();
5071
5072 if (R.isAmbiguous())
5073 return ExprError();
5074
5075 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5076 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5077
5078 if (R.empty()) {
5080 Diag(NameInfo.getLoc(), diag::err_no_member)
5081 << NameInfo.getName() << DC << SS.getRange();
5082 return ExprError();
5083 }
5084
5085 // If necessary, build an implicit class member access.
5086 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5087 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5088 /*S=*/nullptr);
5089
5090 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5091}
5092
5094 CXXScopeSpec &SS,
5095 SourceLocation TemplateKWLoc,
5096 const UnqualifiedId &Name,
5097 ParsedType ObjectType,
5098 bool EnteringContext,
5100 bool AllowInjectedClassName) {
5101 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5102 DiagCompat(TemplateKWLoc, diag_compat::template_outside_of_template)
5103 << FixItHint::CreateRemoval(TemplateKWLoc);
5104
5105 if (SS.isInvalid())
5106 return TNK_Non_template;
5107
5108 // Figure out where isTemplateName is going to look.
5109 DeclContext *LookupCtx = nullptr;
5110 if (SS.isNotEmpty())
5111 LookupCtx = computeDeclContext(SS, EnteringContext);
5112 else if (ObjectType)
5113 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5114
5115 // C++0x [temp.names]p5:
5116 // If a name prefixed by the keyword template is not the name of
5117 // a template, the program is ill-formed. [Note: the keyword
5118 // template may not be applied to non-template members of class
5119 // templates. -end note ] [ Note: as is the case with the
5120 // typename prefix, the template prefix is allowed in cases
5121 // where it is not strictly necessary; i.e., when the
5122 // nested-name-specifier or the expression on the left of the ->
5123 // or . is not dependent on a template-parameter, or the use
5124 // does not appear in the scope of a template. -end note]
5125 //
5126 // Note: C++03 was more strict here, because it banned the use of
5127 // the "template" keyword prior to a template-name that was not a
5128 // dependent name. C++ DR468 relaxed this requirement (the
5129 // "template" keyword is now permitted). We follow the C++0x
5130 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5131 bool MemberOfUnknownSpecialization;
5132 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5133 ObjectType, EnteringContext, Result,
5134 MemberOfUnknownSpecialization);
5135 if (TNK != TNK_Non_template) {
5136 // We resolved this to a (non-dependent) template name. Return it.
5137 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5138 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5140 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5141 // C++14 [class.qual]p2:
5142 // In a lookup in which function names are not ignored and the
5143 // nested-name-specifier nominates a class C, if the name specified
5144 // [...] is the injected-class-name of C, [...] the name is instead
5145 // considered to name the constructor
5146 //
5147 // We don't get here if naming the constructor would be valid, so we
5148 // just reject immediately and recover by treating the
5149 // injected-class-name as naming the template.
5150 Diag(Name.getBeginLoc(),
5151 diag::ext_out_of_line_qualified_id_type_names_constructor)
5152 << Name.Identifier
5153 << 0 /*injected-class-name used as template name*/
5154 << TemplateKWLoc.isValid();
5155 }
5156 return TNK;
5157 }
5158
5159 if (!MemberOfUnknownSpecialization) {
5160 // Didn't find a template name, and the lookup wasn't dependent.
5161 // Do the lookup again to determine if this is a "nothing found" case or
5162 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5163 // need to do this.
5165 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5167 // Tell LookupTemplateName that we require a template so that it diagnoses
5168 // cases where it finds a non-template.
5169 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5170 ? RequiredTemplateKind(TemplateKWLoc)
5172 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5173 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5174 !R.isAmbiguous()) {
5175 if (LookupCtx)
5176 Diag(Name.getBeginLoc(), diag::err_no_member)
5177 << DNI.getName() << LookupCtx << SS.getRange();
5178 else
5179 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5180 << DNI.getName() << SS.getRange();
5181 }
5182 return TNK_Non_template;
5183 }
5184
5185 NestedNameSpecifier Qualifier = SS.getScopeRep();
5186
5187 switch (Name.getKind()) {
5189 Result = TemplateTy::make(Context.getDependentTemplateName(
5190 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5192
5194 Result = TemplateTy::make(Context.getDependentTemplateName(
5195 {Qualifier, Name.OperatorFunctionId.Operator,
5196 TemplateKWLoc.isValid()}));
5197 return TNK_Function_template;
5198
5200 // This is a kind of template name, but can never occur in a dependent
5201 // scope (literal operators can only be declared at namespace scope).
5202 break;
5203
5204 default:
5205 break;
5206 }
5207
5208 // This name cannot possibly name a dependent template. Diagnose this now
5209 // rather than building a dependent template name that can never be valid.
5210 Diag(Name.getBeginLoc(),
5211 diag::err_template_kw_refers_to_dependent_non_template)
5213 << TemplateKWLoc.isValid() << TemplateKWLoc;
5214 return TNK_Non_template;
5215}
5216
5219 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5220 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5221 const TemplateArgument &Arg = AL.getArgument();
5223 TypeSourceInfo *TSI = nullptr;
5224
5225 // Check template type parameter.
5226 switch(Arg.getKind()) {
5228 // C++ [temp.arg.type]p1:
5229 // A template-argument for a template-parameter which is a
5230 // type shall be a type-id.
5231 ArgType = Arg.getAsType();
5232 TSI = AL.getTypeSourceInfo();
5233 break;
5236 // We have a template type parameter but the template argument
5237 // is a template without any arguments.
5238 SourceRange SR = AL.getSourceRange();
5241 return true;
5242 }
5244 // We have a template type parameter but the template argument is an
5245 // expression; see if maybe it is missing the "typename" keyword.
5246 CXXScopeSpec SS;
5247 DeclarationNameInfo NameInfo;
5248 TemplateArgument Pattern = Arg;
5249 if (Pattern.isPackExpansion())
5250 Pattern = Pattern.getPackExpansionPattern();
5251 Expr *E = Pattern.getAsExpr();
5252
5253 if (DependentScopeDeclRefExpr *ArgExpr =
5254 dyn_cast<DependentScopeDeclRefExpr>(E)) {
5255 SS.Adopt(ArgExpr->getQualifierLoc());
5256 NameInfo = ArgExpr->getNameInfo();
5257 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5258 dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5259 if (ArgExpr->isImplicitAccess()) {
5260 SS.Adopt(ArgExpr->getQualifierLoc());
5261 NameInfo = ArgExpr->getMemberNameInfo();
5262 }
5263 }
5264
5265 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5266 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5267 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5268
5269 if (Result.getAsSingle<TypeDecl>() ||
5270 Result.wasNotFoundInCurrentInstantiation()) {
5271 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5272 // Suggest that the user add 'typename' before the NNS.
5274 Diag(Loc, getLangOpts().MSVCCompat
5275 ? diag::ext_ms_template_type_arg_missing_typename
5276 : diag::err_template_arg_must_be_type_suggest)
5277 << FixItHint::CreateInsertion(Loc, "typename ");
5279
5280 // Recover by synthesizing a type using the location information that we
5281 // already have.
5282 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5283 SS.getScopeRep(), II);
5284 TypeLocBuilder TLB;
5286 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5288 TL.setNameLoc(NameInfo.getLoc());
5289 if (Arg.isPackExpansion()) {
5290 ArgType = Context.getPackExpansionType(ArgType, std::nullopt);
5292 TL.setEllipsisLoc(
5293 cast<PackExpansionExpr>(Arg.getAsExpr())->getEllipsisLoc());
5294 }
5295 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5296
5297 // Overwrite our input TemplateArgumentLoc so that we can recover
5298 // properly.
5301
5302 break;
5303 }
5304 }
5305 // fallthrough
5306 [[fallthrough]];
5307 }
5308 default: {
5309 // We allow instantiating a template with template argument packs when
5310 // building deduction guides or mapping constraint template parameters.
5311 if (Arg.getKind() == TemplateArgument::Pack &&
5312 (CodeSynthesisContexts.back().Kind ==
5315 SugaredConverted.push_back(Arg);
5316 CanonicalConverted.push_back(Arg);
5317 return false;
5318 }
5319 // We have a template type parameter but the template argument
5320 // is not a type.
5321 SourceRange SR = AL.getSourceRange();
5322 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5324
5325 return true;
5326 }
5327 }
5328
5329 if (CheckTemplateArgument(TSI))
5330 return true;
5331
5332 // Objective-C ARC:
5333 // If an explicitly-specified template argument type is a lifetime type
5334 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5335 if (getLangOpts().ObjCAutoRefCount &&
5336 ArgType->isObjCLifetimeType() &&
5337 !ArgType.getObjCLifetime()) {
5338 Qualifiers Qs;
5340 ArgType = Context.getQualifiedType(ArgType, Qs);
5341 }
5342
5343 SugaredConverted.push_back(TemplateArgument(ArgType));
5344 CanonicalConverted.push_back(
5345 TemplateArgument(Context.getCanonicalType(ArgType)));
5346 return false;
5347}
5348
5349/// Substitute template arguments into the default template argument for
5350/// the given template type parameter.
5351///
5352/// \param SemaRef the semantic analysis object for which we are performing
5353/// the substitution.
5354///
5355/// \param Template the template that we are synthesizing template arguments
5356/// for.
5357///
5358/// \param TemplateLoc the location of the template name that started the
5359/// template-id we are checking.
5360///
5361/// \param RAngleLoc the location of the right angle bracket ('>') that
5362/// terminates the template-id.
5363///
5364/// \param Param the template template parameter whose default we are
5365/// substituting into.
5366///
5367/// \param Converted the list of template arguments provided for template
5368/// parameters that precede \p Param in the template parameter list.
5369///
5370/// \param Output the resulting substituted template argument.
5371///
5372/// \returns true if an error occurred.
5374 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5375 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5376 ArrayRef<TemplateArgument> SugaredConverted,
5377 ArrayRef<TemplateArgument> CanonicalConverted,
5378 TemplateArgumentLoc &Output) {
5379 Output = Param->getDefaultArgument();
5380
5381 // If the argument type is dependent, instantiate it now based
5382 // on the previously-computed template arguments.
5383 if (Output.getArgument().isInstantiationDependent()) {
5384 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5385 SugaredConverted,
5386 SourceRange(TemplateLoc, RAngleLoc));
5387 if (Inst.isInvalid())
5388 return true;
5389
5390 // Only substitute for the innermost template argument list.
5391 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5392 /*Final=*/true);
5393 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5394 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5395
5396 bool ForLambdaCallOperator = false;
5397 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5398 ForLambdaCallOperator = Rec->isLambda();
5399 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5400 !ForLambdaCallOperator);
5401
5402 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5403 Param->getDefaultArgumentLoc(),
5404 Param->getDeclName()))
5405 return true;
5406 }
5407
5408 return false;
5409}
5410
5411/// Substitute template arguments into the default template argument for
5412/// the given non-type template parameter.
5413///
5414/// \param SemaRef the semantic analysis object for which we are performing
5415/// the substitution.
5416///
5417/// \param Template the template that we are synthesizing template arguments
5418/// for.
5419///
5420/// \param TemplateLoc the location of the template name that started the
5421/// template-id we are checking.
5422///
5423/// \param RAngleLoc the location of the right angle bracket ('>') that
5424/// terminates the template-id.
5425///
5426/// \param Param the non-type template parameter whose default we are
5427/// substituting into.
5428///
5429/// \param Converted the list of template arguments provided for template
5430/// parameters that precede \p Param in the template parameter list.
5431///
5432/// \returns the substituted template argument, or NULL if an error occurred.
5434 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5435 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5436 ArrayRef<TemplateArgument> SugaredConverted,
5437 ArrayRef<TemplateArgument> CanonicalConverted,
5438 TemplateArgumentLoc &Output) {
5439 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5440 SugaredConverted,
5441 SourceRange(TemplateLoc, RAngleLoc));
5442 if (Inst.isInvalid())
5443 return true;
5444
5445 // Only substitute for the innermost template argument list.
5446 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5447 /*Final=*/true);
5448 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5449 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5450
5451 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5452 EnterExpressionEvaluationContext ConstantEvaluated(
5454 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5455 TemplateArgLists, Output);
5456}
5457
5458/// Substitute template arguments into the default template argument for
5459/// the given template template parameter.
5460///
5461/// \param SemaRef the semantic analysis object for which we are performing
5462/// the substitution.
5463///
5464/// \param Template the template that we are synthesizing template arguments
5465/// for.
5466///
5467/// \param TemplateLoc the location of the template name that started the
5468/// template-id we are checking.
5469///
5470/// \param RAngleLoc the location of the right angle bracket ('>') that
5471/// terminates the template-id.
5472///
5473/// \param Param the template template parameter whose default we are
5474/// substituting into.
5475///
5476/// \param Converted the list of template arguments provided for template
5477/// parameters that precede \p Param in the template parameter list.
5478///
5479/// \param QualifierLoc Will be set to the nested-name-specifier (with
5480/// source-location information) that precedes the template name.
5481///
5482/// \returns the substituted template argument, or NULL if an error occurred.
5484 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5485 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5487 ArrayRef<TemplateArgument> SugaredConverted,
5488 ArrayRef<TemplateArgument> CanonicalConverted,
5489 NestedNameSpecifierLoc &QualifierLoc) {
5491 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5492 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5493 if (Inst.isInvalid())
5494 return TemplateName();
5495
5496 // Only substitute for the innermost template argument list.
5497 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5498 /*Final=*/true);
5499 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5500 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5501
5502 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5503
5504 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5505 QualifierLoc = A.getTemplateQualifierLoc();
5506 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5508 A.getTemplateNameLoc(), TemplateArgLists);
5509}
5510
5512 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5513 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5514 ArrayRef<TemplateArgument> SugaredConverted,
5515 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5516 HasDefaultArg = false;
5517
5518 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5519 if (!hasReachableDefaultArgument(TypeParm))
5520 return TemplateArgumentLoc();
5521
5522 HasDefaultArg = true;
5523 TemplateArgumentLoc Output;
5524 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5525 RAngleLoc, TypeParm, SugaredConverted,
5526 CanonicalConverted, Output))
5527 return TemplateArgumentLoc();
5528 return Output;
5529 }
5530
5531 if (NonTypeTemplateParmDecl *NonTypeParm
5532 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5533 if (!hasReachableDefaultArgument(NonTypeParm))
5534 return TemplateArgumentLoc();
5535
5536 HasDefaultArg = true;
5537 TemplateArgumentLoc Output;
5538 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5539 RAngleLoc, NonTypeParm, SugaredConverted,
5540 CanonicalConverted, Output))
5541 return TemplateArgumentLoc();
5542 return Output;
5543 }
5544
5545 TemplateTemplateParmDecl *TempTempParm
5547 if (!hasReachableDefaultArgument(TempTempParm))
5548 return TemplateArgumentLoc();
5549
5550 HasDefaultArg = true;
5551 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5552 NestedNameSpecifierLoc QualifierLoc;
5554 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5555 SugaredConverted, CanonicalConverted, QualifierLoc);
5556 if (TName.isNull())
5557 return TemplateArgumentLoc();
5558
5559 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5560 QualifierLoc, A.getTemplateNameLoc());
5561}
5562
5563/// Convert a template-argument that we parsed as a type into a template, if
5564/// possible. C++ permits injected-class-names to perform dual service as
5565/// template template arguments and as template type arguments.
5568 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5569 if (!TagLoc)
5570 return TemplateArgumentLoc();
5571
5572 // If this type was written as an injected-class-name, it can be used as a
5573 // template template argument.
5574 // If this type was written as an injected-class-name, it may have been
5575 // converted to a RecordType during instantiation. If the RecordType is
5576 // *not* wrapped in a TemplateSpecializationType and denotes a class
5577 // template specialization, it must have come from an injected-class-name.
5578
5579 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5580 if (Name.isNull())
5581 return TemplateArgumentLoc();
5582
5583 return TemplateArgumentLoc(Context, Name,
5584 /*TemplateKWLoc=*/SourceLocation(),
5585 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5586}
5587
5590 SourceLocation TemplateLoc,
5591 SourceLocation RAngleLoc,
5592 unsigned ArgumentPackIndex,
5595 // Check template type parameters.
5596 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5597 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5598 CTAI.CanonicalConverted);
5599
5600 const TemplateArgument &Arg = ArgLoc.getArgument();
5601 // Check non-type template parameters.
5602 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5603 // Do substitution on the type of the non-type template parameter
5604 // with the template arguments we've seen thus far. But if the
5605 // template has a dependent context then we cannot substitute yet.
5606 QualType NTTPType = NTTP->getType();
5607 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5608 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5609
5610 // C++26 [dcl.type.auto.deduct]p3:
5611 // If the placeholder-type-specifier is of the form type-constraint_opt
5612 // auto, [...] If E is a value synthesized for a constant template
5613 // parameter of type decltype(auto) ([temp.func.order]), the declaration
5614 // is ill-formed.
5615 auto isUndeducedAuto = [](QualType T, bool DecltypeAuto) {
5616 const AutoType *AT = T->getContainedAutoType();
5617 return AT && AT->isDecltypeAuto() == DecltypeAuto &&
5618 AT->getDeducedType().isNull();
5619 };
5620 if (CTAI.PartialOrdering &&
5621 isUndeducedAuto(NTTPType, /*DecltypeAuto=*/false) &&
5622 isUndeducedAuto(getTypeOfConstantTemplateParameter(Arg),
5623 /*DecltypeAuto=*/true))
5624 return true;
5625
5626 if (NTTPType->isInstantiationDependentType()) {
5627 // Do substitution on the type of the non-type template parameter.
5628 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5629 CTAI.SugaredConverted,
5630 SourceRange(TemplateLoc, RAngleLoc));
5631 if (Inst.isInvalid())
5632 return true;
5633
5635 /*Final=*/true);
5636 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5637 // If the parameter is a pack expansion, expand this slice of the pack.
5638 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5639 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5640 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5641 NTTP->getDeclName());
5642 } else {
5643 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5644 NTTP->getDeclName());
5645 }
5646
5647 // If that worked, check the non-type template parameter type
5648 // for validity.
5649 if (!NTTPType.isNull())
5650 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5651 NTTP->getLocation());
5652 if (NTTPType.isNull())
5653 return true;
5654 }
5655
5656 auto checkExpr = [&](Expr *E) -> Expr * {
5657 TemplateArgument SugaredResult, CanonicalResult;
5659 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5660 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5661 // If the current template argument causes an error, give up now.
5662 if (Res.isInvalid())
5663 return nullptr;
5664 CTAI.SugaredConverted.push_back(SugaredResult);
5665 CTAI.CanonicalConverted.push_back(CanonicalResult);
5666 return Res.get();
5667 };
5668
5669 switch (Arg.getKind()) {
5671 llvm_unreachable("Should never see a NULL template argument here");
5672
5674 Expr *E = Arg.getAsExpr();
5675 Expr *R = checkExpr(E);
5676 if (!R)
5677 return true;
5678 // If the resulting expression is new, then use it in place of the
5679 // old expression in the template argument.
5680 if (R != E) {
5681 TemplateArgument TA(R, /*IsCanonical=*/false);
5682 ArgLoc = TemplateArgumentLoc(TA, R);
5683 }
5684 break;
5685 }
5686
5687 // As for the converted NTTP kinds, they still might need another
5688 // conversion, as the new corresponding parameter might be different.
5689 // Ideally, we would always perform substitution starting with sugared types
5690 // and never need these, as we would still have expressions. Since these are
5691 // needed so rarely, it's probably a better tradeoff to just convert them
5692 // back to expressions.
5697 // FIXME: StructuralValue is untested here.
5698 ExprResult R =
5700 assert(R.isUsable());
5701 if (!checkExpr(R.get()))
5702 return true;
5703 break;
5704 }
5705
5708 // We were given a template template argument. It may not be ill-formed;
5709 // see below.
5712 // We have a template argument such as \c T::template X, which we
5713 // parsed as a template template argument. However, since we now
5714 // know that we need a non-type template argument, convert this
5715 // template name into an expression.
5716
5717 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5718 ArgLoc.getTemplateNameLoc());
5719
5720 CXXScopeSpec SS;
5721 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5722 // FIXME: the template-template arg was a DependentTemplateName,
5723 // so it was provided with a template keyword. However, its source
5724 // location is not stored in the template argument structure.
5725 SourceLocation TemplateKWLoc;
5727 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5728 nullptr);
5729
5730 // If we parsed the template argument as a pack expansion, create a
5731 // pack expansion expression.
5734 if (E.isInvalid())
5735 return true;
5736 }
5737
5738 TemplateArgument SugaredResult, CanonicalResult;
5740 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5741 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5742 if (E.isInvalid())
5743 return true;
5744
5745 CTAI.SugaredConverted.push_back(SugaredResult);
5746 CTAI.CanonicalConverted.push_back(CanonicalResult);
5747 break;
5748 }
5749
5750 // We have a template argument that actually does refer to a class
5751 // template, alias template, or template template parameter, and
5752 // therefore cannot be a non-type template argument.
5753 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5754 << ArgLoc.getSourceRange();
5756
5757 return true;
5758
5760 // We have a non-type template parameter but the template
5761 // argument is a type.
5762
5763 // C++ [temp.arg]p2:
5764 // In a template-argument, an ambiguity between a type-id and
5765 // an expression is resolved to a type-id, regardless of the
5766 // form of the corresponding template-parameter.
5767 //
5768 // We warn specifically about this case, since it can be rather
5769 // confusing for users.
5770 QualType T = Arg.getAsType();
5771 SourceRange SR = ArgLoc.getSourceRange();
5772 if (T->isFunctionType())
5773 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5774 else
5775 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5777 return true;
5778 }
5779
5781 llvm_unreachable("Caller must expand template argument packs");
5782 }
5783
5784 return false;
5785 }
5786
5787
5788 // Check template template parameters.
5790
5791 TemplateParameterList *Params = TempParm->getTemplateParameters();
5792 if (TempParm->isExpandedParameterPack())
5793 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5794
5795 // Substitute into the template parameter list of the template
5796 // template parameter, since previously-supplied template arguments
5797 // may appear within the template template parameter.
5798 //
5799 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5800 {
5801 // Set up a template instantiation context.
5803 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5804 CTAI.SugaredConverted,
5805 SourceRange(TemplateLoc, RAngleLoc));
5806 if (Inst.isInvalid())
5807 return true;
5808
5809 Params = SubstTemplateParams(
5810 Params, CurContext,
5812 /*Final=*/true),
5813 /*EvaluateConstraints=*/false);
5814 if (!Params)
5815 return true;
5816 }
5817
5818 // C++1z [temp.local]p1: (DR1004)
5819 // When [the injected-class-name] is used [...] as a template-argument for
5820 // a template template-parameter [...] it refers to the class template
5821 // itself.
5822 if (Arg.getKind() == TemplateArgument::Type) {
5824 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5825 if (!ConvertedArg.getArgument().isNull())
5826 ArgLoc = ConvertedArg;
5827 }
5828
5829 switch (Arg.getKind()) {
5831 llvm_unreachable("Should never see a NULL template argument here");
5832
5835 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5836 CTAI.PartialOrdering,
5837 &CTAI.StrictPackMatch))
5838 return true;
5839
5840 CTAI.SugaredConverted.push_back(Arg);
5841 CTAI.CanonicalConverted.push_back(
5842 Context.getCanonicalTemplateArgument(Arg));
5843 break;
5844
5847 auto Kind = 0;
5848 switch (TempParm->templateParameterKind()) {
5850 Kind = 1;
5851 break;
5853 Kind = 2;
5854 break;
5855 default:
5856 break;
5857 }
5858
5859 // We have a template template parameter but the template
5860 // argument does not refer to a template.
5861 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5862 << Kind << getLangOpts().CPlusPlus11;
5863 return true;
5864 }
5865
5870 llvm_unreachable("non-type argument with template template parameter");
5871
5873 llvm_unreachable("Caller must expand template argument packs");
5874 }
5875
5876 return false;
5877}
5878
5879/// Diagnose a missing template argument.
5880template <typename TemplateParmDecl>
5882 TemplateDecl *TD,
5883 const TemplateParmDecl *D) {
5884 // Dig out the most recent declaration of the template parameter; there may be
5885 // declarations of the template that are more recent than TD.
5887 ->getTemplateParameters()
5888 ->getParam(D->getIndex()));
5889
5890 // If there's a default argument that's not reachable, diagnose that we're
5891 // missing a module import.
5893 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5895 D->getDefaultArgumentLoc(), Modules,
5897 /*Recover*/true);
5898 return;
5899 }
5900
5901 // FIXME: If there's a more recent default argument that *is* visible,
5902 // diagnose that it was declared too late.
5903
5905
5906 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5907 << /*not enough args*/0
5909 << TD;
5910 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5911}
5912
5913/// Check that the given template argument list is well-formed
5914/// for specializing the given template.
5916 TemplateDecl *Template, SourceLocation TemplateLoc,
5917 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5918 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5919 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5921 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5922 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5924}
5925
5926/// Check that the given template argument list is well-formed
5927/// for specializing the given template.
5930 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5931 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5932 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5934
5936 *ConstraintsNotSatisfied = false;
5937
5938 // Make a copy of the template arguments for processing. Only make the
5939 // changes at the end when successful in matching the arguments to the
5940 // template.
5941 TemplateArgumentListInfo NewArgs = TemplateArgs;
5942
5943 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5944
5945 // C++23 [temp.arg.general]p1:
5946 // [...] The type and form of each template-argument specified in
5947 // a template-id shall match the type and form specified for the
5948 // corresponding parameter declared by the template in its
5949 // template-parameter-list.
5950 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5951 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5952 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5953 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5954 LocalInstantiationScope InstScope(*this, true);
5955 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5956 ParamEnd = Params->end(),
5957 Param = ParamBegin;
5958 Param != ParamEnd;
5959 /* increment in loop */) {
5960 if (size_t ParamIdx = Param - ParamBegin;
5961 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5962 // All written arguments should have been consumed by this point.
5963 assert(ArgIdx == NumArgs && "bad default argument deduction");
5964 if (ParamIdx == DefaultArgs.StartPos) {
5965 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5966 // Default arguments from a DeducedTemplateName are already converted.
5967 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5968 CTAI.SugaredConverted.push_back(DefArg);
5969 CTAI.CanonicalConverted.push_back(
5970 Context.getCanonicalTemplateArgument(DefArg));
5971 ++Param;
5972 }
5973 continue;
5974 }
5975 }
5976
5977 // If we have an expanded parameter pack, make sure we don't have too
5978 // many arguments.
5979 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5980 if (*Expansions == SugaredArgumentPack.size()) {
5981 // We're done with this parameter pack. Pack up its arguments and add
5982 // them to the list.
5983 CTAI.SugaredConverted.push_back(
5984 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5985 SugaredArgumentPack.clear();
5986
5987 CTAI.CanonicalConverted.push_back(
5988 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5989 CanonicalArgumentPack.clear();
5990
5991 // This argument is assigned to the next parameter.
5992 ++Param;
5993 continue;
5994 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5995 // Not enough arguments for this parameter pack.
5996 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5997 << /*not enough args*/0
5999 << Template;
6001 return true;
6002 }
6003 }
6004
6005 // Check for builtins producing template packs in this context, we do not
6006 // support them yet.
6007 if (const NonTypeTemplateParmDecl *NTTP =
6008 dyn_cast<NonTypeTemplateParmDecl>(*Param);
6009 NTTP && NTTP->isPackExpansion()) {
6010 auto TL = NTTP->getTypeSourceInfo()
6011 ->getTypeLoc()
6014 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
6015 for (const auto &UPP : Unexpanded) {
6016 auto *TST = dyn_cast<const TemplateSpecializationType *>(UPP.first);
6017 if (!TST)
6018 continue;
6019 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
6020 // Expanding a built-in pack in this context is not yet supported.
6021 Diag(TL.getEllipsisLoc(),
6022 diag::err_unsupported_builtin_template_pack_expansion)
6023 << TST->getTemplateName();
6024 return true;
6025 }
6026 }
6027
6028 if (ArgIdx < NumArgs) {
6029 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
6030 bool NonPackParameter =
6031 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
6032 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
6033
6034 if (ArgIsExpansion && CTAI.MatchingTTP) {
6035 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
6036 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
6037 ++Param) {
6038 TemplateArgument &Arg = Args[Param - First];
6039 Arg = ArgLoc.getArgument();
6040 if (!(*Param)->isTemplateParameterPack() ||
6041 getExpandedPackSize(*Param))
6042 Arg = Arg.getPackExpansionPattern();
6043 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
6044 SaveAndRestore _1(CTAI.PartialOrdering, false);
6045 SaveAndRestore _2(CTAI.MatchingTTP, true);
6046 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
6047 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6049 return true;
6050 Arg = NewArgLoc.getArgument();
6051 CTAI.CanonicalConverted.back().setIsDefaulted(
6052 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6053 CTAI.CanonicalConverted,
6054 Params->getDepth()));
6055 }
6056 ArgLoc = TemplateArgumentLoc(
6059 } else {
6060 SaveAndRestore _1(CTAI.PartialOrdering, false);
6061 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6062 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6064 return true;
6065 CTAI.CanonicalConverted.back().setIsDefaulted(
6066 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6067 *Param, CTAI.CanonicalConverted,
6068 Params->getDepth()));
6069 if (ArgIsExpansion && NonPackParameter) {
6070 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6071 // alias template, builtin template, or concept, and it's not part of
6072 // a parameter pack. This can't be canonicalized, so reject it now.
6074 Template)) {
6075 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6077 : 0;
6078 Diag(ArgLoc.getLocation(),
6079 diag::err_template_expansion_into_fixed_list)
6080 << DiagSelect << ArgLoc.getSourceRange();
6082 return true;
6083 }
6084 }
6085 }
6086
6087 // We're now done with this argument.
6088 ++ArgIdx;
6089
6090 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6091 // Directly convert the remaining arguments, because we don't know what
6092 // parameters they'll match up with.
6093
6094 if (!SugaredArgumentPack.empty()) {
6095 // If we were part way through filling in an expanded parameter pack,
6096 // fall back to just producing individual arguments.
6097 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6098 SugaredArgumentPack.begin(),
6099 SugaredArgumentPack.end());
6100 SugaredArgumentPack.clear();
6101
6102 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6103 CanonicalArgumentPack.begin(),
6104 CanonicalArgumentPack.end());
6105 CanonicalArgumentPack.clear();
6106 }
6107
6108 while (ArgIdx < NumArgs) {
6109 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6110 CTAI.SugaredConverted.push_back(Arg);
6111 CTAI.CanonicalConverted.push_back(
6112 Context.getCanonicalTemplateArgument(Arg));
6113 ++ArgIdx;
6114 }
6115
6116 return false;
6117 }
6118
6119 if ((*Param)->isTemplateParameterPack()) {
6120 // The template parameter was a template parameter pack, so take the
6121 // deduced argument and place it on the argument pack. Note that we
6122 // stay on the same template parameter so that we can deduce more
6123 // arguments.
6124 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6125 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6126 } else {
6127 // Move to the next template parameter.
6128 ++Param;
6129 }
6130 continue;
6131 }
6132
6133 // If we're checking a partial template argument list, we're done.
6134 if (PartialTemplateArgs) {
6135 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6136 CTAI.SugaredConverted.push_back(
6137 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6138 CTAI.CanonicalConverted.push_back(
6139 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6140 }
6141 return false;
6142 }
6143
6144 // If we have a template parameter pack with no more corresponding
6145 // arguments, just break out now and we'll fill in the argument pack below.
6146 if ((*Param)->isTemplateParameterPack()) {
6147 assert(!getExpandedPackSize(*Param) &&
6148 "Should have dealt with this already");
6149
6150 // A non-expanded parameter pack before the end of the parameter list
6151 // only occurs for an ill-formed template parameter list, unless we've
6152 // got a partial argument list for a function template, so just bail out.
6153 if (Param + 1 != ParamEnd) {
6154 assert(
6155 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6156 "Concept templates must have parameter packs at the end.");
6157 return true;
6158 }
6159
6160 CTAI.SugaredConverted.push_back(
6161 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6162 SugaredArgumentPack.clear();
6163
6164 CTAI.CanonicalConverted.push_back(
6165 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6166 CanonicalArgumentPack.clear();
6167
6168 ++Param;
6169 continue;
6170 }
6171
6172 // Check whether we have a default argument.
6173 bool HasDefaultArg;
6174
6175 // Retrieve the default template argument from the template
6176 // parameter. For each kind of template parameter, we substitute the
6177 // template arguments provided thus far and any "outer" template arguments
6178 // (when the template parameter was part of a nested template) into
6179 // the default argument.
6181 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6182 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6183
6184 if (Arg.getArgument().isNull()) {
6185 if (!HasDefaultArg) {
6186 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6187 diagnoseMissingArgument(*this, TemplateLoc, Template, TTP);
6188 else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*Param))
6189 diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP);
6190 else
6191 diagnoseMissingArgument(*this, TemplateLoc, Template,
6193 }
6194 return true;
6195 }
6196
6197 // Introduce an instantiation record that describes where we are using
6198 // the default template argument. We're not actually instantiating a
6199 // template here, we just create this object to put a note into the
6200 // context stack.
6201 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6202 CTAI.SugaredConverted,
6203 SourceRange(TemplateLoc, RAngleLoc));
6204 if (Inst.isInvalid())
6205 return true;
6206
6207 SaveAndRestore _1(CTAI.PartialOrdering, false);
6208 SaveAndRestore _2(CTAI.MatchingTTP, false);
6209 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6210 // Check the default template argument.
6211 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6212 CTAI, CTAK_Specified))
6213 return true;
6214
6215 CTAI.SugaredConverted.back().setIsDefaulted(true);
6216 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6217
6218 // Core issue 150 (assumed resolution): if this is a template template
6219 // parameter, keep track of the default template arguments from the
6220 // template definition.
6221 if (isTemplateTemplateParameter)
6222 NewArgs.addArgument(Arg);
6223
6224 // Move to the next template parameter and argument.
6225 ++Param;
6226 ++ArgIdx;
6227 }
6228
6229 // If we're performing a partial argument substitution, allow any trailing
6230 // pack expansions; they might be empty. This can happen even if
6231 // PartialTemplateArgs is false (the list of arguments is complete but
6232 // still dependent).
6233 if (CTAI.MatchingTTP ||
6235 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6236 while (ArgIdx < NumArgs &&
6237 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6238 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6239 CTAI.SugaredConverted.push_back(Arg);
6240 CTAI.CanonicalConverted.push_back(
6241 Context.getCanonicalTemplateArgument(Arg));
6242 }
6243 }
6244
6245 // If we have any leftover arguments, then there were too many arguments.
6246 // Complain and fail.
6247 if (ArgIdx < NumArgs) {
6248 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6249 << /*too many args*/1
6251 << Template
6252 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6254 return true;
6255 }
6256
6257 // No problems found with the new argument list, propagate changes back
6258 // to caller.
6259 if (UpdateArgsWithConversions)
6260 TemplateArgs = std::move(NewArgs);
6261
6262 if (!PartialTemplateArgs) {
6263 // Setup the context/ThisScope for the case where we are needing to
6264 // re-instantiate constraints outside of normal instantiation.
6265 DeclContext *NewContext = Template->getDeclContext();
6266
6267 // If this template is in a template, make sure we extract the templated
6268 // decl.
6269 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6270 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6271 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6272
6273 Qualifiers ThisQuals;
6274 if (const auto *Method =
6275 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6276 ThisQuals = Method->getMethodQualifiers();
6277
6278 ContextRAII Context(*this, NewContext);
6279 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6280
6282 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6283 /*RelativeToPrimary=*/true,
6284 /*Pattern=*/nullptr,
6285 /*ForConceptInstantiation=*/true);
6286 if (!isa<ConceptDecl>(Template) &&
6288 Template, MLTAL,
6289 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6292 return true;
6293 }
6294 }
6295
6296 return false;
6297}
6298
6299namespace {
6300 class UnnamedLocalNoLinkageFinder
6301 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6302 {
6303 Sema &S;
6304 SourceRange SR;
6305
6307
6308 public:
6309 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6310
6311 bool Visit(QualType T) {
6312 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6313 }
6314
6315#define TYPE(Class, Parent) \
6316 bool Visit##Class##Type(const Class##Type *);
6317#define ABSTRACT_TYPE(Class, Parent) \
6318 bool Visit##Class##Type(const Class##Type *) { return false; }
6319#define NON_CANONICAL_TYPE(Class, Parent) \
6320 bool Visit##Class##Type(const Class##Type *) { return false; }
6321#include "clang/AST/TypeNodes.inc"
6322
6323 bool VisitTagDecl(const TagDecl *Tag);
6324 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6325 };
6326} // end anonymous namespace
6327
6328bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6329 return false;
6330}
6331
6332bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6333 return Visit(T->getElementType());
6334}
6335
6336bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6337 return Visit(T->getPointeeType());
6338}
6339
6340bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6341 const BlockPointerType* T) {
6342 return Visit(T->getPointeeType());
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6346 const LValueReferenceType* T) {
6347 return Visit(T->getPointeeType());
6348}
6349
6350bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6351 const RValueReferenceType* T) {
6352 return Visit(T->getPointeeType());
6353}
6354
6355bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6356 const MemberPointerType *T) {
6357 if (Visit(T->getPointeeType()))
6358 return true;
6359 if (auto *RD = T->getMostRecentCXXRecordDecl())
6360 return VisitTagDecl(RD);
6361 return VisitNestedNameSpecifier(T->getQualifier());
6362}
6363
6364bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6365 const ConstantArrayType* T) {
6366 return Visit(T->getElementType());
6367}
6368
6369bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6370 const IncompleteArrayType* T) {
6371 return Visit(T->getElementType());
6372}
6373
6374bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6375 const VariableArrayType* T) {
6376 return Visit(T->getElementType());
6377}
6378
6379bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6380 const DependentSizedArrayType* T) {
6381 return Visit(T->getElementType());
6382}
6383
6384bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6386 return Visit(T->getElementType());
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6390 const DependentSizedMatrixType *T) {
6391 return Visit(T->getElementType());
6392}
6393
6394bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6396 return Visit(T->getPointeeType());
6397}
6398
6399bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6400 return Visit(T->getElementType());
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6404 const DependentVectorType *T) {
6405 return Visit(T->getElementType());
6406}
6407
6408bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6409 return Visit(T->getElementType());
6410}
6411
6412bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6413 const ConstantMatrixType *T) {
6414 return Visit(T->getElementType());
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6418 const FunctionProtoType* T) {
6419 for (const auto &A : T->param_types()) {
6420 if (Visit(A))
6421 return true;
6422 }
6423
6424 return Visit(T->getReturnType());
6425}
6426
6427bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6428 const FunctionNoProtoType* T) {
6429 return Visit(T->getReturnType());
6430}
6431
6432bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6433 const UnresolvedUsingType*) {
6434 return false;
6435}
6436
6437bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6438 return false;
6439}
6440
6441bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6442 return Visit(T->getUnmodifiedType());
6443}
6444
6445bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6446 return false;
6447}
6448
6449bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6450 const PackIndexingType *) {
6451 return false;
6452}
6453
6454bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6455 const UnaryTransformType*) {
6456 return false;
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6460 return Visit(T->getDeducedType());
6461}
6462
6463bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6464 const DeducedTemplateSpecializationType *T) {
6465 return Visit(T->getDeducedType());
6466}
6467
6468bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6469 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6470}
6471
6472bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6473 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6474}
6475
6476bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6477 const TemplateTypeParmType*) {
6478 return false;
6479}
6480
6481bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6482 const SubstTemplateTypeParmPackType *) {
6483 return false;
6484}
6485
6486bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6487 const SubstBuiltinTemplatePackType *) {
6488 return false;
6489}
6490
6491bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6492 const TemplateSpecializationType*) {
6493 return false;
6494}
6495
6496bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6497 const InjectedClassNameType* T) {
6498 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6499}
6500
6501bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6502 const DependentNameType* T) {
6503 return VisitNestedNameSpecifier(T->getQualifier());
6504}
6505
6506bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6507 const PackExpansionType* T) {
6508 return Visit(T->getPattern());
6509}
6510
6511bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6512 return false;
6513}
6514
6515bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6516 const ObjCInterfaceType *) {
6517 return false;
6518}
6519
6520bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6521 const ObjCObjectPointerType *) {
6522 return false;
6523}
6524
6525bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6526 return Visit(T->getValueType());
6527}
6528
6529bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6530 const OverflowBehaviorType *T) {
6531 return Visit(T->getUnderlyingType());
6532}
6533
6534bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6535 return false;
6536}
6537
6538bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6539 return false;
6540}
6541
6542bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6543 const ArrayParameterType *T) {
6544 return VisitConstantArrayType(T);
6545}
6546
6547bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6548 const DependentBitIntType *T) {
6549 return false;
6550}
6551
6552bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6553 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6554 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6555 ? diag::warn_cxx98_compat_template_arg_local_type
6556 : diag::ext_template_arg_local_type)
6557 << S.Context.getCanonicalTagType(Tag) << SR;
6558 return true;
6559 }
6560
6561 if (!Tag->hasNameForLinkage()) {
6562 S.Diag(SR.getBegin(),
6563 S.getLangOpts().CPlusPlus11 ?
6564 diag::warn_cxx98_compat_template_arg_unnamed_type :
6565 diag::ext_template_arg_unnamed_type) << SR;
6566 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6567 return true;
6568 }
6569
6570 return false;
6571}
6572
6573bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6574 NestedNameSpecifier NNS) {
6575 switch (NNS.getKind()) {
6580 return false;
6582 return Visit(QualType(NNS.getAsType(), 0));
6583 }
6584 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6585}
6586
6587bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6588 const HLSLAttributedResourceType *T) {
6589 if (T->hasContainedType() && Visit(T->getContainedType()))
6590 return true;
6591 return Visit(T->getWrappedType());
6592}
6593
6594bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6595 const HLSLInlineSpirvType *T) {
6596 for (auto &Operand : T->getOperands())
6597 if (Operand.isConstant() && Operand.isLiteral())
6598 if (Visit(Operand.getResultType()))
6599 return true;
6600 return false;
6601}
6602
6604 assert(ArgInfo && "invalid TypeSourceInfo");
6605 QualType Arg = ArgInfo->getType();
6606 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6607 QualType CanonArg = Context.getCanonicalType(Arg);
6608
6609 if (CanonArg->isVariablyModifiedType()) {
6610 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6611 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6612 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6613 }
6614
6615 // C++03 [temp.arg.type]p2:
6616 // A local type, a type with no linkage, an unnamed type or a type
6617 // compounded from any of these types shall not be used as a
6618 // template-argument for a template type-parameter.
6619 //
6620 // C++11 allows these, and even in C++03 we allow them as an extension with
6621 // a warning.
6622 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6623 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6624 (void)Finder.Visit(CanonArg);
6625 }
6626
6627 return false;
6628}
6629
6635
6636/// Determine whether the given template argument is a null pointer
6637/// value of the appropriate type.
6640 QualType ParamType, Expr *Arg,
6641 Decl *Entity = nullptr) {
6642 if (Arg->isValueDependent() || Arg->isTypeDependent())
6643 return NPV_NotNullPointer;
6644
6645 // dllimport'd entities aren't constant but are available inside of template
6646 // arguments.
6647 if (Entity && Entity->hasAttr<DLLImportAttr>())
6648 return NPV_NotNullPointer;
6649
6650 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6651 llvm_unreachable(
6652 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6653
6654 if (!S.getLangOpts().CPlusPlus11)
6655 return NPV_NotNullPointer;
6656
6657 // Determine whether we have a constant expression.
6659 if (ArgRV.isInvalid())
6660 return NPV_Error;
6661 Arg = ArgRV.get();
6662
6663 Expr::EvalResult EvalResult;
6665 EvalResult.Diag = &Notes;
6666 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6667 EvalResult.HasSideEffects) {
6668 SourceLocation DiagLoc = Arg->getExprLoc();
6669
6670 // If our only note is the usual "invalid subexpression" note, just point
6671 // the caret at its location rather than producing an essentially
6672 // redundant note.
6673 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6674 diag::note_invalid_subexpr_in_const_expr) {
6675 DiagLoc = Notes[0].first;
6676 Notes.clear();
6677 }
6678
6679 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6680 << Arg->getType() << Arg->getSourceRange();
6681 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6682 S.Diag(Notes[I].first, Notes[I].second);
6683
6685 return NPV_Error;
6686 }
6687
6688 // C++11 [temp.arg.nontype]p1:
6689 // - an address constant expression of type std::nullptr_t
6690 if (Arg->getType()->isNullPtrType())
6691 return NPV_NullPointer;
6692
6693 // - a constant expression that evaluates to a null pointer value (4.10); or
6694 // - a constant expression that evaluates to a null member pointer value
6695 // (4.11); or
6696 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6697 (EvalResult.Val.isMemberPointer() &&
6698 !EvalResult.Val.getMemberPointerDecl())) {
6699 // If our expression has an appropriate type, we've succeeded.
6700 bool ObjCLifetimeConversion;
6701 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6702 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6703 ObjCLifetimeConversion))
6704 return NPV_NullPointer;
6705
6706 // The types didn't match, but we know we got a null pointer; complain,
6707 // then recover as if the types were correct.
6708 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6709 << Arg->getType() << ParamType << Arg->getSourceRange();
6711 return NPV_NullPointer;
6712 }
6713
6714 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6715 // We found a pointer that isn't null, but doesn't refer to an object.
6716 // We could just return NPV_NotNullPointer, but we can print a better
6717 // message with the information we have here.
6718 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6719 << EvalResult.Val.getAsString(S.Context, ParamType);
6721 return NPV_Error;
6722 }
6723
6724 // If we don't have a null pointer value, but we do have a NULL pointer
6725 // constant, suggest a cast to the appropriate type.
6727 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6728 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6729 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6731 ")");
6733 return NPV_NullPointer;
6734 }
6735
6736 // FIXME: If we ever want to support general, address-constant expressions
6737 // as non-type template arguments, we should return the ExprResult here to
6738 // be interpreted by the caller.
6739 return NPV_NotNullPointer;
6740}
6741
6742/// Checks whether the given template argument is compatible with its
6743/// template parameter.
6744static bool
6746 QualType ParamType, Expr *ArgIn,
6747 Expr *Arg, QualType ArgType) {
6748 bool ObjCLifetimeConversion;
6749 if (ParamType->isPointerType() &&
6750 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6751 S.IsQualificationConversion(ArgType, ParamType, false,
6752 ObjCLifetimeConversion)) {
6753 // For pointer-to-object types, qualification conversions are
6754 // permitted.
6755 } else {
6756 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6757 if (!ParamRef->getPointeeType()->isFunctionType()) {
6758 // C++ [temp.arg.nontype]p5b3:
6759 // For a non-type template-parameter of type reference to
6760 // object, no conversions apply. The type referred to by the
6761 // reference may be more cv-qualified than the (otherwise
6762 // identical) type of the template- argument. The
6763 // template-parameter is bound directly to the
6764 // template-argument, which shall be an lvalue.
6765
6766 // FIXME: Other qualifiers?
6767 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6768 unsigned ArgQuals = ArgType.getCVRQualifiers();
6769
6770 if ((ParamQuals | ArgQuals) != ParamQuals) {
6771 S.Diag(Arg->getBeginLoc(),
6772 diag::err_template_arg_ref_bind_ignores_quals)
6773 << ParamType << Arg->getType() << Arg->getSourceRange();
6775 return true;
6776 }
6777 }
6778 }
6779
6780 // At this point, the template argument refers to an object or
6781 // function with external linkage. We now need to check whether the
6782 // argument and parameter types are compatible.
6783 if (!S.Context.hasSameUnqualifiedType(ArgType,
6784 ParamType.getNonReferenceType())) {
6785 // We can't perform this conversion or binding.
6786 if (ParamType->isReferenceType())
6787 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6788 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6789 else
6790 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6791 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6793 return true;
6794 }
6795 }
6796
6797 return false;
6798}
6799
6800/// Checks whether the given template argument is the address
6801/// of an object or function according to C++ [temp.arg.nontype]p1.
6803 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6804 bool IsSpecified, TemplateArgument &SugaredConverted,
6805 TemplateArgument &CanonicalConverted) {
6806 Expr *Arg = ArgIn;
6807 QualType ArgType = Arg->getType();
6808
6809 bool AddressTaken = false;
6810 SourceLocation AddrOpLoc;
6811 if (S.getLangOpts().MicrosoftExt) {
6812 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6813 // dereference and address-of operators.
6814 Arg = Arg->IgnoreParenCasts();
6815
6816 bool ExtWarnMSTemplateArg = false;
6817 UnaryOperatorKind FirstOpKind;
6818 SourceLocation FirstOpLoc;
6819 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6820 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6821 if (UnOpKind == UO_Deref)
6822 ExtWarnMSTemplateArg = true;
6823 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6824 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6825 if (!AddrOpLoc.isValid()) {
6826 FirstOpKind = UnOpKind;
6827 FirstOpLoc = UnOp->getOperatorLoc();
6828 }
6829 } else
6830 break;
6831 }
6832 if (FirstOpLoc.isValid()) {
6833 if (ExtWarnMSTemplateArg)
6834 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6835 << ArgIn->getSourceRange();
6836
6837 if (FirstOpKind == UO_AddrOf)
6838 AddressTaken = true;
6839 else if (Arg->getType()->isPointerType()) {
6840 // We cannot let pointers get dereferenced here, that is obviously not a
6841 // constant expression.
6842 assert(FirstOpKind == UO_Deref);
6843 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6844 << Arg->getSourceRange();
6845 }
6846 }
6847 } else {
6848 // See through any implicit casts we added to fix the type.
6849 // Also ignore parentheses for deduced template arguments.
6850 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6851
6852 // C++ [temp.arg.nontype]p1:
6853 //
6854 // A template-argument for a non-type, non-template
6855 // template-parameter shall be one of: [...]
6856 //
6857 // -- the address of an object or function with external
6858 // linkage, including function templates and function
6859 // template-ids but excluding non-static class members,
6860 // expressed as & id-expression where the & is optional if
6861 // the name refers to a function or array, or if the
6862 // corresponding template-parameter is a reference; or
6863
6864 // In C++98/03 mode, give an extension warning on any extra parentheses.
6865 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6866 if (IsSpecified) {
6867 bool ExtraParens = false;
6868 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6869 if (!ExtraParens) {
6870 S.DiagCompat(Arg->getBeginLoc(),
6871 diag_compat::template_arg_extra_parens)
6872 << Arg->getSourceRange();
6873 ExtraParens = true;
6874 }
6875
6876 Arg = Parens->getSubExpr();
6877 }
6878 }
6879
6880 while (SubstNonTypeTemplateParmExpr *subst =
6881 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6882 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6883
6884 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6885 if (UnOp->getOpcode() == UO_AddrOf) {
6886 Arg = UnOp->getSubExpr();
6887 AddressTaken = true;
6888 AddrOpLoc = UnOp->getOperatorLoc();
6889 }
6890 }
6891
6892 while (SubstNonTypeTemplateParmExpr *subst =
6893 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6894 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6895 }
6896
6897 ValueDecl *Entity = nullptr;
6898 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6899 Entity = DRE->getDecl();
6900 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6901 Entity = CUE->getGuidDecl();
6902
6903 // If our parameter has pointer type, check for a null template value.
6904 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6905 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6906 Entity)) {
6907 case NPV_NullPointer:
6908 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6909 SugaredConverted = TemplateArgument(ParamType,
6910 /*isNullPtr=*/true);
6911 CanonicalConverted =
6913 /*isNullPtr=*/true);
6914 return false;
6915
6916 case NPV_Error:
6917 return true;
6918
6919 case NPV_NotNullPointer:
6920 break;
6921 }
6922 }
6923
6924 // Stop checking the precise nature of the argument if it is value dependent,
6925 // it should be checked when instantiated.
6926 if (Arg->isValueDependent()) {
6927 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6928 CanonicalConverted =
6929 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6930 return false;
6931 }
6932
6933 if (!Entity) {
6934 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6935 << Arg->getSourceRange();
6937 return true;
6938 }
6939
6940 // Cannot refer to non-static data members
6941 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6942 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6943 << Entity << Arg->getSourceRange();
6945 return true;
6946 }
6947
6948 // Cannot refer to non-static member functions
6949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6950 if (!Method->isStatic()) {
6951 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6952 << Method << Arg->getSourceRange();
6954 return true;
6955 }
6956 }
6957
6958 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6959 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6960 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6961
6962 // A non-type template argument must refer to an object or function.
6963 if (!Func && !Var && !Guid) {
6964 // We found something, but we don't know specifically what it is.
6965 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6966 << Arg->getSourceRange();
6967 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6968 return true;
6969 }
6970
6971 // Address / reference template args must have external linkage in C++98.
6972 if (Entity->getFormalLinkage() == Linkage::Internal) {
6973 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_object_internal)
6974 << !Func << Entity << Arg->getSourceRange();
6975 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6976 << !Func;
6977 } else if (!Entity->hasLinkage()) {
6978 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6979 << !Func << Entity << Arg->getSourceRange();
6980 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6981 << !Func;
6982 return true;
6983 }
6984
6985 if (Var) {
6986 // A value of reference type is not an object.
6987 if (Var->getType()->isReferenceType()) {
6988 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6989 << Var->getType() << Arg->getSourceRange();
6991 return true;
6992 }
6993
6994 // A template argument must have static storage duration.
6995 if (Var->getTLSKind()) {
6996 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6997 << Arg->getSourceRange();
6998 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6999 return true;
7000 }
7001 }
7002
7003 if (AddressTaken && ParamType->isReferenceType()) {
7004 // If we originally had an address-of operator, but the
7005 // parameter has reference type, complain and (if things look
7006 // like they will work) drop the address-of operator.
7007 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7008 ParamType.getNonReferenceType())) {
7009 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7010 << ParamType;
7012 return true;
7013 }
7014
7015 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7016 << ParamType
7017 << FixItHint::CreateRemoval(AddrOpLoc);
7019
7020 ArgType = Entity->getType();
7021 }
7022
7023 // If the template parameter has pointer type, either we must have taken the
7024 // address or the argument must decay to a pointer.
7025 if (!AddressTaken && ParamType->isPointerType()) {
7026 if (Func) {
7027 // Function-to-pointer decay.
7028 ArgType = S.Context.getPointerType(Func->getType());
7029 } else if (Entity->getType()->isArrayType()) {
7030 // Array-to-pointer decay.
7031 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7032 } else {
7033 // If the template parameter has pointer type but the address of
7034 // this object was not taken, complain and (possibly) recover by
7035 // taking the address of the entity.
7036 ArgType = S.Context.getPointerType(Entity->getType());
7037 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7038 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7039 << ParamType;
7041 return true;
7042 }
7043
7044 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7045 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7046
7048 }
7049 }
7050
7051 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7052 Arg, ArgType))
7053 return true;
7054
7055 // Create the template argument.
7056 SugaredConverted = TemplateArgument(Entity, ParamType);
7057 CanonicalConverted =
7059 S.Context.getCanonicalType(ParamType));
7060 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7061 return false;
7062}
7063
7064/// Checks whether the given template argument is a pointer to
7065/// member constant according to C++ [temp.arg.nontype]p1.
7067 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7068 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7069 bool Invalid = false;
7070
7071 Expr *Arg = ResultArg;
7072 bool ObjCLifetimeConversion;
7073
7074 // C++ [temp.arg.nontype]p1:
7075 //
7076 // A template-argument for a non-type, non-template
7077 // template-parameter shall be one of: [...]
7078 //
7079 // -- a pointer to member expressed as described in 5.3.1.
7080 DeclRefExpr *DRE = nullptr;
7081
7082 // In C++98/03 mode, give an extension warning on any extra parentheses.
7083 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7084 bool ExtraParens = false;
7085 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7086 if (!Invalid && !ExtraParens) {
7087 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7088 << Arg->getSourceRange();
7089 ExtraParens = true;
7090 }
7091
7092 Arg = Parens->getSubExpr();
7093 }
7094
7095 while (SubstNonTypeTemplateParmExpr *subst =
7096 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7097 Arg = subst->getReplacement()->IgnoreImpCasts();
7098
7099 // A pointer-to-member constant written &Class::member.
7100 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7101 if (UnOp->getOpcode() == UO_AddrOf) {
7102 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7103 if (DRE && !DRE->getQualifier())
7104 DRE = nullptr;
7105 }
7106 }
7107 // A constant of pointer-to-member type.
7108 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7109 ValueDecl *VD = DRE->getDecl();
7110 if (VD->getType()->isMemberPointerType()) {
7112 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7113 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7114 CanonicalConverted =
7115 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7116 } else {
7117 SugaredConverted = TemplateArgument(VD, ParamType);
7118 CanonicalConverted =
7120 S.Context.getCanonicalType(ParamType));
7121 }
7122 return Invalid;
7123 }
7124 }
7125
7126 DRE = nullptr;
7127 }
7128
7129 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7130
7131 // Check for a null pointer value.
7132 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7133 Entity)) {
7134 case NPV_Error:
7135 return true;
7136 case NPV_NullPointer:
7137 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7138 SugaredConverted = TemplateArgument(ParamType,
7139 /*isNullPtr*/ true);
7140 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7141 /*isNullPtr*/ true);
7142 return false;
7143 case NPV_NotNullPointer:
7144 break;
7145 }
7146
7147 if (S.IsQualificationConversion(ResultArg->getType(),
7148 ParamType.getNonReferenceType(), false,
7149 ObjCLifetimeConversion)) {
7150 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7151 ResultArg->getValueKind())
7152 .get();
7153 } else if (!S.Context.hasSameUnqualifiedType(
7154 ResultArg->getType(), ParamType.getNonReferenceType())) {
7155 // We can't perform this conversion.
7156 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7157 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7159 return true;
7160 }
7161
7162 if (!DRE)
7163 return S.Diag(Arg->getBeginLoc(),
7164 diag::err_template_arg_not_pointer_to_member_form)
7165 << Arg->getSourceRange();
7166
7167 if (isa<FieldDecl>(DRE->getDecl()) ||
7169 isa<CXXMethodDecl>(DRE->getDecl())) {
7170 assert((isa<FieldDecl>(DRE->getDecl()) ||
7173 ->isImplicitObjectMemberFunction()) &&
7174 "Only non-static member pointers can make it here");
7175
7176 // Okay: this is the address of a non-static member, and therefore
7177 // a member pointer constant.
7178 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7179 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7180 CanonicalConverted =
7181 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7182 } else {
7183 ValueDecl *D = DRE->getDecl();
7184 SugaredConverted = TemplateArgument(D, ParamType);
7185 CanonicalConverted =
7187 S.Context.getCanonicalType(ParamType));
7188 }
7189 return Invalid;
7190 }
7191
7192 // We found something else, but we don't know specifically what it is.
7193 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7194 << Arg->getSourceRange();
7195 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7196 return true;
7197}
7198
7199/// Check a template argument against its corresponding
7200/// non-type template parameter.
7201///
7202/// This routine implements the semantics of C++ [temp.arg.nontype].
7203/// If an error occurred, it returns ExprError(); otherwise, it
7204/// returns the converted template argument. \p ParamType is the
7205/// type of the non-type template parameter after it has been instantiated.
7207 Expr *Arg,
7208 TemplateArgument &SugaredConverted,
7209 TemplateArgument &CanonicalConverted,
7210 bool StrictCheck,
7212 SourceLocation StartLoc = Arg->getBeginLoc();
7213 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7214 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7215 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7216 DeductionArg = NewDeductionArg;
7217 if (ArgPE) {
7218 // Recreate a pack expansion if we unwrapped one.
7219 Arg = new (Context) PackExpansionExpr(
7220 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7221 } else {
7222 Arg = DeductionArg;
7223 }
7224 };
7225
7226 // If the parameter type somehow involves auto, deduce the type now.
7227 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7228 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7229 if (IsDeduced) {
7230 // When checking a deduced template argument, deduce from its type even if
7231 // the type is dependent, in order to check the types of non-type template
7232 // arguments line up properly in partial ordering.
7233 TypeSourceInfo *TSI =
7234 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7236 InitializedEntity Entity =
7239 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7240 Expr *Inits[1] = {DeductionArg};
7241 ParamType =
7243 if (ParamType.isNull())
7244 return ExprError();
7245 } else {
7246 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7247 Param->getTemplateDepth() + 1);
7248 ParamType = QualType();
7250 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7251 /*DependentDeduction=*/true,
7252 // We do not check constraints right now because the
7253 // immediately-declared constraint of the auto type is
7254 // also an associated constraint, and will be checked
7255 // along with the other associated constraints after
7256 // checking the template argument list.
7257 /*IgnoreConstraints=*/true);
7259 ParamType = TSI->getType();
7260 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7262 return ExprError();
7263 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7264 Diag(Arg->getExprLoc(),
7265 diag::err_non_type_template_parm_type_deduction_failure)
7266 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7267 << Arg->getSourceRange();
7269 return ExprError();
7270 }
7271 ParamType = SubstAutoTypeDependent(ParamType);
7272 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7273 }
7274 }
7275 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7276 // an error. The error message normally references the parameter
7277 // declaration, but here we'll pass the argument location because that's
7278 // where the parameter type is deduced.
7279 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7280 if (ParamType.isNull()) {
7282 return ExprError();
7283 }
7284 }
7285
7286 // We should have already dropped all cv-qualifiers by now.
7287 assert(!ParamType.hasQualifiers() &&
7288 "non-type template parameter type cannot be qualified");
7289
7290 // If either the parameter has a dependent type or the argument is
7291 // type-dependent, there's nothing we can check now.
7292 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7293 // Force the argument to the type of the parameter to maintain invariants.
7294 if (!IsDeduced) {
7296 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7297 ParamType->isLValueReferenceType() ? VK_LValue
7298 : ParamType->isRValueReferenceType() ? VK_XValue
7299 : VK_PRValue);
7300 if (E.isInvalid())
7301 return ExprError();
7302 setDeductionArg(E.get());
7303 }
7304 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7305 CanonicalConverted = TemplateArgument(
7306 Context.getCanonicalTemplateArgument(SugaredConverted));
7307 return Arg;
7308 }
7309
7310 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7311 if (CTAK == CTAK_Deduced && !StrictCheck &&
7312 (ParamType->isReferenceType()
7313 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7314 DeductionArg->getType())
7315 : !Context.hasSameUnqualifiedType(ParamType,
7316 DeductionArg->getType()))) {
7317 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7318 // we should actually be checking the type of the template argument in P,
7319 // not the type of the template argument deduced from A, against the
7320 // template parameter type.
7321 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7322 << Arg->getType() << ParamType.getUnqualifiedType();
7324 return ExprError();
7325 }
7326
7327 // If the argument is a pack expansion, we don't know how many times it would
7328 // expand. If we continue checking the argument, this will make the template
7329 // definition ill-formed if it would be ill-formed for any number of
7330 // expansions during instantiation time. When partial ordering or matching
7331 // template template parameters, this is exactly what we want. Otherwise, the
7332 // normal template rules apply: we accept the template if it would be valid
7333 // for any number of expansions (i.e. none).
7334 if (ArgPE && !StrictCheck) {
7335 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7336 CanonicalConverted = TemplateArgument(
7337 Context.getCanonicalTemplateArgument(SugaredConverted));
7338 return Arg;
7339 }
7340
7341 // Avoid making a copy when initializing a template parameter of class type
7342 // from a template parameter object of the same type. This is going beyond
7343 // the standard, but is required for soundness: in
7344 // template<A a> struct X { X *p; X<a> *q; };
7345 // ... we need p and q to have the same type.
7346 //
7347 // Similarly, don't inject a call to a copy constructor when initializing
7348 // from a template parameter of the same type.
7349 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7350 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7351 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7352 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7353 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7354
7355 SugaredConverted = TemplateArgument(TPO, ParamType);
7356 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7357 ParamType.getCanonicalType());
7358 return Arg;
7359 }
7361 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7362 CanonicalConverted =
7363 Context.getCanonicalTemplateArgument(SugaredConverted);
7364 return Arg;
7365 }
7366 }
7367
7368 // The initialization of the parameter from the argument is
7369 // a constant-evaluated context.
7372
7373 bool IsConvertedConstantExpression = true;
7374 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7376 StartLoc, /*DirectInit=*/false, DeductionArg);
7377 Expr *Inits[1] = {DeductionArg};
7378 InitializedEntity Entity =
7380 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7381 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7382 if (Result.isInvalid() || !Result.get())
7383 return ExprError();
7385 if (Result.isInvalid() || !Result.get())
7386 return ExprError();
7387 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7388 /*DiscardedValue=*/false,
7389 /*IsConstexpr=*/true,
7390 /*IsTemplateArgument=*/true)
7391 .get());
7392 IsConvertedConstantExpression = false;
7393 }
7394
7395 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7396 // C++17 [temp.arg.nontype]p1:
7397 // A template-argument for a non-type template parameter shall be
7398 // a converted constant expression of the type of the template-parameter.
7399 APValue Value;
7400 ExprResult ArgResult;
7401 if (IsConvertedConstantExpression) {
7403 DeductionArg, ParamType,
7404 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7405 assert(!ArgResult.isUnset());
7406 if (ArgResult.isInvalid()) {
7408 return ExprError();
7409 }
7410 } else {
7411 ArgResult = DeductionArg;
7412 }
7413
7414 // For a value-dependent argument, CheckConvertedConstantExpression is
7415 // permitted (and expected) to be unable to determine a value.
7416 if (ArgResult.get()->isValueDependent()) {
7417 setDeductionArg(ArgResult.get());
7418 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7419 CanonicalConverted =
7420 Context.getCanonicalTemplateArgument(SugaredConverted);
7421 return Arg;
7422 }
7423
7424 APValue PreNarrowingValue;
7426 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7427 false, PreNarrowingValue);
7428 if (ArgResult.isInvalid())
7429 return ExprError();
7430 setDeductionArg(ArgResult.get());
7431
7432 if (Value.isLValue()) {
7433 APValue::LValueBase Base = Value.getLValueBase();
7434 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7435 // For a non-type template-parameter of pointer or reference type,
7436 // the value of the constant expression shall not refer to
7437 assert(ParamType->isPointerOrReferenceType() ||
7438 ParamType->isNullPtrType());
7439 // -- a temporary object
7440 // -- a string literal
7441 // -- the result of a typeid expression, or
7442 // -- a predefined __func__ variable
7443 if (Base &&
7444 (!VD ||
7446 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7447 << Arg->getSourceRange();
7448 return ExprError();
7449 }
7450
7451 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7452 VD->getType()->isArrayType() &&
7453 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7454 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7455 if (ArgPE) {
7456 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7457 CanonicalConverted =
7458 Context.getCanonicalTemplateArgument(SugaredConverted);
7459 } else {
7460 SugaredConverted = TemplateArgument(VD, ParamType);
7461 CanonicalConverted =
7462 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7463 ParamType.getCanonicalType());
7464 }
7465 return Arg;
7466 }
7467
7468 // -- a subobject [until C++20]
7469 if (!getLangOpts().CPlusPlus20) {
7470 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7471 Value.isLValueOnePastTheEnd()) {
7472 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7473 << Value.getAsString(Context, ParamType);
7474 return ExprError();
7475 }
7476 assert((VD || !ParamType->isReferenceType()) &&
7477 "null reference should not be a constant expression");
7478 assert((!VD || !ParamType->isNullPtrType()) &&
7479 "non-null value of type nullptr_t?");
7480 }
7481 }
7482
7483 if (Value.isAddrLabelDiff())
7484 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7485
7486 if (ArgPE) {
7487 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7488 CanonicalConverted =
7489 Context.getCanonicalTemplateArgument(SugaredConverted);
7490 } else {
7491 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7492 CanonicalConverted =
7494 }
7495 return Arg;
7496 }
7497
7498 // These should have all been handled above using the C++17 rules.
7499 assert(!ArgPE && !StrictCheck);
7500
7501 // C++ [temp.arg.nontype]p5:
7502 // The following conversions are performed on each expression used
7503 // as a non-type template-argument. If a non-type
7504 // template-argument cannot be converted to the type of the
7505 // corresponding template-parameter then the program is
7506 // ill-formed.
7507 if (ParamType->isIntegralOrEnumerationType()) {
7508 // C++11:
7509 // -- for a non-type template-parameter of integral or
7510 // enumeration type, conversions permitted in a converted
7511 // constant expression are applied.
7512 //
7513 // C++98:
7514 // -- for a non-type template-parameter of integral or
7515 // enumeration type, integral promotions (4.5) and integral
7516 // conversions (4.7) are applied.
7517
7518 if (getLangOpts().CPlusPlus11) {
7519 // C++ [temp.arg.nontype]p1:
7520 // A template-argument for a non-type, non-template template-parameter
7521 // shall be one of:
7522 //
7523 // -- for a non-type template-parameter of integral or enumeration
7524 // type, a converted constant expression of the type of the
7525 // template-parameter; or
7526 llvm::APSInt Value;
7528 Arg, ParamType, Value, CCEKind::TemplateArg);
7529 if (ArgResult.isInvalid())
7530 return ExprError();
7531 Arg = ArgResult.get();
7532
7533 // We can't check arbitrary value-dependent arguments.
7534 if (Arg->isValueDependent()) {
7535 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7536 CanonicalConverted =
7537 Context.getCanonicalTemplateArgument(SugaredConverted);
7538 return Arg;
7539 }
7540
7541 // Widen the argument value to sizeof(parameter type). This is almost
7542 // always a no-op, except when the parameter type is bool. In
7543 // that case, this may extend the argument from 1 bit to 8 bits.
7544 QualType IntegerType = ParamType;
7545 if (const auto *ED = IntegerType->getAsEnumDecl())
7546 IntegerType = ED->getIntegerType();
7547 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7548 ? Context.getIntWidth(IntegerType)
7549 : Context.getTypeSize(IntegerType));
7550
7551 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7552 CanonicalConverted =
7553 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7554 return Arg;
7555 }
7556
7557 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7558 if (ArgResult.isInvalid())
7559 return ExprError();
7560 Arg = ArgResult.get();
7561
7562 QualType ArgType = Arg->getType();
7563
7564 // C++ [temp.arg.nontype]p1:
7565 // A template-argument for a non-type, non-template
7566 // template-parameter shall be one of:
7567 //
7568 // -- an integral constant-expression of integral or enumeration
7569 // type; or
7570 // -- the name of a non-type template-parameter; or
7571 llvm::APSInt Value;
7572 if (!ArgType->isIntegralOrEnumerationType()) {
7573 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7574 << ArgType << Arg->getSourceRange();
7576 return ExprError();
7577 }
7578 if (!Arg->isValueDependent()) {
7579 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7580 QualType T;
7581
7582 public:
7583 TmplArgICEDiagnoser(QualType T) : T(T) { }
7584
7585 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7586 SourceLocation Loc) override {
7587 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7588 }
7589 } Diagnoser(ArgType);
7590
7591 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7592 if (!Arg)
7593 return ExprError();
7594 }
7595
7596 // From here on out, all we care about is the unqualified form
7597 // of the argument type.
7598 ArgType = ArgType.getUnqualifiedType();
7599
7600 // Try to convert the argument to the parameter's type.
7601 if (Context.hasSameType(ParamType, ArgType)) {
7602 // Okay: no conversion necessary
7603 } else if (ParamType->isBooleanType()) {
7604 // This is an integral-to-boolean conversion.
7605 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7606 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7607 !ParamType->isEnumeralType()) {
7608 // This is an integral promotion or conversion.
7609 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7610 } else {
7611 // We can't perform this conversion.
7612 Diag(StartLoc, diag::err_template_arg_not_convertible)
7613 << Arg->getType() << ParamType << Arg->getSourceRange();
7615 return ExprError();
7616 }
7617
7618 // Add the value of this argument to the list of converted
7619 // arguments. We use the bitwidth and signedness of the template
7620 // parameter.
7621 if (Arg->isValueDependent()) {
7622 // The argument is value-dependent. Create a new
7623 // TemplateArgument with the converted expression.
7624 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7625 CanonicalConverted =
7626 Context.getCanonicalTemplateArgument(SugaredConverted);
7627 return Arg;
7628 }
7629
7630 QualType IntegerType = ParamType;
7631 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7632 IntegerType = ED->getIntegerType();
7633 }
7634
7635 if (ParamType->isBooleanType()) {
7636 // Value must be zero or one.
7637 Value = Value != 0;
7638 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7639 if (Value.getBitWidth() != AllowedBits)
7640 Value = Value.extOrTrunc(AllowedBits);
7641 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7642 } else {
7643 llvm::APSInt OldValue = Value;
7644
7645 // Coerce the template argument's value to the value it will have
7646 // based on the template parameter's type.
7647 unsigned AllowedBits = IntegerType->isBitIntType()
7648 ? Context.getIntWidth(IntegerType)
7649 : Context.getTypeSize(IntegerType);
7650 if (Value.getBitWidth() != AllowedBits)
7651 Value = Value.extOrTrunc(AllowedBits);
7652 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7653
7654 // Complain if an unsigned parameter received a negative value.
7655 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7656 (OldValue.isSigned() && OldValue.isNegative())) {
7657 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7658 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7659 << Arg->getSourceRange();
7661 }
7662
7663 // Complain if we overflowed the template parameter's type.
7664 unsigned RequiredBits;
7665 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7666 RequiredBits = OldValue.getActiveBits();
7667 else if (OldValue.isUnsigned())
7668 RequiredBits = OldValue.getActiveBits() + 1;
7669 else
7670 RequiredBits = OldValue.getSignificantBits();
7671 if (RequiredBits > AllowedBits) {
7672 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7673 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7674 << Arg->getSourceRange();
7676 }
7677 }
7678
7679 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7680 SugaredConverted = TemplateArgument(Context, Value, T);
7681 CanonicalConverted =
7682 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7683 return Arg;
7684 }
7685
7686 QualType ArgType = Arg->getType();
7687 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7688 bool IsSpecified = CTAK == CTAK_Specified;
7689
7690 // Handle pointer-to-function, reference-to-function, and
7691 // pointer-to-member-function all in (roughly) the same way.
7692 if (// -- For a non-type template-parameter of type pointer to
7693 // function, only the function-to-pointer conversion (4.3) is
7694 // applied. If the template-argument represents a set of
7695 // overloaded functions (or a pointer to such), the matching
7696 // function is selected from the set (13.4).
7697 (ParamType->isPointerType() &&
7698 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7699 // -- For a non-type template-parameter of type reference to
7700 // function, no conversions apply. If the template-argument
7701 // represents a set of overloaded functions, the matching
7702 // function is selected from the set (13.4).
7703 (ParamType->isReferenceType() &&
7704 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7705 // -- For a non-type template-parameter of type pointer to
7706 // member function, no conversions apply. If the
7707 // template-argument represents a set of overloaded member
7708 // functions, the matching member function is selected from
7709 // the set (13.4).
7710 (ParamType->isMemberPointerType() &&
7711 ParamType->castAs<MemberPointerType>()->getPointeeType()
7712 ->isFunctionType())) {
7713
7714 if (Arg->getType() == Context.OverloadTy) {
7715 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7716 true,
7717 FoundResult)) {
7718 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7719 return ExprError();
7720
7721 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7722 if (Res.isInvalid())
7723 return ExprError();
7724 Arg = Res.get();
7725 ArgType = Arg->getType();
7726 } else
7727 return ExprError();
7728 }
7729
7730 if (!ParamType->isMemberPointerType()) {
7732 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7733 CanonicalConverted))
7734 return ExprError();
7735 return Arg;
7736 }
7737
7739 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7740 return ExprError();
7741 return Arg;
7742 }
7743
7744 if (ParamType->isPointerType()) {
7745 // -- for a non-type template-parameter of type pointer to
7746 // object, qualification conversions (4.4) and the
7747 // array-to-pointer conversion (4.2) are applied.
7748 // C++0x also allows a value of std::nullptr_t.
7749 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7750 "Only object pointers allowed here");
7751
7753 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7754 CanonicalConverted))
7755 return ExprError();
7756 return Arg;
7757 }
7758
7759 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7760 // -- For a non-type template-parameter of type reference to
7761 // object, no conversions apply. The type referred to by the
7762 // reference may be more cv-qualified than the (otherwise
7763 // identical) type of the template-argument. The
7764 // template-parameter is bound directly to the
7765 // template-argument, which must be an lvalue.
7766 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7767 "Only object references allowed here");
7768
7769 if (Arg->getType() == Context.OverloadTy) {
7771 ParamRefType->getPointeeType(),
7772 true,
7773 FoundResult)) {
7774 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7775 return ExprError();
7776 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7777 if (Res.isInvalid())
7778 return ExprError();
7779 Arg = Res.get();
7780 ArgType = Arg->getType();
7781 } else
7782 return ExprError();
7783 }
7784
7786 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7787 CanonicalConverted))
7788 return ExprError();
7789 return Arg;
7790 }
7791
7792 // Deal with parameters of type std::nullptr_t.
7793 if (ParamType->isNullPtrType()) {
7794 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7795 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7796 CanonicalConverted =
7797 Context.getCanonicalTemplateArgument(SugaredConverted);
7798 return Arg;
7799 }
7800
7801 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7802 case NPV_NotNullPointer:
7803 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7804 << Arg->getType() << ParamType;
7806 return ExprError();
7807
7808 case NPV_Error:
7809 return ExprError();
7810
7811 case NPV_NullPointer:
7812 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7813 SugaredConverted = TemplateArgument(ParamType,
7814 /*isNullPtr=*/true);
7815 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7816 /*isNullPtr=*/true);
7817 return Arg;
7818 }
7819 }
7820
7821 // -- For a non-type template-parameter of type pointer to data
7822 // member, qualification conversions (4.4) are applied.
7823 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7824
7826 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7827 return ExprError();
7828 return Arg;
7829}
7830
7834
7837 const TemplateArgumentLoc &Arg) {
7838 // C++0x [temp.arg.template]p1:
7839 // A template-argument for a template template-parameter shall be
7840 // the name of a class template or an alias template, expressed as an
7841 // id-expression. When the template-argument names a class template, only
7842 // primary class templates are considered when matching the
7843 // template template argument with the corresponding parameter;
7844 // partial specializations are not considered even if their
7845 // parameter lists match that of the template template parameter.
7846 //
7847
7849 unsigned DiagFoundKind = 0;
7850
7851 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7852 switch (TTP->templateParameterKind()) {
7854 DiagFoundKind = 3;
7855 break;
7857 DiagFoundKind = 2;
7858 break;
7859 default:
7860 DiagFoundKind = 1;
7861 break;
7862 }
7863 Kind = TTP->templateParameterKind();
7864 } else if (isa<ConceptDecl>(Template)) {
7866 DiagFoundKind = 3;
7867 } else if (isa<FunctionTemplateDecl>(Template)) {
7869 DiagFoundKind = 0;
7870 } else if (isa<VarTemplateDecl>(Template)) {
7872 DiagFoundKind = 2;
7873 } else if (isa<ClassTemplateDecl>(Template) ||
7877 DiagFoundKind = 1;
7878 } else {
7879 assert(false && "Unexpected Decl");
7880 }
7881
7882 if (Kind == Param->templateParameterKind()) {
7883 return true;
7884 }
7885
7886 unsigned DiagKind = 0;
7887 switch (Param->templateParameterKind()) {
7889 DiagKind = 2;
7890 break;
7892 DiagKind = 1;
7893 break;
7894 default:
7895 DiagKind = 0;
7896 break;
7897 }
7898 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7899 << DiagKind;
7900 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7901 << DiagFoundKind << Template;
7902 return false;
7903}
7904
7905/// Check a template argument against its corresponding
7906/// template template parameter.
7907///
7908/// This routine implements the semantics of C++ [temp.arg.template].
7909/// It returns true if an error occurred, and false otherwise.
7911 TemplateParameterList *Params,
7913 bool PartialOrdering,
7914 bool *StrictPackMatch) {
7916 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7917 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7918 if (!Template) {
7919 // FIXME: Handle AssumedTemplateNames
7920 // Any dependent template name is fine.
7921 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7922 return false;
7923 }
7924
7925 if (Template->isInvalidDecl())
7926 return true;
7927
7929 return true;
7930 }
7931
7932 // C++1z [temp.arg.template]p3: (DR 150)
7933 // A template-argument matches a template template-parameter P when P
7934 // is at least as specialized as the template-argument A.
7936 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7937 PartialOrdering, StrictPackMatch))
7938 return true;
7939 // P2113
7940 // C++20[temp.func.order]p2
7941 // [...] If both deductions succeed, the partial ordering selects the
7942 // more constrained template (if one exists) as determined below.
7943 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7944 Params->getAssociatedConstraints(ParamsAC);
7945 // C++20[temp.arg.template]p3
7946 // [...] In this comparison, if P is unconstrained, the constraints on A
7947 // are not considered.
7948 if (ParamsAC.empty())
7949 return false;
7950
7951 Template->getAssociatedConstraints(TemplateAC);
7952
7953 bool IsParamAtLeastAsConstrained;
7954 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7955 IsParamAtLeastAsConstrained))
7956 return true;
7957 if (!IsParamAtLeastAsConstrained) {
7958 Diag(Arg.getLocation(),
7959 diag::err_template_template_parameter_not_at_least_as_constrained)
7960 << Template << Param << Arg.getSourceRange();
7961 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7962 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7964 TemplateAC);
7965 return true;
7966 }
7967 return false;
7968}
7969
7971 unsigned HereDiagID,
7972 unsigned ExternalDiagID) {
7973 if (Decl.getLocation().isValid())
7974 return S.Diag(Decl.getLocation(), HereDiagID);
7975
7976 SmallString<128> Str;
7977 llvm::raw_svector_ostream Out(Str);
7979 PP.TerseOutput = 1;
7980 Decl.print(Out, PP);
7981 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7982}
7983
7985 std::optional<SourceRange> ParamRange) {
7987 noteLocation(*this, Decl, diag::note_template_decl_here,
7988 diag::note_template_decl_external);
7989 if (ParamRange && ParamRange->isValid()) {
7990 assert(Decl.getLocation().isValid() &&
7991 "Parameter range has location when Decl does not");
7992 DB << *ParamRange;
7993 }
7994}
7995
7997 noteLocation(*this, Decl, diag::note_template_param_here,
7998 diag::note_template_param_external);
7999}
8000
8001/// Given a non-type template argument that refers to a
8002/// declaration and the type of its corresponding non-type template
8003/// parameter, produce an expression that properly refers to that
8004/// declaration.
8006 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
8007 // C++ [temp.param]p8:
8008 //
8009 // A non-type template-parameter of type "array of T" or
8010 // "function returning T" is adjusted to be of type "pointer to
8011 // T" or "pointer to function returning T", respectively.
8012 if (ParamType->isArrayType())
8013 ParamType = Context.getArrayDecayedType(ParamType);
8014 else if (ParamType->isFunctionType())
8015 ParamType = Context.getPointerType(ParamType);
8016
8017 // For a NULL non-type template argument, return nullptr casted to the
8018 // parameter's type.
8019 if (Arg.getKind() == TemplateArgument::NullPtr) {
8020 return ImpCastExprToType(
8021 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8022 ParamType,
8023 ParamType->getAs<MemberPointerType>()
8024 ? CK_NullToMemberPointer
8025 : CK_NullToPointer);
8026 }
8027 assert(Arg.getKind() == TemplateArgument::Declaration &&
8028 "Only declaration template arguments permitted here");
8029
8030 ValueDecl *VD = Arg.getAsDecl();
8031
8032 CXXScopeSpec SS;
8033 if (ParamType->isMemberPointerType()) {
8034 // If this is a pointer to member, we need to use a qualified name to
8035 // form a suitable pointer-to-member constant.
8036 assert(VD->getDeclContext()->isRecord() &&
8037 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8039 CanQualType ClassType =
8040 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
8041 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
8042 SS.MakeTrivial(Context, Qualifier, Loc);
8043 }
8044
8046 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8047 if (RefExpr.isInvalid())
8048 return ExprError();
8049
8050 // For a pointer, the argument declaration is the pointee. Take its address.
8051 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8052 if (ParamType->isPointerType() && !ElemT.isNull() &&
8053 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8054 // Decay an array argument if we want a pointer to its first element.
8055 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8056 if (RefExpr.isInvalid())
8057 return ExprError();
8058 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8059 // For any other pointer, take the address (or form a pointer-to-member).
8060 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8061 if (RefExpr.isInvalid())
8062 return ExprError();
8063 } else if (ParamType->isRecordType()) {
8064 assert(isa<TemplateParamObjectDecl>(VD) &&
8065 "arg for class template param not a template parameter object");
8066 // No conversions apply in this case.
8067 return RefExpr;
8068 } else {
8069 assert(ParamType->isReferenceType() &&
8070 "unexpected type for decl template argument");
8071 // If the parameter has reference type, wrap it in paretheses so that this
8072 // expression will have the correct type under `decltype`.
8073 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8074 }
8075
8076 // At this point we should have the right value category.
8077 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8078 "value kind mismatch for non-type template argument");
8079
8080 // The type of the template parameter can differ from the type of the
8081 // argument in various ways; convert it now if necessary.
8082 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8083 QualType SrcExprType = RefExpr.get()->getType();
8084 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8085 CastKind CK;
8086 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8087 IsFunctionConversion(SrcExprType, DestExprType)) {
8088 CK = CK_NoOp;
8089 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8090 CK = CK_BitCast;
8091 } else {
8092 // FIXME: Pointers to members can need conversion derived-to-base or
8093 // base-to-derived conversions. We currently don't retain enough
8094 // information to convert properly (we need to track a cast path or
8095 // subobject number in the template argument).
8096 llvm_unreachable(
8097 "unexpected conversion required for non-type template argument");
8098 }
8099 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8100 RefExpr.get()->getValueKind());
8101 }
8102
8103 return RefExpr;
8104}
8105
8106/// Construct a new expression that refers to the given
8107/// integral template argument with the given source-location
8108/// information.
8109///
8110/// This routine takes care of the mapping from an integral template
8111/// argument (which may have any integral type) to the appropriate
8112/// literal value.
8114 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8115 assert(OrigT->isIntegralOrEnumerationType());
8116
8117 // If this is an enum type that we're instantiating, we need to use an integer
8118 // type the same size as the enumerator. We don't want to build an
8119 // IntegerLiteral with enum type. The integer type of an enum type can be of
8120 // any integral type with C++11 enum classes, make sure we create the right
8121 // type of literal for it.
8122 QualType T = OrigT;
8123 if (const auto *ED = OrigT->getAsEnumDecl())
8124 T = ED->getIntegerType();
8125
8126 Expr *E;
8127 if (T->isAnyCharacterType()) {
8129 if (T->isWideCharType())
8131 else if (T->isChar8Type() && S.getLangOpts().Char8)
8133 else if (T->isChar16Type())
8135 else if (T->isChar32Type())
8137 else
8139
8140 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8141 } else if (T->isBooleanType()) {
8142 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8143 } else {
8144 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8145 }
8146
8147 if (OrigT->isEnumeralType()) {
8148 // FIXME: This is a hack. We need a better way to handle substituted
8149 // non-type template parameters.
8150 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8151 nullptr, S.CurFPFeatureOverrides(),
8152 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8153 Loc, Loc);
8154 }
8155
8156 return E;
8157}
8158
8159/// Construct a new reflect expression that refers to the given
8160/// entity with the given source-location of the reflection operator.
8162 SourceLocation CaretCaretLoc) {
8163 // TODO(Reflection): Add support for NamespaceReference, TemplateReference,
8164 // and DeclRefExpr.
8166 S.Context, CaretCaretLoc,
8167 static_cast<TypeSourceInfo *>(
8168 const_cast<void *>(RV.getReflectionOpaqueOperand())));
8169}
8170
8172 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8173 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8174 auto *ILE = new (S.Context)
8175 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8176 ILE->setType(T);
8177 return ILE;
8178 };
8179
8180 switch (Val.getKind()) {
8182 // This cannot occur in a template argument at all.
8183 case APValue::Array:
8184 case APValue::Struct:
8185 case APValue::Union:
8186 // These can only occur within a template parameter object, which is
8187 // represented as a TemplateArgument::Declaration.
8188 llvm_unreachable("unexpected template argument value");
8189
8190 case APValue::Int:
8192 Loc);
8193
8194 case APValue::Float:
8195 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8196 T, Loc);
8197
8200 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8201 Val.getFixedPoint().getScale());
8202
8203 case APValue::ComplexInt: {
8204 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8206 S, ElemT, Val.getComplexIntReal(), Loc),
8208 S, ElemT, Val.getComplexIntImag(), Loc)});
8209 }
8210
8211 case APValue::ComplexFloat: {
8212 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8213 return MakeInitList(
8215 ElemT, Loc),
8217 ElemT, Loc)});
8218 }
8219
8220 case APValue::Vector: {
8221 QualType ElemT = T->castAs<VectorType>()->getElementType();
8223 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8225 S, ElemT, Val.getVectorElt(I), Loc));
8226 return MakeInitList(Elts);
8227 }
8228
8229 case APValue::Matrix:
8230 llvm_unreachable("Matrix template argument expression not yet supported");
8231
8232 case APValue::None:
8234 llvm_unreachable("Unexpected APValue kind.");
8235 case APValue::LValue:
8237 // There isn't necessarily a valid equivalent source-level syntax for
8238 // these; in particular, a naive lowering might violate access control.
8239 // So for now we lower to a ConstantExpr holding the value, wrapped around
8240 // an OpaqueValueExpr.
8241 // FIXME: We should have a better representation for this.
8243 if (T->isReferenceType()) {
8244 T = T->getPointeeType();
8245 VK = VK_LValue;
8246 }
8247 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8248 return ConstantExpr::Create(S.Context, OVE, Val);
8249 }
8251 return BuildExpressionFromReflection(S, Val, Loc).get();
8252 }
8253 llvm_unreachable("Unhandled APValue::ValueKind enum");
8254}
8255
8258 SourceLocation Loc) {
8259 switch (Arg.getKind()) {
8265 llvm_unreachable("not a non-type template argument");
8266
8268 return Arg.getAsExpr();
8269
8273 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8274
8277 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8278
8281 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8282 }
8283 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8284}
8285
8286/// Match two template parameters within template parameter lists.
8288 Sema &S, NamedDecl *New,
8289 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8290 const NamedDecl *OldInstFrom, bool Complain,
8292 // Check the actual kind (type, non-type, template).
8293 if (Old->getKind() != New->getKind()) {
8294 if (Complain) {
8295 unsigned NextDiag = diag::err_template_param_different_kind;
8296 if (TemplateArgLoc.isValid()) {
8297 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8298 NextDiag = diag::note_template_param_different_kind;
8299 }
8300 S.Diag(New->getLocation(), NextDiag)
8301 << (Kind != Sema::TPL_TemplateMatch);
8302 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8303 << (Kind != Sema::TPL_TemplateMatch);
8304 }
8305
8306 return false;
8307 }
8308
8309 // Check that both are parameter packs or neither are parameter packs.
8310 // However, if we are matching a template template argument to a
8311 // template template parameter, the template template parameter can have
8312 // a parameter pack where the template template argument does not.
8313 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8314 if (Complain) {
8315 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8316 if (TemplateArgLoc.isValid()) {
8317 S.Diag(TemplateArgLoc,
8318 diag::err_template_arg_template_params_mismatch);
8319 NextDiag = diag::note_template_parameter_pack_non_pack;
8320 }
8321
8322 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8324 : 2;
8325 S.Diag(New->getLocation(), NextDiag)
8326 << ParamKind << New->isParameterPack();
8327 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8328 << ParamKind << Old->isParameterPack();
8329 }
8330
8331 return false;
8332 }
8333 // For non-type template parameters, check the type of the parameter.
8334 if (NonTypeTemplateParmDecl *OldNTTP =
8335 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8337
8338 // If we are matching a template template argument to a template
8339 // template parameter and one of the non-type template parameter types
8340 // is dependent, then we must wait until template instantiation time
8341 // to actually compare the arguments.
8343 (!OldNTTP->getType()->isDependentType() &&
8344 !NewNTTP->getType()->isDependentType())) {
8345 // C++20 [temp.over.link]p6:
8346 // Two [non-type] template-parameters are equivalent [if] they have
8347 // equivalent types ignoring the use of type-constraints for
8348 // placeholder types
8349 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8350 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8351 if (!S.Context.hasSameType(OldType, NewType)) {
8352 if (Complain) {
8353 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8354 if (TemplateArgLoc.isValid()) {
8355 S.Diag(TemplateArgLoc,
8356 diag::err_template_arg_template_params_mismatch);
8357 NextDiag = diag::note_template_nontype_parm_different_type;
8358 }
8359 S.Diag(NewNTTP->getLocation(), NextDiag)
8360 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8361 S.Diag(OldNTTP->getLocation(),
8362 diag::note_template_nontype_parm_prev_declaration)
8363 << OldNTTP->getType();
8364 }
8365 return false;
8366 }
8367 }
8368 }
8369 // For template template parameters, check the template parameter types.
8370 // The template parameter lists of template template
8371 // parameters must agree.
8372 else if (TemplateTemplateParmDecl *OldTTP =
8373 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8375 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8376 return false;
8378 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8379 OldTTP->getTemplateParameters(), Complain,
8382 : Kind),
8383 TemplateArgLoc))
8384 return false;
8385 }
8386
8390 const Expr *NewC = nullptr, *OldC = nullptr;
8391
8393 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8394 NewC = TC->getImmediatelyDeclaredConstraint();
8395 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8396 OldC = TC->getImmediatelyDeclaredConstraint();
8397 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8398 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8399 ->getPlaceholderTypeConstraint())
8400 NewC = E;
8401 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8402 ->getPlaceholderTypeConstraint())
8403 OldC = E;
8404 } else
8405 llvm_unreachable("unexpected template parameter type");
8406
8407 auto Diagnose = [&] {
8408 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8409 diag::err_template_different_type_constraint);
8410 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8411 diag::note_template_prev_declaration) << /*declaration*/0;
8412 };
8413
8414 if (!NewC != !OldC) {
8415 if (Complain)
8416 Diagnose();
8417 return false;
8418 }
8419
8420 if (NewC) {
8421 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8422 NewC)) {
8423 if (Complain)
8424 Diagnose();
8425 return false;
8426 }
8427 }
8428 }
8429
8430 return true;
8431}
8432
8433/// Diagnose a known arity mismatch when comparing template argument
8434/// lists.
8435static
8440 SourceLocation TemplateArgLoc) {
8441 unsigned NextDiag = diag::err_template_param_list_different_arity;
8442 if (TemplateArgLoc.isValid()) {
8443 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8444 NextDiag = diag::note_template_param_list_different_arity;
8445 }
8446 S.Diag(New->getTemplateLoc(), NextDiag)
8447 << (New->size() > Old->size())
8448 << (Kind != Sema::TPL_TemplateMatch)
8449 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8450 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8451 << (Kind != Sema::TPL_TemplateMatch)
8452 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8453}
8454
8457 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8458 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8459 if (Old->size() != New->size()) {
8460 if (Complain)
8462 TemplateArgLoc);
8463
8464 return false;
8465 }
8466
8467 // C++0x [temp.arg.template]p3:
8468 // A template-argument matches a template template-parameter (call it P)
8469 // when each of the template parameters in the template-parameter-list of
8470 // the template-argument's corresponding class template or alias template
8471 // (call it A) matches the corresponding template parameter in the
8472 // template-parameter-list of P. [...]
8473 TemplateParameterList::iterator NewParm = New->begin();
8474 TemplateParameterList::iterator NewParmEnd = New->end();
8475 for (TemplateParameterList::iterator OldParm = Old->begin(),
8476 OldParmEnd = Old->end();
8477 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8478 if (NewParm == NewParmEnd) {
8479 if (Complain)
8481 TemplateArgLoc);
8482 return false;
8483 }
8484 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8485 OldInstFrom, Complain, Kind,
8486 TemplateArgLoc))
8487 return false;
8488 }
8489
8490 // Make sure we exhausted all of the arguments.
8491 if (NewParm != NewParmEnd) {
8492 if (Complain)
8494 TemplateArgLoc);
8495
8496 return false;
8497 }
8498
8499 if (Kind != TPL_TemplateParamsEquivalent) {
8500 const Expr *NewRC = New->getRequiresClause();
8501 const Expr *OldRC = Old->getRequiresClause();
8502
8503 auto Diagnose = [&] {
8504 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8505 diag::err_template_different_requires_clause);
8506 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8507 diag::note_template_prev_declaration) << /*declaration*/0;
8508 };
8509
8510 if (!NewRC != !OldRC) {
8511 if (Complain)
8512 Diagnose();
8513 return false;
8514 }
8515
8516 if (NewRC) {
8517 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8518 NewRC)) {
8519 if (Complain)
8520 Diagnose();
8521 return false;
8522 }
8523 }
8524 }
8525
8526 return true;
8527}
8528
8529bool
8531 if (!S)
8532 return false;
8533
8534 // Find the nearest enclosing declaration scope.
8535 S = S->getDeclParent();
8536
8537 // C++ [temp.pre]p6: [P2096]
8538 // A template, explicit specialization, or partial specialization shall not
8539 // have C linkage.
8540 DeclContext *Ctx = S->getEntity();
8541 if (Ctx && Ctx->isExternCContext()) {
8542 SourceRange Range =
8543 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8544 ? TemplateParams->getParam(0)->getSourceRange()
8545 : TemplateParams->getSourceRange();
8546 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8547 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8548 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8549 return true;
8550 }
8551 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8552
8553 // C++ [temp]p2:
8554 // A template-declaration can appear only as a namespace scope or
8555 // class scope declaration.
8556 // C++ [temp.expl.spec]p3:
8557 // An explicit specialization may be declared in any scope in which the
8558 // corresponding primary template may be defined.
8559 // C++ [temp.class.spec]p6: [P2096]
8560 // A partial specialization may be declared in any scope in which the
8561 // corresponding primary template may be defined.
8562 if (Ctx) {
8563 if (Ctx->isFileContext())
8564 return false;
8565 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8566 // C++ [temp.mem]p2:
8567 // A local class shall not have member templates.
8568
8569 // Trace the outer context chain, bypassing nested records and OpenMP
8570 // captured regions, to determine if the class in defined inside a
8571 // function or method.
8572 const DeclContext *OutCtx = RD->getDeclContext();
8573 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(OutCtx))
8574 OutCtx = OutCtx->getParent();
8575
8576 if (OutCtx && OutCtx->isFunctionOrMethod())
8577 return Diag(TemplateParams->getTemplateLoc(),
8578 diag::err_template_inside_local_class)
8579 << TemplateParams->getSourceRange();
8580
8581 return false;
8582 }
8583 }
8584
8585 return Diag(TemplateParams->getTemplateLoc(),
8586 diag::err_template_outside_namespace_or_class_scope)
8587 << TemplateParams->getSourceRange();
8588}
8589
8590/// Determine what kind of template specialization the given declaration
8591/// is.
8593 if (!D)
8594 return TSK_Undeclared;
8595
8596 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8597 return Record->getTemplateSpecializationKind();
8598 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8599 return Function->getTemplateSpecializationKind();
8600 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8601 return Var->getTemplateSpecializationKind();
8602
8603 return TSK_Undeclared;
8604}
8605
8606/// Check whether a specialization is well-formed in the current
8607/// context.
8608///
8609/// This routine determines whether a template specialization can be declared
8610/// in the current context (C++ [temp.expl.spec]p2).
8611///
8612/// \param S the semantic analysis object for which this check is being
8613/// performed.
8614///
8615/// \param Specialized the entity being specialized or instantiated, which
8616/// may be a kind of template (class template, function template, etc.) or
8617/// a member of a class template (member function, static data member,
8618/// member class).
8619///
8620/// \param PrevDecl the previous declaration of this entity, if any.
8621///
8622/// \param Loc the location of the explicit specialization or instantiation of
8623/// this entity.
8624///
8625/// \param IsPartialSpecialization whether this is a partial specialization of
8626/// a class template.
8627///
8628/// \returns true if there was an error that we cannot recover from, false
8629/// otherwise.
8631 NamedDecl *Specialized,
8632 NamedDecl *PrevDecl,
8633 SourceLocation Loc,
8635 // Keep these "kind" numbers in sync with the %select statements in the
8636 // various diagnostics emitted by this routine.
8637 int EntityKind = 0;
8638 if (isa<ClassTemplateDecl>(Specialized))
8639 EntityKind = IsPartialSpecialization? 1 : 0;
8640 else if (isa<VarTemplateDecl>(Specialized))
8641 EntityKind = IsPartialSpecialization ? 3 : 2;
8642 else if (isa<FunctionTemplateDecl>(Specialized))
8643 EntityKind = 4;
8644 else if (isa<CXXMethodDecl>(Specialized))
8645 EntityKind = 5;
8646 else if (isa<VarDecl>(Specialized))
8647 EntityKind = 6;
8648 else if (isa<RecordDecl>(Specialized))
8649 EntityKind = 7;
8650 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8651 EntityKind = 8;
8652 else {
8653 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8654 << S.getLangOpts().CPlusPlus11;
8655 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8656 return true;
8657 }
8658
8659 // C++ [temp.expl.spec]p2:
8660 // An explicit specialization may be declared in any scope in which
8661 // the corresponding primary template may be defined.
8663 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8664 << Specialized;
8665 return true;
8666 }
8667
8668 // C++ [temp.class.spec]p6:
8669 // A class template partial specialization may be declared in any
8670 // scope in which the primary template may be defined.
8671 DeclContext *SpecializedContext =
8672 Specialized->getDeclContext()->getRedeclContext();
8674
8675 // Make sure that this redeclaration (or definition) occurs in the same
8676 // scope or an enclosing namespace.
8677 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8678 : DC->Equals(SpecializedContext))) {
8679 if (isa<TranslationUnitDecl>(SpecializedContext))
8680 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8681 << EntityKind << Specialized;
8682 else {
8683 auto *ND = cast<NamedDecl>(SpecializedContext);
8684 int Diag = diag::err_template_spec_redecl_out_of_scope;
8685 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8686 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8687 S.Diag(Loc, Diag) << EntityKind << Specialized
8688 << ND << isa<CXXRecordDecl>(ND);
8689 }
8690
8691 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8692
8693 // Don't allow specializing in the wrong class during error recovery.
8694 // Otherwise, things can go horribly wrong.
8695 if (DC->isRecord())
8696 return true;
8697 }
8698
8699 return false;
8700}
8701
8703 if (!E->isTypeDependent())
8704 return SourceLocation();
8705 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8706 Checker.TraverseStmt(E);
8707 if (Checker.MatchLoc.isInvalid())
8708 return E->getSourceRange();
8709 return Checker.MatchLoc;
8710}
8711
8712static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8713 if (!TL.getType()->isDependentType())
8714 return SourceLocation();
8715 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8716 Checker.TraverseTypeLoc(TL);
8717 if (Checker.MatchLoc.isInvalid())
8718 return TL.getSourceRange();
8719 return Checker.MatchLoc;
8720}
8721
8722/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8723/// that checks non-type template partial specialization arguments.
8725 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8726 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8727 bool HasError = false;
8728 for (unsigned I = 0; I != NumArgs; ++I) {
8729 if (Args[I].getKind() == TemplateArgument::Pack) {
8731 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8732 Args[I].pack_size(), IsDefaultArgument))
8733 return true;
8734
8735 continue;
8736 }
8737
8738 if (Args[I].getKind() != TemplateArgument::Expression)
8739 continue;
8740
8741 Expr *ArgExpr = Args[I].getAsExpr();
8742 if (ArgExpr->containsErrors()) {
8743 HasError = true;
8744 continue;
8745 }
8746
8747 // We can have a pack expansion of any of the bullets below.
8748 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8749 ArgExpr = Expansion->getPattern();
8750
8751 // Strip off any implicit casts we added as part of type checking.
8752 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8753 ArgExpr = ICE->getSubExpr();
8754
8755 // C++ [temp.class.spec]p8:
8756 // A non-type argument is non-specialized if it is the name of a
8757 // non-type parameter. All other non-type arguments are
8758 // specialized.
8759 //
8760 // Below, we check the two conditions that only apply to
8761 // specialized non-type arguments, so skip any non-specialized
8762 // arguments.
8763 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8764 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8765 continue;
8766
8767 if (isa<DependentTemplateIdExpr>(ArgExpr))
8768 continue;
8769
8770 // C++ [temp.class.spec]p9:
8771 // Within the argument list of a class template partial
8772 // specialization, the following restrictions apply:
8773 // -- A partially specialized non-type argument expression
8774 // shall not involve a template parameter of the partial
8775 // specialization except when the argument expression is a
8776 // simple identifier.
8777 // -- The type of a template parameter corresponding to a
8778 // specialized non-type argument shall not be dependent on a
8779 // parameter of the specialization.
8780 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8781 // We implement a compromise between the original rules and DR1315:
8782 // -- A specialized non-type template argument shall not be
8783 // type-dependent and the corresponding template parameter
8784 // shall have a non-dependent type.
8785 SourceRange ParamUseRange =
8786 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8787 if (ParamUseRange.isValid()) {
8788 if (IsDefaultArgument) {
8789 S.Diag(TemplateNameLoc,
8790 diag::err_dependent_non_type_arg_in_partial_spec);
8791 S.Diag(ParamUseRange.getBegin(),
8792 diag::note_dependent_non_type_default_arg_in_partial_spec)
8793 << ParamUseRange;
8794 } else {
8795 S.Diag(ParamUseRange.getBegin(),
8796 diag::err_dependent_non_type_arg_in_partial_spec)
8797 << ParamUseRange;
8798 }
8799 return true;
8800 }
8801
8802 ParamUseRange = findTemplateParameter(
8803 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8804 if (ParamUseRange.isValid()) {
8805 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8806 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8807 << Param->getType();
8809 return true;
8810 }
8811 }
8812
8813 return HasError;
8814}
8815
8817 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8818 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8819 // We have to be conservative when checking a template in a dependent
8820 // context.
8821 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8822 return false;
8823
8824 TemplateParameterList *TemplateParams =
8825 PrimaryTemplate->getTemplateParameters();
8826 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8828 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8829 if (!Param)
8830 continue;
8831
8832 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8833 Param, &TemplateArgs[I],
8834 1, I >= NumExplicit))
8835 return true;
8836 }
8837
8838 return false;
8839}
8840
8842 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8843 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8845 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8846 assert(TUK != TagUseKind::Reference && "References are not specializations");
8847
8848 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8849 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8850 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8851
8852 // Find the class template we're specializing
8853 TemplateName Name = TemplateId.Template.get();
8855 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8856
8857 if (!ClassTemplate) {
8858 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8859 << (Name.getAsTemplateDecl() &&
8861 return true;
8862 }
8863
8864 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8865 auto Message = DSA->getMessage();
8866 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8867 << ClassTemplate << !Message.empty() << Message;
8868 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8869 }
8870
8871 if (S->isTemplateParamScope())
8872 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8873
8874 DeclContext *DC = ClassTemplate->getDeclContext();
8875
8876 bool isMemberSpecialization = false;
8877 bool isPartialSpecialization = false;
8878
8879 if (SS.isSet()) {
8880 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8881 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8882 TemplateNameLoc, &TemplateId,
8883 /*IsMemberSpecialization=*/false))
8884 return true;
8885 }
8886
8887 // Check the validity of the template headers that introduce this
8888 // template.
8889 // FIXME: We probably shouldn't complain about these headers for
8890 // friend declarations.
8891 bool Invalid = false;
8892 TemplateParameterList *TemplateParams =
8894 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8895 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8896 if (Invalid)
8897 return true;
8898
8899 // Check that we can declare a template specialization here.
8900 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8901 return true;
8902
8903 if (TemplateParams && DC->isDependentContext()) {
8904 ContextRAII SavedContext(*this, DC);
8906 return true;
8907 }
8908
8909 if (TemplateParams && TemplateParams->size() > 0) {
8910 isPartialSpecialization = true;
8911
8912 if (TUK == TagUseKind::Friend) {
8913 Diag(KWLoc, diag::err_partial_specialization_friend)
8914 << SourceRange(LAngleLoc, RAngleLoc);
8915 return true;
8916 }
8917
8918 // C++ [temp.class.spec]p10:
8919 // The template parameter list of a specialization shall not
8920 // contain default template argument values.
8921 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8922 Decl *Param = TemplateParams->getParam(I);
8923 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8924 if (TTP->hasDefaultArgument()) {
8925 Diag(TTP->getDefaultArgumentLoc(),
8926 diag::err_default_arg_in_partial_spec);
8927 TTP->removeDefaultArgument();
8928 }
8929 } else if (NonTypeTemplateParmDecl *NTTP
8930 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8931 if (NTTP->hasDefaultArgument()) {
8932 Diag(NTTP->getDefaultArgumentLoc(),
8933 diag::err_default_arg_in_partial_spec)
8934 << NTTP->getDefaultArgument().getSourceRange();
8935 NTTP->removeDefaultArgument();
8936 }
8937 } else {
8939 if (TTP->hasDefaultArgument()) {
8941 diag::err_default_arg_in_partial_spec)
8943 TTP->removeDefaultArgument();
8944 }
8945 }
8946 }
8947 } else if (TemplateParams) {
8948 if (TUK == TagUseKind::Friend)
8949 Diag(KWLoc, diag::err_template_spec_friend)
8951 SourceRange(TemplateParams->getTemplateLoc(),
8952 TemplateParams->getRAngleLoc()))
8953 << SourceRange(LAngleLoc, RAngleLoc);
8954 } else {
8955 assert(TUK == TagUseKind::Friend &&
8956 "should have a 'template<>' for this decl");
8957 }
8958
8959 // Check that the specialization uses the same tag kind as the
8960 // original template.
8962 assert(Kind != TagTypeKind::Enum &&
8963 "Invalid enum tag in class template spec!");
8964 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8965 TUK == TagUseKind::Definition, KWLoc,
8966 ClassTemplate->getIdentifier())) {
8967 Diag(KWLoc, diag::err_use_with_wrong_tag)
8968 << ClassTemplate
8970 ClassTemplate->getTemplatedDecl()->getKindName());
8971 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8972 diag::note_previous_use);
8973 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8974 }
8975
8976 // Translate the parser's template argument list in our AST format.
8977 TemplateArgumentListInfo TemplateArgs =
8978 makeTemplateArgumentListInfo(*this, TemplateId);
8979
8980 // Check for unexpanded parameter packs in any of the template arguments.
8981 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8982 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8983 isPartialSpecialization
8986 return true;
8987
8988 // Check that the template argument list is well-formed for this
8989 // template.
8991 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8992 /*DefaultArgs=*/{},
8993 /*PartialTemplateArgs=*/false, CTAI,
8994 /*UpdateArgsWithConversions=*/true))
8995 return true;
8996
8997 // Find the class template (partial) specialization declaration that
8998 // corresponds to these arguments.
8999 if (isPartialSpecialization) {
9001 TemplateArgs.size(),
9002 CTAI.CanonicalConverted))
9003 return true;
9004
9005 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9006 // also do it during instantiation.
9007 if (!Name.isDependent() &&
9008 !TemplateSpecializationType::anyDependentTemplateArguments(
9009 TemplateArgs, CTAI.CanonicalConverted)) {
9010 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9011 << ClassTemplate->getDeclName();
9012 isPartialSpecialization = false;
9013 Invalid = true;
9014 }
9015 }
9016
9017 llvm::FoldingSetInsertToken InsertToken;
9018 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9019
9020 if (isPartialSpecialization)
9021 PrevDecl = ClassTemplate->findPartialSpecialization(
9022 CTAI.CanonicalConverted, TemplateParams, InsertToken);
9023 else
9024 PrevDecl =
9025 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
9026
9028
9029 // Check whether we can declare a class template specialization in
9030 // the current scope.
9031 if (TUK != TagUseKind::Friend &&
9033 TemplateNameLoc,
9034 isPartialSpecialization))
9035 return true;
9036
9037 if (!isPartialSpecialization) {
9038 // Create a new class template specialization declaration node for
9039 // this explicit specialization or friend declaration.
9041 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9042 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
9043 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9045 if (TemplateParameterLists.size() > 0) {
9046 Specialization->setTemplateParameterListsInfo(Context,
9047 TemplateParameterLists);
9048 }
9049
9050 if (!PrevDecl)
9051 ClassTemplate->AddSpecialization(Specialization, InsertToken);
9052 } else {
9054 Context.getCanonicalTemplateSpecializationType(
9056 TemplateName(ClassTemplate->getCanonicalDecl()),
9057 CTAI.CanonicalConverted));
9058 if (Context.hasSameType(
9059 CanonType,
9060 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
9061 (!Context.getLangOpts().CPlusPlus20 ||
9062 !TemplateParams->hasAssociatedConstraints())) {
9063 // C++ [temp.class.spec]p9b3:
9064 //
9065 // -- The argument list of the specialization shall not be identical
9066 // to the implicit argument list of the primary template.
9067 //
9068 // This rule has since been removed, because it's redundant given DR1495,
9069 // but we keep it because it produces better diagnostics and recovery.
9070 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9071 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9072 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9073 return CheckClassTemplate(
9074 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9075 TemplateNameLoc, Attr, TemplateParams, AS_none,
9076 /*ModulePrivateLoc=*/SourceLocation(),
9077 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9078 TemplateParameterLists.data(), isMemberSpecialization);
9079 }
9080
9081 // Create a new class template partial specialization declaration node.
9083 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9086 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9087 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9088 Partial->setTemplateArgsAsWritten(TemplateArgs);
9089 SetNestedNameSpecifier(*this, Partial, SS);
9090 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9092 Context, TemplateParameterLists.drop_back(1));
9093 }
9094
9095 if (!PrevPartial)
9096 ClassTemplate->AddPartialSpecialization(Partial, InsertToken);
9097 Specialization = Partial;
9098
9099 // If we are providing an explicit specialization of a member class
9100 // template specialization, make a note of that.
9101 if (isMemberSpecialization)
9102 Partial->setMemberSpecialization();
9103
9105 }
9106
9107 // C++ [temp.expl.spec]p6:
9108 // If a template, a member template or the member of a class template is
9109 // explicitly specialized then that specialization shall be declared
9110 // before the first use of that specialization that would cause an implicit
9111 // instantiation to take place, in every translation unit in which such a
9112 // use occurs; no diagnostic is required.
9113 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9114 bool Okay = false;
9115 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9116 // Is there any previous explicit specialization declaration?
9118 Okay = true;
9119 break;
9120 }
9121 }
9122
9123 if (!Okay) {
9124 SourceRange Range(TemplateNameLoc, RAngleLoc);
9125 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9126 << Context.getCanonicalTagType(Specialization) << Range;
9127
9128 Diag(PrevDecl->getPointOfInstantiation(),
9129 diag::note_instantiation_required_here)
9130 << (PrevDecl->getTemplateSpecializationKind()
9132 return true;
9133 }
9134 }
9135
9136 // If this is not a friend, note that this is an explicit specialization.
9137 if (TUK != TagUseKind::Friend)
9138 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9139
9140 // Check that this isn't a redefinition of this specialization.
9141 if (TUK == TagUseKind::Definition) {
9142 RecordDecl *Def = Specialization->getDefinition();
9143 NamedDecl *Hidden = nullptr;
9144 bool HiddenDefVisible = false;
9145 if (Def && SkipBody &&
9146 isRedefinitionAllowedFor(Def, TemplateNameLoc, &Hidden,
9147 HiddenDefVisible)) {
9148 SkipBody->ShouldSkip = true;
9149 SkipBody->Previous = Def;
9150 if (!HiddenDefVisible && Hidden)
9152 } else if (Def) {
9153 SourceRange Range(TemplateNameLoc, RAngleLoc);
9154 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9155 Diag(Def->getLocation(), diag::note_previous_definition);
9156 Specialization->setInvalidDecl();
9157 return true;
9158 }
9159 }
9160
9163
9164 // Add alignment attributes if necessary; these attributes are checked when
9165 // the ASTContext lays out the structure.
9166 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9167 if (LangOpts.HLSL)
9168 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9171 }
9172
9173 if (ModulePrivateLoc.isValid())
9174 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9175 << (isPartialSpecialization? 1 : 0)
9176 << FixItHint::CreateRemoval(ModulePrivateLoc);
9177
9178 // C++ [temp.expl.spec]p9:
9179 // A template explicit specialization is in the scope of the
9180 // namespace in which the template was defined.
9181 //
9182 // We actually implement this paragraph where we set the semantic
9183 // context (in the creation of the ClassTemplateSpecializationDecl),
9184 // but we also maintain the lexical context where the actual
9185 // definition occurs.
9186 Specialization->setLexicalDeclContext(CurContext);
9187
9188 // We may be starting the definition of this specialization.
9189 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9190 Specialization->startDefinition();
9191
9192 if (TUK == TagUseKind::Friend) {
9193 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9194 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9195 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9197 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9198 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9199
9200 // Build the fully-sugared type for this class template
9201 // specialization as the user wrote in the specialization
9202 // itself. This means that we'll pretty-print the type retrieved
9203 // from the specialization's declaration the way that the user
9204 // actually wrote the specialization, rather than formatting the
9205 // name based on the "canonical" representation used to store the
9206 // template arguments in the specialization.
9208 TemplateNameLoc,
9209 WrittenTy,
9210 /*FIXME:*/KWLoc);
9211 Friend->setAccess(AS_public);
9212 CurContext->addDecl(Friend);
9213 } else {
9214 // Add the specialization into its lexical context, so that it can
9215 // be seen when iterating through the list of declarations in that
9216 // context. However, specializations are not found by name lookup.
9217 CurContext->addDecl(Specialization);
9218 }
9219
9220 if (SkipBody && SkipBody->ShouldSkip)
9221 return SkipBody->Previous;
9222
9223 Specialization->setInvalidDecl(Invalid);
9225 return Specialization;
9226}
9227
9229 MultiTemplateParamsArg TemplateParameterLists,
9230 Declarator &D) {
9231 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9232 ActOnDocumentableDecl(NewDecl);
9233 return NewDecl;
9234}
9235
9237 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9238 const IdentifierInfo *Name, SourceLocation NameLoc) {
9239 DeclContext *DC = CurContext;
9240
9241 if (!DC->getRedeclContext()->isFileContext()) {
9242 Diag(NameLoc,
9243 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9244 return nullptr;
9245 }
9246
9247 if (TemplateParameterLists.size() > 1) {
9248 Diag(NameLoc, diag::err_concept_extra_headers);
9249 return nullptr;
9250 }
9251
9252 TemplateParameterList *Params = TemplateParameterLists.front();
9253
9254 if (Params->size() == 0) {
9255 Diag(NameLoc, diag::err_concept_no_parameters);
9256 return nullptr;
9257 }
9258
9259 // Ensure that the parameter pack, if present, is the last parameter in the
9260 // template.
9261 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9262 ParamEnd = Params->end();
9263 ParamIt != ParamEnd; ++ParamIt) {
9264 Decl const *Param = *ParamIt;
9265 if (Param->isParameterPack()) {
9266 if (++ParamIt == ParamEnd)
9267 break;
9268 Diag(Param->getLocation(),
9269 diag::err_template_param_pack_must_be_last_template_parameter);
9270 return nullptr;
9271 }
9272 }
9273
9274 ConceptDecl *NewDecl =
9275 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9276
9277 if (NewDecl->hasAssociatedConstraints()) {
9278 // C++2a [temp.concept]p4:
9279 // A concept shall not have associated constraints.
9280 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9281 NewDecl->setInvalidDecl();
9282 }
9283
9284 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9285 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9287 LookupName(Previous, S);
9288 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9289 /*AllowInlineNamespace*/ false);
9290
9291 // We cannot properly handle redeclarations until we parse the constraint
9292 // expression, so only inject the name if we are sure we are not redeclaring a
9293 // symbol
9294 if (Previous.empty())
9295 PushOnScopeChains(NewDecl, S, true);
9296
9297 return NewDecl;
9298}
9299
9301 bool Found = false;
9302 LookupResult::Filter F = R.makeFilter();
9303 while (F.hasNext()) {
9304 NamedDecl *D = F.next();
9305 if (D == C) {
9306 F.erase();
9307 Found = true;
9308 break;
9309 }
9310 }
9311 F.done();
9312 return Found;
9313}
9314
9317 Expr *ConstraintExpr,
9318 const ParsedAttributesView &Attrs) {
9319 assert(!C->hasDefinition() && "Concept already defined");
9320 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9321 C->setInvalidDecl();
9322 return nullptr;
9323 }
9324 C->setDefinition(ConstraintExpr);
9325 ProcessDeclAttributeList(S, C, Attrs);
9326
9327 // Check for conflicting previous declaration.
9328 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9329 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9331 LookupName(Previous, S);
9332 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9333 /*AllowInlineNamespace*/ false);
9334 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9335 bool AddToScope = true;
9336 CheckConceptRedefinition(C, Previous, AddToScope);
9337
9339 if (!WasAlreadyAdded && AddToScope)
9340 PushOnScopeChains(C, S);
9341
9342 return C;
9343}
9344
9346 LookupResult &Previous, bool &AddToScope) {
9347 AddToScope = true;
9348
9349 if (Previous.empty())
9350 return;
9351
9352 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9353 if (!OldConcept) {
9354 auto *Old = Previous.getRepresentativeDecl();
9355 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9356 << NewDecl->getDeclName();
9357 notePreviousDefinition(Old, NewDecl->getLocation());
9358 AddToScope = false;
9359 return;
9360 }
9361 // Check if we can merge with a concept declaration.
9362 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9363 if (!IsSame) {
9364 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9365 << NewDecl->getDeclName();
9366 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9367 AddToScope = false;
9368 return;
9369 }
9370 if (hasReachableDefinition(OldConcept) &&
9371 IsRedefinitionInModule(NewDecl, OldConcept)) {
9372 Diag(NewDecl->getLocation(), diag::err_redefinition)
9373 << NewDecl->getDeclName();
9374 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9375 AddToScope = false;
9376 return;
9377 }
9378 if (!Previous.isSingleResult()) {
9379 // FIXME: we should produce an error in case of ambig and failed lookups.
9380 // Other decls (e.g. namespaces) also have this shortcoming.
9381 return;
9382 }
9383 // We unwrap canonical decl late to check for module visibility.
9384 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9385}
9386
9388 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9389 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9390 Diag(Loc, diag::err_recursive_concept) << CE;
9391 Diag(CE->getLocation(), diag::note_declared_at);
9392 CE->setInvalidDecl();
9393 return true;
9394 }
9395 // Concept template parameters don't have a definition and can't
9396 // be defined recursively.
9397 return false;
9398}
9399
9400/// \brief Strips various properties off an implicit instantiation
9401/// that has just been explicitly specialized.
9402static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9403 if (MinGW || (isa<FunctionDecl>(D) &&
9404 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9405 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9406
9407 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9408 FD->setInlineSpecified(false);
9409}
9410
9411/// Create an ExplicitInstantiationDecl to record source-location info for an
9412/// explicit template instantiation statement, and add it to \p CurContext.
9413///
9414/// For class templates / nested classes, the caller should build a
9415/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9416/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9417///
9418/// For function / variable templates, the caller should pass TypeAsWritten for
9419/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9421 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9422 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9423 NestedNameSpecifierLoc QualifierLoc,
9424 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9425 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9427 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9428 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9429 Context.addExplicitInstantiationDecl(Spec, EID);
9430 CurContext->addDecl(EID);
9431}
9432
9433/// Compute the diagnostic location for an explicit instantiation
9434// declaration or definition.
9435static SourceLocation
9437 SourceLocation PointOfInstantiation) {
9438 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9439 if (EID->getTemplateSpecializationKind() ==
9441 return EID->getTemplateLoc();
9442
9443 // Explicit instantiations following a specialization have no effect and
9444 // hence no PointOfInstantiation. In that case, walk decl backwards
9445 // until a valid name loc is found.
9446 SourceLocation PrevDiagLoc = PointOfInstantiation;
9447 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9448 Prev = Prev->getPreviousDecl()) {
9449 PrevDiagLoc = Prev->getLocation();
9450 }
9451 assert(PrevDiagLoc.isValid() &&
9452 "Explicit instantiation without point of instantiation?");
9453 return PrevDiagLoc;
9454}
9455
9456bool
9459 NamedDecl *PrevDecl,
9461 SourceLocation PrevPointOfInstantiation,
9462 bool &HasNoEffect) {
9463 HasNoEffect = false;
9464
9465 switch (NewTSK) {
9466 case TSK_Undeclared:
9468 assert(
9469 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9470 "previous declaration must be implicit!");
9471 return false;
9472
9474 switch (PrevTSK) {
9475 case TSK_Undeclared:
9477 // Okay, we're just specializing something that is either already
9478 // explicitly specialized or has merely been mentioned without any
9479 // instantiation.
9480 return false;
9481
9483 if (PrevPointOfInstantiation.isInvalid()) {
9484 // The declaration itself has not actually been instantiated, so it is
9485 // still okay to specialize it.
9487 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9488 return false;
9489 }
9490 // Fall through
9491 [[fallthrough]];
9492
9495 assert((PrevTSK == TSK_ImplicitInstantiation ||
9496 PrevPointOfInstantiation.isValid()) &&
9497 "Explicit instantiation without point of instantiation?");
9498
9499 // C++ [temp.expl.spec]p6:
9500 // If a template, a member template or the member of a class template
9501 // is explicitly specialized then that specialization shall be declared
9502 // before the first use of that specialization that would cause an
9503 // implicit instantiation to take place, in every translation unit in
9504 // which such a use occurs; no diagnostic is required.
9505 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9506 // Is there any previous explicit specialization declaration?
9508 return false;
9509 }
9510
9511 Diag(NewLoc, diag::err_specialization_after_instantiation)
9512 << PrevDecl;
9513 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9514 << (PrevTSK != TSK_ImplicitInstantiation);
9515
9516 return true;
9517 }
9518 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9519
9521 switch (PrevTSK) {
9523 // This explicit instantiation declaration is redundant (that's okay).
9524 HasNoEffect = true;
9525 return false;
9526
9527 case TSK_Undeclared:
9529 // We're explicitly instantiating something that may have already been
9530 // implicitly instantiated; that's fine.
9531 return false;
9532
9534 // C++0x [temp.explicit]p4:
9535 // For a given set of template parameters, if an explicit instantiation
9536 // of a template appears after a declaration of an explicit
9537 // specialization for that template, the explicit instantiation has no
9538 // effect.
9539 HasNoEffect = true;
9540 return false;
9541
9543 // C++0x [temp.explicit]p10:
9544 // If an entity is the subject of both an explicit instantiation
9545 // declaration and an explicit instantiation definition in the same
9546 // translation unit, the definition shall follow the declaration.
9547 Diag(NewLoc,
9548 diag::err_explicit_instantiation_declaration_after_definition);
9549
9550 // Explicit instantiations following a specialization have no effect and
9551 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9552 // until a valid name loc is found.
9553 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9554 diag::note_explicit_instantiation_definition_here);
9555 HasNoEffect = true;
9556 return false;
9557 }
9558 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9559
9561 switch (PrevTSK) {
9562 case TSK_Undeclared:
9564 // We're explicitly instantiating something that may have already been
9565 // implicitly instantiated; that's fine.
9566 return false;
9567
9569 // C++ DR 259, C++0x [temp.explicit]p4:
9570 // For a given set of template parameters, if an explicit
9571 // instantiation of a template appears after a declaration of
9572 // an explicit specialization for that template, the explicit
9573 // instantiation has no effect.
9574 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9575 << PrevDecl;
9576 Diag(PrevDecl->getLocation(),
9577 diag::note_previous_template_specialization);
9578 HasNoEffect = true;
9579 return false;
9580
9582 // We're explicitly instantiating a definition for something for which we
9583 // were previously asked to suppress instantiations. That's fine.
9584
9585 // C++0x [temp.explicit]p4:
9586 // For a given set of template parameters, if an explicit instantiation
9587 // of a template appears after a declaration of an explicit
9588 // specialization for that template, the explicit instantiation has no
9589 // effect.
9590 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9591 // Is there any previous explicit specialization declaration?
9593 HasNoEffect = true;
9594 break;
9595 }
9596 }
9597
9598 return false;
9599
9601 // C++0x [temp.spec]p5:
9602 // For a given template and a given set of template-arguments,
9603 // - an explicit instantiation definition shall appear at most once
9604 // in a program,
9605
9606 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9607 Diag(NewLoc, (getLangOpts().MSVCCompat)
9608 ? diag::ext_explicit_instantiation_duplicate
9609 : diag::err_explicit_instantiation_duplicate)
9610 << PrevDecl;
9611 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9612 diag::note_previous_explicit_instantiation);
9613 HasNoEffect = true;
9614 return false;
9615 }
9616 }
9617
9618 llvm_unreachable("Missing specialization/instantiation case?");
9619}
9620
9622 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9624 // Remove anything from Previous that isn't a function template in
9625 // the correct context.
9626 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9627 LookupResult::Filter F = Previous.makeFilter();
9628 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9629 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9630 while (F.hasNext()) {
9631 NamedDecl *D = F.next()->getUnderlyingDecl();
9632 if (!isa<FunctionTemplateDecl>(D)) {
9633 F.erase();
9634 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9635 continue;
9636 }
9637
9638 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9640 F.erase();
9641 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9642 continue;
9643 }
9644 }
9645 F.done();
9646
9647 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9648 if (Previous.empty()) {
9649 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9650 if (IsFriend && FriendQualifier.isDependent() &&
9651 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9652 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9654 Context, Previous.asUnresolvedSet(), ExplicitTemplateArgs);
9655 return false;
9656 }
9657
9658 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9659 << IsFriend;
9660 for (auto &P : DiscardedCandidates)
9661 Diag(P.second->getLocation(),
9662 diag::note_dependent_function_template_spec_discard_reason)
9663 << P.first << IsFriend;
9664 return true;
9665 }
9666
9668 ExplicitTemplateArgs);
9669 return false;
9670}
9671
9673 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9674 LookupResult &Previous, bool QualifiedFriend) {
9675 // The set of function template specializations that could match this
9676 // explicit function template specialization.
9677 UnresolvedSet<8> Candidates;
9678 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9679 /*ForTakingAddress=*/false);
9680
9681 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9682 ConvertedTemplateArgs;
9683
9684 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9685 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9686 I != E; ++I) {
9687 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9688 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9689 // Only consider templates found within the same semantic lookup scope as
9690 // FD.
9691 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9693 continue;
9694
9695 QualType FT = FD->getType();
9696 // C++11 [dcl.constexpr]p8:
9697 // A constexpr specifier for a non-static member function that is not
9698 // a constructor declares that member function to be const.
9699 //
9700 // When matching a constexpr member function template specialization
9701 // against the primary template, we don't yet know whether the
9702 // specialization has an implicit 'const' (because we don't know whether
9703 // it will be a static member function until we know which template it
9704 // specializes). This rule was removed in C++14.
9705 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9706 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9708 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9709 if (OldMD && OldMD->isConst()) {
9710 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9712 EPI.TypeQuals.addConst();
9713 FT = Context.getFunctionType(FPT->getReturnType(),
9714 FPT->getParamTypes(), EPI);
9715 }
9716 }
9717
9719 if (ExplicitTemplateArgs)
9720 Args = *ExplicitTemplateArgs;
9721
9722 // C++ [temp.expl.spec]p11:
9723 // A trailing template-argument can be left unspecified in the
9724 // template-id naming an explicit function template specialization
9725 // provided it can be deduced from the function argument type.
9726 // Perform template argument deduction to determine whether we may be
9727 // specializing this template.
9728 // FIXME: It is somewhat wasteful to build
9729 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9730 FunctionDecl *Specialization = nullptr;
9732 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9733 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9735 // Template argument deduction failed; record why it failed, so
9736 // that we can provide nifty diagnostics.
9737 FailedCandidates.addCandidate().set(
9738 I.getPair(), FunTmpl->getTemplatedDecl(),
9739 MakeDeductionFailureInfo(Context, TDK, Info));
9740 (void)TDK;
9741 continue;
9742 }
9743
9744 // Target attributes are part of the cuda function signature, so
9745 // the deduced template's cuda target must match that of the
9746 // specialization. Given that C++ template deduction does not
9747 // take target attributes into account, we reject candidates
9748 // here that have a different target.
9749 if (LangOpts.CUDA &&
9750 CUDA().IdentifyTarget(Specialization,
9751 /* IgnoreImplicitHDAttr = */ true) !=
9752 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9753 FailedCandidates.addCandidate().set(
9754 I.getPair(), FunTmpl->getTemplatedDecl(),
9757 continue;
9758 }
9759
9760 // Record this candidate.
9761 if (ExplicitTemplateArgs)
9762 ConvertedTemplateArgs[Specialization] = std::move(Args);
9763 Candidates.addDecl(Specialization, I.getAccess());
9764 }
9765 }
9766
9767 // For a qualified friend declaration (with no explicit marker to indicate
9768 // that a template specialization was intended), note all (template and
9769 // non-template) candidates.
9770 if (QualifiedFriend && Candidates.empty()) {
9771 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9772 << FD->getDeclName() << FDLookupContext;
9773 // FIXME: We should form a single candidate list and diagnose all
9774 // candidates at once, to get proper sorting and limiting.
9775 for (auto *OldND : Previous) {
9776 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9777 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9778 }
9779 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9780 return true;
9781 }
9782
9783 // Find the most specialized function template.
9785 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9786 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9787 PDiag(diag::err_function_template_spec_ambiguous)
9788 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9789 PDiag(diag::note_function_template_spec_matched));
9790
9791 if (Result == Candidates.end())
9792 return true;
9793
9794 // Ignore access information; it doesn't figure into redeclaration checking.
9796
9797 if (const auto *PT = Specialization->getPrimaryTemplate();
9798 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9799 auto Message = DSA->getMessage();
9800 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9801 << PT << !Message.empty() << Message;
9802 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9803 }
9804
9805 // C++23 [except.spec]p13:
9806 // An exception specification is considered to be needed when:
9807 // - [...]
9808 // - the exception specification is compared to that of another declaration
9809 // (e.g., an explicit specialization or an overriding virtual function);
9810 // - [...]
9811 //
9812 // The exception specification of a defaulted function is evaluated as
9813 // described above only when needed; similarly, the noexcept-specifier of a
9814 // specialization of a function template or member function of a class
9815 // template is instantiated only when needed.
9816 //
9817 // The standard doesn't specify what the "comparison with another declaration"
9818 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9819 // not state which properties of an explicit specialization must match the
9820 // primary template.
9821 //
9822 // We assume that an explicit specialization must correspond with (per
9823 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9824 // the declaration produced by substitution into the function template.
9825 //
9826 // Since the determination whether two function declarations correspond does
9827 // not consider exception specification, we only need to instantiate it once
9828 // we determine the primary template when comparing types per
9829 // [basic.link]p11.1.
9830 auto *SpecializationFPT =
9831 Specialization->getType()->castAs<FunctionProtoType>();
9832 // If the function has a dependent exception specification, resolve it after
9833 // we have selected the primary template so we can check whether it matches.
9834 if (getLangOpts().CPlusPlus17 &&
9835 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9836 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9837 return true;
9838
9840 = Specialization->getTemplateSpecializationInfo();
9841 assert(SpecInfo && "Function template specialization info missing?");
9842
9843 // Note: do not overwrite location info if previous template
9844 // specialization kind was explicit.
9846 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9847 Specialization->setLocation(FD->getLocation());
9848 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9849 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9850 // function can differ from the template declaration with respect to
9851 // the constexpr specifier.
9852 // FIXME: We need an update record for this AST mutation.
9853 // FIXME: What if there are multiple such prior declarations (for instance,
9854 // from different modules)?
9855 Specialization->setConstexprKind(FD->getConstexprKind());
9856 }
9857
9858 // FIXME: Check if the prior specialization has a point of instantiation.
9859 // If so, we have run afoul of .
9860
9861 // If this is a friend declaration, then we're not really declaring
9862 // an explicit specialization.
9863 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9864
9865 // Check the scope of this explicit specialization.
9866 if (!isFriend &&
9868 Specialization->getPrimaryTemplate(),
9870 false))
9871 return true;
9872
9873 // C++ [temp.expl.spec]p6:
9874 // If a template, a member template or the member of a class template is
9875 // explicitly specialized then that specialization shall be declared
9876 // before the first use of that specialization that would cause an implicit
9877 // instantiation to take place, in every translation unit in which such a
9878 // use occurs; no diagnostic is required.
9879 bool HasNoEffect = false;
9880 if (!isFriend &&
9885 SpecInfo->getPointOfInstantiation(),
9886 HasNoEffect))
9887 return true;
9888
9889 // Mark the prior declaration as an explicit specialization, so that later
9890 // clients know that this is an explicit specialization.
9891 // A dependent friend specialization which has a definition should be treated
9892 // as explicit specialization, despite being invalid.
9893 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9894 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9895 // Since explicit specializations do not inherit '=delete' from their
9896 // primary function template - check if the 'specialization' that was
9897 // implicitly generated (during template argument deduction for partial
9898 // ordering) from the most specialized of all the function templates that
9899 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9900 // first check that it was implicitly generated during template argument
9901 // deduction by making sure it wasn't referenced, and then reset the deleted
9902 // flag to not-deleted, so that we can inherit that information from 'FD'.
9903 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9904 !Specialization->getCanonicalDecl()->isReferenced()) {
9905 // FIXME: This assert will not hold in the presence of modules.
9906 assert(
9907 Specialization->getCanonicalDecl() == Specialization &&
9908 "This must be the only existing declaration of this specialization");
9909 // FIXME: We need an update record for this AST mutation.
9910 Specialization->setDeletedAsWritten(false);
9911 }
9912 // FIXME: We need an update record for this AST mutation.
9915 }
9916
9917 // Turn the given function declaration into a function template
9918 // specialization, with the template arguments from the previous
9919 // specialization.
9920 // Take copies of (semantic and syntactic) template argument lists.
9922 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9923 FD->setFunctionTemplateSpecialization(
9924 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertToken=*/{},
9926 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9927
9928 // A function template specialization inherits the target attributes
9929 // of its template. (We require the attributes explicitly in the
9930 // code to match, but a template may have implicit attributes by
9931 // virtue e.g. of being constexpr, and it passes these implicit
9932 // attributes on to its specializations.)
9933 if (LangOpts.CUDA)
9934 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9935
9936 // The "previous declaration" for this function template specialization is
9937 // the prior function template specialization.
9938 Previous.clear();
9939 Previous.addDecl(Specialization);
9940 return false;
9941}
9942
9943bool
9945 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9946 "Only for non-template members");
9947
9948 // Try to find the member we are instantiating.
9949 NamedDecl *FoundInstantiation = nullptr;
9950 NamedDecl *Instantiation = nullptr;
9951 NamedDecl *InstantiatedFrom = nullptr;
9952 MemberSpecializationInfo *MSInfo = nullptr;
9953
9954 if (Previous.empty()) {
9955 // Nowhere to look anyway.
9956 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9957 UnresolvedSet<8> Candidates;
9958 for (NamedDecl *Candidate : Previous) {
9959 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9960 // Ignore any candidates that aren't member functions.
9961 if (!Method)
9962 continue;
9963
9964 QualType Adjusted = Function->getType();
9965 if (!hasExplicitCallingConv(Adjusted))
9966 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9967 // Ignore any candidates with the wrong type.
9968 // This doesn't handle deduced return types, but both function
9969 // declarations should be undeduced at this point.
9970 // FIXME: The exception specification should probably be ignored when
9971 // comparing the types.
9972 if (!Context.hasSameType(Adjusted, Method->getType()))
9973 continue;
9974
9975 // Ignore any candidates with unsatisfied constraints.
9976 if (ConstraintSatisfaction Satisfaction;
9977 Method->getTrailingRequiresClause() &&
9978 (CheckFunctionConstraints(Method, Satisfaction,
9979 /*UsageLoc=*/Member->getLocation(),
9980 /*ForOverloadResolution=*/true) ||
9981 !Satisfaction.IsSatisfied))
9982 continue;
9983
9984 Candidates.addDecl(Candidate);
9985 }
9986
9987 // If we have no viable candidates left after filtering, we are done.
9988 if (Candidates.empty())
9989 return false;
9990
9991 // Find the function that is more constrained than every other function it
9992 // has been compared to.
9993 UnresolvedSetIterator Best = Candidates.begin();
9994 CXXMethodDecl *BestMethod = nullptr;
9995 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9996 I != E; ++I) {
9997 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9998 if (I == Best ||
9999 getMoreConstrainedFunction(Method, BestMethod) == Method) {
10000 Best = I;
10001 BestMethod = Method;
10002 }
10003 }
10004
10005 FoundInstantiation = *Best;
10006 Instantiation = BestMethod;
10007 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
10008 MSInfo = BestMethod->getMemberSpecializationInfo();
10009
10010 // Make sure the best candidate is more constrained than all of the others.
10011 bool Ambiguous = false;
10012 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
10013 I != E; ++I) {
10014 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
10015 if (I != Best &&
10016 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
10017 Ambiguous = true;
10018 break;
10019 }
10020 }
10021
10022 if (Ambiguous) {
10023 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
10024 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10025 for (NamedDecl *Candidate : Candidates) {
10026 Candidate = Candidate->getUnderlyingDecl();
10027 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
10028 << Candidate;
10029 }
10030 return true;
10031 }
10032 } else if (isa<VarDecl>(Member)) {
10033 VarDecl *PrevVar;
10034 if (Previous.isSingleResult() &&
10035 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10036 if (PrevVar->isStaticDataMember()) {
10037 FoundInstantiation = Previous.getRepresentativeDecl();
10038 Instantiation = PrevVar;
10039 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10040 MSInfo = PrevVar->getMemberSpecializationInfo();
10041 }
10042 } else if (isa<RecordDecl>(Member)) {
10043 CXXRecordDecl *PrevRecord;
10044 if (Previous.isSingleResult() &&
10045 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10046 FoundInstantiation = Previous.getRepresentativeDecl();
10047 Instantiation = PrevRecord;
10048 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10049 MSInfo = PrevRecord->getMemberSpecializationInfo();
10050 }
10051 } else if (isa<EnumDecl>(Member)) {
10052 EnumDecl *PrevEnum;
10053 if (Previous.isSingleResult() &&
10054 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10055 FoundInstantiation = Previous.getRepresentativeDecl();
10056 Instantiation = PrevEnum;
10057 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10058 MSInfo = PrevEnum->getMemberSpecializationInfo();
10059 }
10060 }
10061
10062 if (!Instantiation) {
10063 // There is no previous declaration that matches. Since member
10064 // specializations are always out-of-line, the caller will complain about
10065 // this mismatch later.
10066 return false;
10067 }
10068
10069 // A member specialization in a friend declaration isn't really declaring
10070 // an explicit specialization, just identifying a specific (possibly implicit)
10071 // specialization. Don't change the template specialization kind.
10072 //
10073 // FIXME: Is this really valid? Other compilers reject.
10074 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10075 // Preserve instantiation information.
10076 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10077 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10078 cast<CXXMethodDecl>(InstantiatedFrom),
10080 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10081 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10082 cast<CXXRecordDecl>(InstantiatedFrom),
10084 }
10085
10086 Previous.clear();
10087 Previous.addDecl(FoundInstantiation);
10088 return false;
10089 }
10090
10091 // Make sure that this is a specialization of a member.
10092 if (!InstantiatedFrom) {
10093 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10094 << Member;
10095 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10096 return true;
10097 }
10098
10099 // C++ [temp.expl.spec]p6:
10100 // If a template, a member template or the member of a class template is
10101 // explicitly specialized then that specialization shall be declared
10102 // before the first use of that specialization that would cause an implicit
10103 // instantiation to take place, in every translation unit in which such a
10104 // use occurs; no diagnostic is required.
10105 assert(MSInfo && "Member specialization info missing?");
10106
10107 bool HasNoEffect = false;
10110 Instantiation,
10112 MSInfo->getPointOfInstantiation(),
10113 HasNoEffect))
10114 return true;
10115
10116 // Check the scope of this explicit specialization.
10118 InstantiatedFrom,
10119 Instantiation, Member->getLocation(),
10120 false))
10121 return true;
10122
10123 // Note that this member specialization is an "instantiation of" the
10124 // corresponding member of the original template.
10125 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10126 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10127 if (InstantiationFunction->getTemplateSpecializationKind() ==
10129 // Explicit specializations of member functions of class templates do not
10130 // inherit '=delete' from the member function they are specializing.
10131 if (InstantiationFunction->isDeleted()) {
10132 // FIXME: This assert will not hold in the presence of modules.
10133 assert(InstantiationFunction->getCanonicalDecl() ==
10134 InstantiationFunction);
10135 // FIXME: We need an update record for this AST mutation.
10136 InstantiationFunction->setDeletedAsWritten(false);
10137 }
10138 }
10139
10140 MemberFunction->setInstantiationOfMemberFunction(
10142 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10143 MemberVar->setInstantiationOfStaticDataMember(
10144 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10145 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10146 MemberClass->setInstantiationOfMemberClass(
10148 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10149 MemberEnum->setInstantiationOfMemberEnum(
10150 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10151 } else {
10152 llvm_unreachable("unknown member specialization kind");
10153 }
10154
10155 // Save the caller the trouble of having to figure out which declaration
10156 // this specialization matches.
10157 Previous.clear();
10158 Previous.addDecl(FoundInstantiation);
10159 return false;
10160}
10161
10162/// Complete the explicit specialization of a member of a class template by
10163/// updating the instantiated member to be marked as an explicit specialization.
10164///
10165/// \param OrigD The member declaration instantiated from the template.
10166/// \param Loc The location of the explicit specialization of the member.
10167template<typename DeclT>
10168static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10169 SourceLocation Loc) {
10170 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10171 return;
10172
10173 // FIXME: Inform AST mutation listeners of this AST mutation.
10174 // FIXME: If there are multiple in-class declarations of the member (from
10175 // multiple modules, or a declaration and later definition of a member type),
10176 // should we update all of them?
10177 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10178 OrigD->setLocation(Loc);
10179}
10180
10183 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10184 if (Instantiation == Member)
10185 return;
10186
10187 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10188 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10189 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10190 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10191 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10192 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10193 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10194 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10195 else
10196 llvm_unreachable("unknown member specialization kind");
10197}
10198
10199/// Check the scope of an explicit instantiation.
10200///
10201/// \returns true if a serious error occurs, false otherwise.
10203 SourceLocation InstLoc,
10204 bool WasQualifiedName) {
10206 DeclContext *CurContext = S.CurContext->getRedeclContext();
10207
10208 if (CurContext->isRecord()) {
10209 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10210 << D;
10211 return true;
10212 }
10213
10214 // C++11 [temp.explicit]p3:
10215 // An explicit instantiation shall appear in an enclosing namespace of its
10216 // template. If the name declared in the explicit instantiation is an
10217 // unqualified name, the explicit instantiation shall appear in the
10218 // namespace where its template is declared or, if that namespace is inline
10219 // (7.3.1), any namespace from its enclosing namespace set.
10220 //
10221 // This is DR275, which we do not retroactively apply to C++98/03.
10222 if (WasQualifiedName) {
10223 if (CurContext->Encloses(OrigContext))
10224 return false;
10225 } else {
10226 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10227 return false;
10228 }
10229
10230 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10231 if (WasQualifiedName)
10232 S.Diag(InstLoc,
10233 S.getLangOpts().CPlusPlus11?
10234 diag::err_explicit_instantiation_out_of_scope :
10235 diag::warn_explicit_instantiation_out_of_scope_0x)
10236 << D << NS;
10237 else
10238 S.Diag(InstLoc,
10239 S.getLangOpts().CPlusPlus11?
10240 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10241 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10242 << D << NS;
10243 } else
10244 S.Diag(InstLoc,
10245 S.getLangOpts().CPlusPlus11?
10246 diag::err_explicit_instantiation_must_be_global :
10247 diag::warn_explicit_instantiation_must_be_global_0x)
10248 << D;
10249 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10250 return false;
10251}
10252
10253/// Common checks for whether an explicit instantiation of \p D is valid.
10255 SourceLocation InstLoc,
10256 bool WasQualifiedName,
10258 // C++ [temp.explicit]p13:
10259 // An explicit instantiation declaration shall not name a specialization of
10260 // a template with internal linkage.
10263 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10264 return true;
10265 }
10266
10267 // C++11 [temp.explicit]p3: [DR 275]
10268 // An explicit instantiation shall appear in an enclosing namespace of its
10269 // template.
10270 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10271 return true;
10272
10273 return false;
10274}
10275
10276/// Determine whether the given scope specifier has a template-id in it.
10278 // C++11 [temp.explicit]p3:
10279 // If the explicit instantiation is for a member function, a member class
10280 // or a static data member of a class template specialization, the name of
10281 // the class template specialization in the qualified-id for the member
10282 // name shall be a simple-template-id.
10283 //
10284 // C++98 has the same restriction, just worded differently.
10285 for (NestedNameSpecifier NNS = SS.getScopeRep();
10287 /**/) {
10288 const Type *T = NNS.getAsType();
10290 return true;
10291 NNS = T->getPrefix();
10292 }
10293 return false;
10294}
10295
10296/// Make a dllexport or dllimport attr on a class template specialization take
10297/// effect.
10300 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10301 assert(A && "dllExportImportClassTemplateSpecialization called "
10302 "on Def without dllexport or dllimport");
10303
10304 // We reject explicit instantiations in class scope, so there should
10305 // never be any delayed exported classes to worry about.
10306 assert(S.DelayedDllExportClasses.empty() &&
10307 "delayed exports present at explicit instantiation");
10309
10310 // Propagate attribute to base class templates.
10311 for (auto &B : Def->bases()) {
10312 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10313 B.getType()->getAsCXXRecordDecl()))
10315 }
10316
10318}
10319
10321 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10322 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10323 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10324 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10325 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10326 // Find the class template we're specializing
10327 TemplateName Name = TemplateD.get();
10328 TemplateDecl *TD = Name.getAsTemplateDecl();
10329 // Check that the specialization uses the same tag kind as the
10330 // original template.
10332 assert(Kind != TagTypeKind::Enum &&
10333 "Invalid enum tag in class template explicit instantiation!");
10334
10335 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10336
10337 if (!ClassTemplate) {
10338 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10339 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10340 Diag(TD->getLocation(), diag::note_previous_use);
10341 return true;
10342 }
10343
10344 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10345 Kind, /*isDefinition*/false, KWLoc,
10346 ClassTemplate->getIdentifier())) {
10347 Diag(KWLoc, diag::err_use_with_wrong_tag)
10348 << ClassTemplate
10350 ClassTemplate->getTemplatedDecl()->getKindName());
10351 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10352 diag::note_previous_use);
10353 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10354 }
10355
10356 // C++0x [temp.explicit]p2:
10357 // There are two forms of explicit instantiation: an explicit instantiation
10358 // definition and an explicit instantiation declaration. An explicit
10359 // instantiation declaration begins with the extern keyword. [...]
10360 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10363
10365 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10366 // Check for dllexport class template instantiation declarations,
10367 // except for MinGW mode.
10368 for (const ParsedAttr &AL : Attr) {
10369 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10370 Diag(ExternLoc,
10371 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10372 Diag(AL.getLoc(), diag::note_attribute);
10373 break;
10374 }
10375 }
10376
10377 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10378 Diag(ExternLoc,
10379 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10380 Diag(A->getLocation(), diag::note_attribute);
10381 }
10382 }
10383
10384 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10385 // instantiation declarations for most purposes.
10386 bool DLLImportExplicitInstantiationDef = false;
10388 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10389 // Check for dllimport class template instantiation definitions.
10390 bool DLLImport =
10391 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10392 for (const ParsedAttr &AL : Attr) {
10393 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10394 DLLImport = true;
10395 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10396 // dllexport trumps dllimport here.
10397 DLLImport = false;
10398 break;
10399 }
10400 }
10401 if (DLLImport) {
10403 DLLImportExplicitInstantiationDef = true;
10404 }
10405 }
10406
10407 // Translate the parser's template argument list in our AST format.
10408 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10409 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10410
10411 // Check that the template argument list is well-formed for this
10412 // template.
10414 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10415 /*DefaultArgs=*/{}, false, CTAI,
10416 /*UpdateArgsWithConversions=*/true,
10417 /*ConstraintsNotSatisfied=*/nullptr))
10418 return true;
10419
10420 // Find the class template specialization declaration that
10421 // corresponds to these arguments.
10422 llvm::FoldingSetInsertToken InsertToken;
10424 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
10425
10426 TemplateSpecializationKind PrevDecl_TSK
10427 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10428
10429 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10430 Context.getTargetInfo().getTriple().isOSCygMing()) {
10431 // Check for dllexport class template instantiation definitions in MinGW
10432 // mode, if a previous declaration of the instantiation was seen.
10433 for (const ParsedAttr &AL : Attr) {
10434 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10435 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10436 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10437 } else {
10438 Diag(AL.getLoc(),
10439 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10440 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10441 }
10442 break;
10443 }
10444 }
10445 }
10446
10447 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10448 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10449 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10450 return AL.getKind() == ParsedAttr::AT_DLLExport;
10451 })) {
10452 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10453 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10454 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10455 }
10456 }
10457
10458 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10459 SS.isSet(), TSK))
10460 return true;
10461
10463
10464 bool HasNoEffect = false;
10465 if (PrevDecl) {
10466 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10467 PrevDecl, PrevDecl_TSK,
10468 PrevDecl->getPointOfInstantiation(),
10469 HasNoEffect))
10470 return PrevDecl;
10471
10472 // Even though HasNoEffect == true means that this explicit instantiation
10473 // has no effect on semantics, we go on to put its syntax in the AST.
10474
10475 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10476 PrevDecl_TSK == TSK_Undeclared) {
10477 // Since the only prior class template specialization with these
10478 // arguments was referenced but not declared, reuse that
10479 // declaration node as our own, updating the source location
10480 // for the template name to reflect our new declaration.
10481 // (Other source locations will be updated later.)
10482 Specialization = PrevDecl;
10483 Specialization->setLocation(TemplateNameLoc);
10484 PrevDecl = nullptr;
10485 }
10486
10487 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10488 DLLImportExplicitInstantiationDef) {
10489 // The new specialization might add a dllimport attribute.
10490 HasNoEffect = false;
10491 }
10492 }
10493
10494 if (!Specialization) {
10495 // Create a new class template specialization declaration node for
10496 // this explicit specialization.
10498 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10499 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10501
10502 // A MSInheritanceAttr attached to the previous declaration must be
10503 // propagated to the new node prior to instantiation.
10504 if (PrevDecl) {
10505 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10506 auto *Clone = A->clone(getASTContext());
10507 Clone->setInherited(true);
10508 Specialization->addAttr(Clone);
10509 Consumer.AssignInheritanceModel(Specialization);
10510 }
10511 }
10512
10513 if (!HasNoEffect && !PrevDecl) {
10514 // Insert the new specialization.
10515 ClassTemplate->AddSpecialization(Specialization, InsertToken);
10516 }
10517 }
10518
10519 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10520
10521 // Set source locations for keywords.
10522 Specialization->setExternKeywordLoc(ExternLoc);
10523 Specialization->setTemplateKeywordLoc(TemplateLoc);
10524 Specialization->setBraceRange(SourceRange());
10525
10526 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10529
10530 // Add the explicit instantiation into its lexical context. However,
10531 // since explicit instantiations are never found by name lookup, we
10532 // just put it into the declaration context directly.
10533 Specialization->setLexicalDeclContext(CurContext);
10534 CurContext->addDecl(Specialization);
10535
10536 // Syntax is now OK, so return if it has no other effect on semantics.
10537 if (HasNoEffect) {
10538 // Set the template specialization kind.
10539 Specialization->setTemplateSpecializationKind(TSK);
10540
10542 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10543 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10544 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10545 Context.getCanonicalTagType(Specialization));
10547 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10548 TemplateNameLoc, TSI, TSK);
10549 return Specialization;
10550 }
10551
10552 // C++ [temp.explicit]p3:
10553 // A definition of a class template or class member template
10554 // shall be in scope at the point of the explicit instantiation of
10555 // the class template or class member template.
10556 //
10557 // This check comes when we actually try to perform the
10558 // instantiation.
10560 = cast_or_null<ClassTemplateSpecializationDecl>(
10561 Specialization->getDefinition());
10562 if (!Def)
10564 /*Complain=*/true,
10565 CTAI.StrictPackMatch);
10566 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10567 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10568 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10569 }
10570
10571 // Instantiate the members of this class template specialization.
10572 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10573 Specialization->getDefinition());
10574 if (Def) {
10576 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10577 // TSK_ExplicitInstantiationDefinition
10578 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10580 DLLImportExplicitInstantiationDef)) {
10581 // FIXME: Need to notify the ASTMutationListener that we did this.
10583
10584 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10585 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10586 // An explicit instantiation definition can add a dll attribute to a
10587 // template with a previous instantiation declaration. MinGW doesn't
10588 // allow this.
10589 auto *A = cast<InheritableAttr>(
10591 A->setInherited(true);
10592 Def->addAttr(A);
10594 }
10595 }
10596
10597 // Fix a TSK_ImplicitInstantiation followed by a
10598 // TSK_ExplicitInstantiationDefinition
10599 bool NewlyDLLExported =
10600 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10601 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10602 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10603 // An explicit instantiation definition can add a dll attribute to a
10604 // template with a previous implicit instantiation. MinGW doesn't allow
10605 // this. We limit clang to only adding dllexport, to avoid potentially
10606 // strange codegen behavior. For example, if we extend this conditional
10607 // to dllimport, and we have a source file calling a method on an
10608 // implicitly instantiated template class instance and then declaring a
10609 // dllimport explicit instantiation definition for the same template
10610 // class, the codegen for the method call will not respect the dllimport,
10611 // while it will with cl. The Def will already have the DLL attribute,
10612 // since the Def and Specialization will be the same in the case of
10613 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10614 // attribute to the Specialization; we just need to make it take effect.
10615 assert(Def == Specialization &&
10616 "Def and Specialization should match for implicit instantiation");
10618 }
10619
10620 // In MinGW mode, export the template instantiation if the declaration
10621 // was marked dllexport.
10622 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10623 Context.getTargetInfo().getTriple().isOSCygMing() &&
10624 PrevDecl->hasAttr<DLLExportAttr>()) {
10626 }
10627
10628 // Set the template specialization kind. Make sure it is set before
10629 // instantiating the members which will trigger ASTConsumer callbacks.
10630 Specialization->setTemplateSpecializationKind(TSK);
10631 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10632 } else {
10633
10634 // Set the template specialization kind.
10635 Specialization->setTemplateSpecializationKind(TSK);
10636 }
10637
10639 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10640 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10641 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10642 Context.getCanonicalTagType(Specialization));
10644 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10645 TemplateNameLoc, TSI, TSK);
10646 return Specialization;
10647}
10648
10651 SourceLocation TemplateLoc, unsigned TagSpec,
10652 SourceLocation KWLoc, CXXScopeSpec &SS,
10653 IdentifierInfo *Name, SourceLocation NameLoc,
10654 const ParsedAttributesView &Attr) {
10655
10656 bool Owned = false;
10657 bool IsDependent = false;
10658 Decl *TagD =
10659 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10660 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10661 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10662 false, TypeResult(), /*IsTypeSpecifier*/ false,
10663 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10664 .get();
10665 assert(!IsDependent &&
10666 "explicit instantiation of dependent name not yet handled");
10667
10668 if (!TagD)
10669 return true;
10670
10671 TagDecl *Tag = cast<TagDecl>(TagD);
10672 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10673
10674 if (Tag->isInvalidDecl())
10675 return true;
10676
10678 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10679 if (!Pattern) {
10680 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10681 << Context.getCanonicalTagType(Record);
10682 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10683 return true;
10684 }
10685
10686 // C++0x [temp.explicit]p2:
10687 // If the explicit instantiation is for a class or member class, the
10688 // elaborated-type-specifier in the declaration shall include a
10689 // simple-template-id.
10690 //
10691 // C++98 has the same restriction, just worded differently.
10693 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10694 << Record << SS.getRange();
10695
10696 // C++0x [temp.explicit]p2:
10697 // There are two forms of explicit instantiation: an explicit instantiation
10698 // definition and an explicit instantiation declaration. An explicit
10699 // instantiation declaration begins with the extern keyword. [...]
10703
10704 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10705
10706 // Verify that it is okay to explicitly instantiate here.
10707 CXXRecordDecl *PrevDecl
10708 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10709 if (!PrevDecl && Record->getDefinition())
10710 PrevDecl = Record;
10711 if (PrevDecl) {
10713 bool HasNoEffect = false;
10714 assert(MSInfo && "No member specialization information?");
10715 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10716 PrevDecl,
10718 MSInfo->getPointOfInstantiation(),
10719 HasNoEffect))
10720 return true;
10721 if (HasNoEffect) {
10725 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10726 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10727 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10728 TL.setElaboratedKeywordLoc(KWLoc);
10729 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10730 TL.setNameLoc(NameLoc);
10732 TemplateLoc, NestedNameSpecifierLoc(),
10733 nullptr, NameLoc, TSI, TSK);
10734 return TagD;
10735 }
10736 }
10737
10738 CXXRecordDecl *RecordDef
10739 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10740 if (!RecordDef) {
10741 // C++ [temp.explicit]p3:
10742 // A definition of a member class of a class template shall be in scope
10743 // at the point of an explicit instantiation of the member class.
10744 CXXRecordDecl *Def
10745 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10746 if (!Def) {
10747 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10748 << 0 << Record->getDeclName() << Record->getDeclContext();
10749 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10750 << Pattern;
10751 return true;
10752 } else {
10753 if (InstantiateClass(NameLoc, Record, Def,
10755 TSK))
10756 return true;
10757
10758 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10759 if (!RecordDef)
10760 return true;
10761 }
10762 }
10763
10764 // Instantiate all of the members of the class.
10765 InstantiateClassMembers(NameLoc, RecordDef,
10767
10769 MarkVTableUsed(NameLoc, RecordDef, true);
10770
10773 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10774 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10775 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10776 TL.setElaboratedKeywordLoc(KWLoc);
10777 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10778 TL.setNameLoc(NameLoc);
10780 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10781 NameLoc, TSI, TSK);
10782 return TagD;
10783}
10784
10786 SourceLocation ExternLoc,
10787 SourceLocation TemplateLoc,
10788 Declarator &D) {
10789 // Explicit instantiations always require a name.
10790 // TODO: check if/when DNInfo should replace Name.
10792 DeclarationName Name = NameInfo.getName();
10793 if (!Name) {
10794 if (!D.isInvalidType())
10796 diag::err_explicit_instantiation_requires_name)
10798
10799 return true;
10800 }
10801
10802 // Get the innermost enclosing declaration scope.
10803 S = S->getDeclParent();
10804
10805 // Determine the type of the declaration.
10807 QualType R = T->getType();
10808 if (R.isNull())
10809 return true;
10810
10811 // C++ [dcl.stc]p1:
10812 // A storage-class-specifier shall not be specified in [...] an explicit
10813 // instantiation (14.7.2) directive.
10815 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10816 << Name;
10817 return true;
10818 } else if (D.getDeclSpec().getStorageClassSpec()
10820 // Complain about then remove the storage class specifier.
10821 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10823
10825 }
10826
10827 // C++0x [temp.explicit]p1:
10828 // [...] An explicit instantiation of a function template shall not use the
10829 // inline or constexpr specifiers.
10830 // Presumably, this also applies to member functions of class templates as
10831 // well.
10835 diag::err_explicit_instantiation_inline :
10836 diag::warn_explicit_instantiation_inline_0x)
10838 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10839 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10840 // not already specified.
10842 diag::err_explicit_instantiation_constexpr);
10843
10844 // A deduction guide is not on the list of entities that can be explicitly
10845 // instantiated.
10847 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10848 << /*explicit instantiation*/ 0;
10849 return true;
10850 }
10851
10852 // C++0x [temp.explicit]p2:
10853 // There are two forms of explicit instantiation: an explicit instantiation
10854 // definition and an explicit instantiation declaration. An explicit
10855 // instantiation declaration begins with the extern keyword. [...]
10859
10860 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10862 /*ObjectType=*/QualType());
10863
10864 if (!R->isFunctionType()) {
10865 // C++ [temp.explicit]p1:
10866 // A [...] static data member of a class template can be explicitly
10867 // instantiated from the member definition associated with its class
10868 // template.
10869 // C++1y [temp.explicit]p1:
10870 // A [...] variable [...] template specialization can be explicitly
10871 // instantiated from its template.
10872 if (Previous.isAmbiguous())
10873 return true;
10874
10875 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10876 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10877 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10878
10879 if (!PrevTemplate) {
10880 if (!Prev || !Prev->isStaticDataMember()) {
10881 // We expect to see a static data member here.
10882 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10883 << Name;
10884 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10885 P != PEnd; ++P)
10886 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10887 return true;
10888 }
10889
10891 // FIXME: Check for explicit specialization?
10893 diag::err_explicit_instantiation_data_member_not_instantiated)
10894 << Prev;
10895 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10896 // FIXME: Can we provide a note showing where this was declared?
10897 return true;
10898 }
10899 } else {
10900 // Explicitly instantiate a variable template.
10901
10902 // C++1y [dcl.spec.auto]p6:
10903 // ... A program that uses auto or decltype(auto) in a context not
10904 // explicitly allowed in this section is ill-formed.
10905 //
10906 // This includes auto-typed variable template instantiations.
10907 if (R->isUndeducedType()) {
10908 Diag(T->getTypeLoc().getBeginLoc(),
10909 diag::err_auto_not_allowed_var_inst);
10910 return true;
10911 }
10912
10914 // C++1y [temp.explicit]p3:
10915 // If the explicit instantiation is for a variable, the unqualified-id
10916 // in the declaration shall be a template-id.
10918 diag::err_explicit_instantiation_without_template_id)
10919 << PrevTemplate;
10920 Diag(PrevTemplate->getLocation(),
10921 diag::note_explicit_instantiation_here);
10922 return true;
10923 }
10924
10925 // Translate the parser's template argument list into our AST format.
10926 TemplateArgumentListInfo TemplateArgs =
10928
10929 DeclResult Res =
10930 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10931 TemplateArgs, /*SetWrittenArgs=*/true);
10932 if (Res.isInvalid())
10933 return true;
10934
10935 if (!Res.isUsable()) {
10936 // We somehow specified dependent template arguments in an explicit
10937 // instantiation. This should probably only happen during error
10938 // recovery.
10939 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10940 return true;
10941 }
10942
10943 // Ignore access control bits, we don't need them for redeclaration
10944 // checking.
10945 Prev = cast<VarDecl>(Res.get());
10946 ArgsAsWritten =
10948 }
10949
10950 // C++0x [temp.explicit]p2:
10951 // If the explicit instantiation is for a member function, a member class
10952 // or a static data member of a class template specialization, the name of
10953 // the class template specialization in the qualified-id for the member
10954 // name shall be a simple-template-id.
10955 //
10956 // C++98 has the same restriction, just worded differently.
10957 //
10958 // This does not apply to variable template specializations, where the
10959 // template-id is in the unqualified-id instead.
10960 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10962 diag::ext_explicit_instantiation_without_qualified_id)
10963 << Prev << D.getCXXScopeSpec().getRange();
10964
10965 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10966
10967 // Verify that it is okay to explicitly instantiate here.
10970 bool HasNoEffect = false;
10972 PrevTSK, POI, HasNoEffect))
10973 return true;
10974
10975 if (!HasNoEffect) {
10976 // Instantiate static data member or variable template.
10978 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10979 VTSD->setExternKeywordLoc(ExternLoc);
10980 VTSD->setTemplateKeywordLoc(TemplateLoc);
10981 }
10982
10983 // Merge attributes.
10985 if (PrevTemplate)
10986 ProcessAPINotes(Prev);
10987
10990 }
10991
10992 // Check the new variable specialization against the parsed input.
10993 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10994 Diag(T->getTypeLoc().getBeginLoc(),
10995 diag::err_invalid_var_template_spec_type)
10996 << 0 << PrevTemplate << R << Prev->getType();
10997 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10998 << 2 << PrevTemplate->getDeclName();
10999 return true;
11000 }
11001
11003 Context, CurContext, Prev, ExternLoc, TemplateLoc,
11004 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11005 D.getIdentifierLoc(), T, TSK);
11006 return (Decl *)nullptr;
11007 }
11008
11009 // If the declarator is a template-id, translate the parser's template
11010 // argument list into our AST format.
11011 bool HasExplicitTemplateArgs = false;
11012 TemplateArgumentListInfo TemplateArgs;
11014 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
11015 HasExplicitTemplateArgs = true;
11016 }
11017
11018 // C++ [temp.explicit]p1:
11019 // A [...] function [...] can be explicitly instantiated from its template.
11020 // A member function [...] of a class template can be explicitly
11021 // instantiated from the member definition associated with its class
11022 // template.
11023 UnresolvedSet<8> TemplateMatches;
11024 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
11026 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
11027 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11028 P != PEnd; ++P) {
11029 NamedDecl *Prev = *P;
11030 if (!HasExplicitTemplateArgs) {
11031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11032 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11033 /*AdjustExceptionSpec*/true);
11034 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11035 if (Method->getPrimaryTemplate()) {
11036 TemplateMatches.addDecl(Method, P.getAccess());
11037 } else {
11038 OverloadCandidate &C = NonTemplateMatches.addCandidate();
11039 C.FoundDecl = P.getPair();
11040 C.Function = Method;
11041 C.Viable = true;
11043 if (Method->getTrailingRequiresClause() &&
11045 /*ForOverloadResolution=*/true) ||
11046 !S.IsSatisfied)) {
11047 C.Viable = false;
11049 }
11050 }
11051 }
11052 }
11053 }
11054
11055 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11056 if (!FunTmpl)
11057 continue;
11058
11059 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11060 FunctionDecl *Specialization = nullptr;
11062 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11063 Specialization, Info);
11065 // Keep track of almost-matches.
11066 FailedTemplateCandidates.addCandidate().set(
11067 P.getPair(), FunTmpl->getTemplatedDecl(),
11068 MakeDeductionFailureInfo(Context, TDK, Info));
11069 (void)TDK;
11070 continue;
11071 }
11072
11073 // Target attributes are part of the cuda function signature, so
11074 // the cuda target of the instantiated function must match that of its
11075 // template. Given that C++ template deduction does not take
11076 // target attributes into account, we reject candidates here that
11077 // have a different target.
11078 if (LangOpts.CUDA &&
11079 CUDA().IdentifyTarget(Specialization,
11080 /* IgnoreImplicitHDAttr = */ true) !=
11081 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11082 FailedTemplateCandidates.addCandidate().set(
11083 P.getPair(), FunTmpl->getTemplatedDecl(),
11086 continue;
11087 }
11088
11089 TemplateMatches.addDecl(Specialization, P.getAccess());
11090 }
11091
11092 FunctionDecl *Specialization = nullptr;
11093 if (!NonTemplateMatches.empty()) {
11094 unsigned Msg = 0;
11095 OverloadCandidateDisplayKind DisplayKind;
11097 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11098 Best)) {
11099 case OR_Success:
11100 case OR_Deleted:
11101 Specialization = cast<FunctionDecl>(Best->Function);
11102 break;
11103 case OR_Ambiguous:
11104 Msg = diag::err_explicit_instantiation_ambiguous;
11105 DisplayKind = OCD_AmbiguousCandidates;
11106 break;
11108 Msg = diag::err_explicit_instantiation_no_candidate;
11109 DisplayKind = OCD_AllCandidates;
11110 break;
11111 }
11112 if (Msg) {
11113 PartialDiagnostic Diag = PDiag(Msg) << Name;
11114 NonTemplateMatches.NoteCandidates(
11115 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11116 {});
11117 return true;
11118 }
11119 }
11120
11121 if (!Specialization) {
11122 // Find the most specialized function template specialization.
11124 TemplateMatches.begin(), TemplateMatches.end(),
11125 FailedTemplateCandidates, D.getIdentifierLoc(),
11126 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11127 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11128 PDiag(diag::note_explicit_instantiation_candidate));
11129
11130 if (Result == TemplateMatches.end())
11131 return true;
11132
11133 // Ignore access control bits, we don't need them for redeclaration checking.
11135 }
11136
11137 // C++11 [except.spec]p4
11138 // In an explicit instantiation an exception-specification may be specified,
11139 // but is not required.
11140 // If an exception-specification is specified in an explicit instantiation
11141 // directive, it shall be compatible with the exception-specifications of
11142 // other declarations of that function.
11143 if (auto *FPT = R->getAs<FunctionProtoType>())
11144 if (FPT->hasExceptionSpec()) {
11145 unsigned DiagID =
11146 diag::err_mismatched_exception_spec_explicit_instantiation;
11147 if (getLangOpts().MicrosoftExt)
11148 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11150 PDiag(DiagID) << Specialization->getType(),
11151 PDiag(diag::note_explicit_instantiation_here),
11152 Specialization->getType()->getAs<FunctionProtoType>(),
11153 Specialization->getLocation(), FPT, D.getBeginLoc());
11154 // In Microsoft mode, mismatching exception specifications just cause a
11155 // warning.
11156 if (!getLangOpts().MicrosoftExt && Result)
11157 return true;
11158 }
11159
11160 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11162 diag::err_explicit_instantiation_member_function_not_instantiated)
11164 << (Specialization->getTemplateSpecializationKind() ==
11166 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11167 return true;
11168 }
11169
11170 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11171 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11172 PrevDecl = Specialization;
11173
11174 if (PrevDecl) {
11175 bool HasNoEffect = false;
11177 PrevDecl,
11179 PrevDecl->getPointOfInstantiation(),
11180 HasNoEffect))
11181 return true;
11182
11183 if (HasNoEffect) {
11184 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11185 if (HasExplicitTemplateArgs)
11186 ArgsAsWritten =
11189 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11190 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11191 D.getIdentifierLoc(), T, TSK);
11192 return (Decl *)nullptr;
11193 }
11194 }
11195
11196 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11197 // functions
11198 // valarray<size_t>::valarray(size_t) and
11199 // valarray<size_t>::~valarray()
11200 // that it declared to have internal linkage with the internal_linkage
11201 // attribute. Ignore the explicit instantiation declaration in this case.
11202 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11204 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11205 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11206 RD->isInStdNamespace())
11207 return (Decl*) nullptr;
11208 }
11209
11212
11213 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11214 // instantiation declarations.
11216 Specialization->hasAttr<DLLImportAttr>() &&
11217 Context.getTargetInfo().getCXXABI().isMicrosoft())
11219
11220 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11221 if (Specialization->isDefined()) {
11222 // Let the ASTConsumer know that this function has been explicitly
11223 // instantiated now, and its linkage might have changed.
11224 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11225 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11226 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11227 // be explicitly instantiated.
11228 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11229 RD && RD->isLambda()) {
11230 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11231 << /*instantiation*/ 1;
11232 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11233 return (Decl *)nullptr;
11234 }
11236 }
11237
11238 // C++0x [temp.explicit]p2:
11239 // If the explicit instantiation is for a member function, a member class
11240 // or a static data member of a class template specialization, the name of
11241 // the class template specialization in the qualified-id for the member
11242 // name shall be a simple-template-id.
11243 //
11244 // C++98 has the same restriction, just worded differently.
11245 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11246 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11247 D.getCXXScopeSpec().isSet() &&
11250 diag::ext_explicit_instantiation_without_qualified_id)
11252
11254 *this,
11255 FunTmpl ? (NamedDecl *)FunTmpl
11256 : Specialization->getInstantiatedFromMemberFunction(),
11257 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11258
11259 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11260 if (HasExplicitTemplateArgs)
11261 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11263 TemplateLoc,
11265 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11266 return (Decl *)nullptr;
11267}
11268
11270 const CXXScopeSpec &SS,
11271 const IdentifierInfo *Name,
11272 SourceLocation TagLoc,
11273 SourceLocation NameLoc) {
11274 // This has to hold, because SS is expected to be defined.
11275 assert(Name && "Expected a name in a dependent tag");
11276
11278 if (!NNS)
11279 return true;
11280
11281 if (TUK == TagUseKind::Friend &&
11283 return true;
11284
11286
11287 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11288 Diag(NameLoc, diag::err_dependent_tag_decl)
11289 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11290 return true;
11291 }
11292
11293 // Create the resulting type.
11295 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11296
11297 // Create type-source location information for this type.
11298 TypeLocBuilder TLB;
11300 TL.setElaboratedKeywordLoc(TagLoc);
11302 TL.setNameLoc(NameLoc);
11304}
11305
11307 const CXXScopeSpec &SS,
11308 const IdentifierInfo &II,
11309 SourceLocation IdLoc,
11310 ImplicitTypenameContext IsImplicitTypename) {
11311 if (SS.isInvalid())
11312 return true;
11313
11314 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11315 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11316 << FixItHint::CreateRemoval(TypenameLoc);
11317
11319 TypeSourceInfo *TSI = nullptr;
11320 QualType T =
11323 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11324 /*DeducedTSTContext=*/true);
11325 if (T.isNull())
11326 return true;
11327 return CreateParsedType(T, TSI);
11328}
11329
11332 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11333 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11334 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11335 ASTTemplateArgsPtr TemplateArgsIn,
11336 SourceLocation RAngleLoc) {
11337 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11338 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11339 ? diag::compat_cxx11_typename_outside_of_template
11340 : diag::compat_pre_cxx11_typename_outside_of_template)
11341 << FixItHint::CreateRemoval(TypenameLoc);
11342
11343 // Strangely, non-type results are not ignored by this lookup, so the
11344 // program is ill-formed if it finds an injected-class-name.
11345 if (TypenameLoc.isValid()) {
11346 auto *LookupRD =
11347 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11348 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11349 Diag(TemplateIILoc,
11350 diag::ext_out_of_line_qualified_id_type_names_constructor)
11351 << TemplateII << 0 /*injected-class-name used as template name*/
11352 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11353 }
11354 }
11355
11356 // Translate the parser's template argument list in our AST format.
11357 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11358 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11359
11363 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11364 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11365 if (T.isNull())
11366 return true;
11367
11368 // Provide source-location information for the template specialization type.
11369 TypeLocBuilder Builder;
11371 = Builder.push<TemplateSpecializationTypeLoc>(T);
11372 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11373 TemplateIILoc, TemplateArgs);
11374 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11375 return CreateParsedType(T, TSI);
11376}
11377
11378/// Determine whether this failed name lookup should be treated as being
11379/// disabled by a usage of std::enable_if.
11381 SourceRange &CondRange, Expr *&Cond) {
11382 // We must be looking for a ::type...
11383 if (!II.isStr("type"))
11384 return false;
11385
11386 // ... within an explicitly-written template specialization...
11388 return false;
11389
11390 // FIXME: Look through sugar.
11391 auto EnableIfTSTLoc =
11393 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11394 return false;
11395 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11396
11397 // ... which names a complete class template declaration...
11398 const TemplateDecl *EnableIfDecl =
11399 EnableIfTST->getTemplateName().getAsTemplateDecl();
11400 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11401 return false;
11402
11403 // ... called "enable_if".
11404 const IdentifierInfo *EnableIfII =
11405 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11406 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11407 return false;
11408
11409 // Assume the first template argument is the condition.
11410 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11411
11412 // Dig out the condition.
11413 Cond = nullptr;
11414 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11416 return true;
11417
11418 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11419
11420 // Ignore Boolean literals; they add no value.
11422 Cond = nullptr;
11423
11424 return true;
11425}
11426
11429 SourceLocation KeywordLoc,
11430 NestedNameSpecifierLoc QualifierLoc,
11431 const IdentifierInfo &II,
11432 SourceLocation IILoc,
11433 TypeSourceInfo **TSI,
11434 bool DeducedTSTContext) {
11435 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11436 DeducedTSTContext);
11437 if (T.isNull())
11438 return QualType();
11439
11440 TypeLocBuilder TLB;
11442 auto TL = TLB.push<DependentNameTypeLoc>(T);
11443 TL.setElaboratedKeywordLoc(KeywordLoc);
11444 TL.setQualifierLoc(QualifierLoc);
11445 TL.setNameLoc(IILoc);
11448 TL.setElaboratedKeywordLoc(KeywordLoc);
11449 TL.setQualifierLoc(QualifierLoc);
11450 TL.setNameLoc(IILoc);
11451 } else if (isa<TemplateTypeParmType>(T)) {
11452 // FIXME: There might be a 'typename' keyword here, but we just drop it
11453 // as it can't be represented.
11454 assert(!QualifierLoc);
11455 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11456 } else if (isa<TagType>(T)) {
11457 auto TL = TLB.push<TagTypeLoc>(T);
11458 TL.setElaboratedKeywordLoc(KeywordLoc);
11459 TL.setQualifierLoc(QualifierLoc);
11460 TL.setNameLoc(IILoc);
11461 } else if (isa<TypedefType>(T)) {
11462 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11463 } else {
11464 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11465 }
11466 *TSI = TLB.getTypeSourceInfo(Context, T);
11467 return T;
11468}
11469
11470/// Build the type that describes a C++ typename specifier,
11471/// e.g., "typename T::type".
11474 SourceLocation KeywordLoc,
11475 NestedNameSpecifierLoc QualifierLoc,
11476 const IdentifierInfo &II,
11477 SourceLocation IILoc, bool DeducedTSTContext) {
11478 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11479
11480 CXXScopeSpec SS;
11481 SS.Adopt(QualifierLoc);
11482
11483 DeclContext *Ctx = nullptr;
11484 if (QualifierLoc) {
11485 Ctx = computeDeclContext(SS);
11486 if (!Ctx) {
11487 // If the nested-name-specifier is dependent and couldn't be
11488 // resolved to a type, build a typename type.
11489 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11490 return Context.getDependentNameType(Keyword,
11491 QualifierLoc.getNestedNameSpecifier(),
11492 &II);
11493 }
11494
11495 // If the nested-name-specifier refers to the current instantiation,
11496 // the "typename" keyword itself is superfluous. In C++03, the
11497 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11498 // allows such extraneous "typename" keywords, and we retroactively
11499 // apply this DR to C++03 code with only a warning. In any case we continue.
11500
11501 if (RequireCompleteDeclContext(SS, Ctx))
11502 return QualType();
11503 }
11504
11505 DeclarationName Name(&II);
11506 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11507 if (Ctx)
11508 LookupQualifiedName(Result, Ctx, SS);
11509 else
11510 LookupName(Result, CurScope);
11511 unsigned DiagID = 0;
11512 Decl *Referenced = nullptr;
11513 switch (Result.getResultKind()) {
11515 // If we're looking up 'type' within a template named 'enable_if', produce
11516 // a more specific diagnostic.
11517 SourceRange CondRange;
11518 Expr *Cond = nullptr;
11519 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11520 // If we have a condition, narrow it down to the specific failed
11521 // condition.
11522 if (Cond) {
11523 Expr *FailedCond;
11524 std::string FailedDescription;
11525 std::tie(FailedCond, FailedDescription) =
11527
11528 Diag(FailedCond->getExprLoc(),
11529 diag::err_typename_nested_not_found_requirement)
11530 << FailedDescription
11531 << FailedCond->getSourceRange();
11532 return QualType();
11533 }
11534
11535 Diag(CondRange.getBegin(),
11536 diag::err_typename_nested_not_found_enable_if)
11537 << Ctx << CondRange;
11538 return QualType();
11539 }
11540
11541 DiagID = Ctx ? diag::err_typename_nested_not_found
11542 : diag::err_unknown_typename;
11543 break;
11544 }
11545
11547 // We found a using declaration that is a value. Most likely, the using
11548 // declaration itself is meant to have the 'typename' keyword.
11549 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11550 IILoc);
11551 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11552 << Name << Ctx << FullRange;
11553 if (UnresolvedUsingValueDecl *Using
11554 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11555 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11556 Diag(Loc, diag::note_using_value_decl_missing_typename)
11557 << FixItHint::CreateInsertion(Loc, "typename ");
11558 }
11559 }
11560 // Fall through to create a dependent typename type, from which we can
11561 // recover better.
11562 [[fallthrough]];
11563
11565 // Okay, it's a member of an unknown instantiation.
11566 return Context.getDependentNameType(Keyword,
11567 QualifierLoc.getNestedNameSpecifier(),
11568 &II);
11569
11571 // FXIME: Missing support for UsingShadowDecl on this path?
11572 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11573 // C++ [class.qual]p2:
11574 // In a lookup in which function names are not ignored and the
11575 // nested-name-specifier nominates a class C, if the name specified
11576 // after the nested-name-specifier, when looked up in C, is the
11577 // injected-class-name of C [...] then the name is instead considered
11578 // to name the constructor of class C.
11579 //
11580 // Unlike in an elaborated-type-specifier, function names are not ignored
11581 // in typename-specifier lookup. However, they are ignored in all the
11582 // contexts where we form a typename type with no keyword (that is, in
11583 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11584 //
11585 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11586 // ignore functions, but that appears to be an oversight.
11591 Type, IILoc);
11592 // FIXME: This appears to be the only case where a template type parameter
11593 // can have an elaborated keyword. We should preserve it somehow.
11596 assert(!QualifierLoc);
11598 }
11599 return Context.getTypeDeclType(
11600 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11601 }
11602
11603 // C++ [dcl.type.simple]p2:
11604 // A type-specifier of the form
11605 // typename[opt] nested-name-specifier[opt] template-name
11606 // is a placeholder for a deduced class type [...].
11607 if (getLangOpts().CPlusPlus17) {
11608 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11609 if (!DeducedTSTContext) {
11610 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11611 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11612 Diag(IILoc, diag::err_dependent_deduced_tst)
11614 << QualType(Qualifier.getAsType(), 0);
11615 else
11616 Diag(IILoc, diag::err_deduced_tst)
11619 return QualType();
11620 }
11621 TemplateName Name = Context.getQualifiedTemplateName(
11622 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11623 TemplateName(TD));
11624 return Context.getDeducedTemplateSpecializationType(
11625 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11626 Name);
11627 }
11628 }
11629
11630 DiagID = Ctx ? diag::err_typename_nested_not_type
11631 : diag::err_typename_not_type;
11632 Referenced = Result.getFoundDecl();
11633 break;
11634
11636 DiagID = Ctx ? diag::err_typename_nested_not_type
11637 : diag::err_typename_not_type;
11638 Referenced = *Result.begin();
11639 break;
11640
11642 return QualType();
11643 }
11644
11645 // If we get here, it's because name lookup did not find a
11646 // type. Emit an appropriate diagnostic and return an error.
11647 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11648 IILoc);
11649 if (Ctx)
11650 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11651 else
11652 Diag(IILoc, DiagID) << FullRange << Name;
11653 if (Referenced)
11654 Diag(Referenced->getLocation(),
11655 Ctx ? diag::note_typename_member_refers_here
11656 : diag::note_typename_refers_here)
11657 << Name;
11658 return QualType();
11659}
11660
11661namespace {
11662 // See Sema::RebuildTypeInCurrentInstantiation
11663 class CurrentInstantiationRebuilder
11664 : public TreeTransform<CurrentInstantiationRebuilder> {
11665 SourceLocation Loc;
11666 DeclarationName Entity;
11667
11668 public:
11670
11671 CurrentInstantiationRebuilder(Sema &SemaRef,
11672 SourceLocation Loc,
11673 DeclarationName Entity)
11674 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11675 Loc(Loc), Entity(Entity) { }
11676
11677 /// Determine whether the given type \p T has already been
11678 /// transformed.
11679 ///
11680 /// For the purposes of type reconstruction, a type has already been
11681 /// transformed if it is NULL or if it is not dependent.
11682 bool AlreadyTransformed(QualType T) {
11683 return T.isNull() || !T->isInstantiationDependentType();
11684 }
11685
11686 /// Returns the location of the entity whose type is being
11687 /// rebuilt.
11688 SourceLocation getBaseLocation() { return Loc; }
11689
11690 /// Returns the name of the entity whose type is being rebuilt.
11691 DeclarationName getBaseEntity() { return Entity; }
11692
11693 /// Sets the "base" location and entity when that
11694 /// information is known based on another transformation.
11695 void setBase(SourceLocation Loc, DeclarationName Entity) {
11696 this->Loc = Loc;
11697 this->Entity = Entity;
11698 }
11699
11700 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11701 // Lambdas never need to be transformed.
11702 return E;
11703 }
11704 };
11705} // end anonymous namespace
11706
11708 SourceLocation Loc,
11709 DeclarationName Name) {
11710 if (!T || !T->getType()->isInstantiationDependentType())
11711 return T;
11712
11713 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11714 return Rebuilder.TransformType(T);
11715}
11716
11718 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11719 DeclarationName());
11720 return Rebuilder.TransformExpr(E);
11721}
11722
11724 if (SS.isInvalid())
11725 return true;
11726
11728 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11729 DeclarationName());
11731 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11732 if (!Rebuilt)
11733 return true;
11734
11735 SS.Adopt(Rebuilt);
11736 return false;
11737}
11738
11740 TemplateParameterList *Params) {
11741 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11742 Decl *Param = Params->getParam(I);
11743
11744 // There is nothing to rebuild in a type parameter.
11745 if (isa<TemplateTypeParmDecl>(Param))
11746 continue;
11747
11748 // Rebuild the template parameter list of a template template parameter.
11750 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11752 TTP->getTemplateParameters()))
11753 return true;
11754
11755 continue;
11756 }
11757
11758 // Rebuild the type of a non-type template parameter.
11760 TypeSourceInfo *NewTSI
11762 NTTP->getLocation(),
11763 NTTP->getDeclName());
11764 if (!NewTSI)
11765 return true;
11766
11767 if (NewTSI->getType()->isUndeducedType()) {
11768 // C++17 [temp.dep.expr]p3:
11769 // An id-expression is type-dependent if it contains
11770 // - an identifier associated by name lookup with a non-type
11771 // template-parameter declared with a type that contains a
11772 // placeholder type (7.1.7.4),
11773 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11774 }
11775
11776 if (NewTSI != NTTP->getTypeSourceInfo()) {
11777 NTTP->setTypeSourceInfo(NewTSI);
11778 NTTP->setType(NewTSI->getType());
11779 }
11780 }
11781
11782 return false;
11783}
11784
11785std::string
11787 const TemplateArgumentList &Args) {
11788 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11789}
11790
11791std::string
11793 const TemplateArgument *Args,
11794 unsigned NumArgs) {
11795 SmallString<128> Str;
11796 llvm::raw_svector_ostream Out(Str);
11797
11798 if (!Params || Params->size() == 0 || NumArgs == 0)
11799 return std::string();
11800
11801 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11802 if (I >= NumArgs)
11803 break;
11804
11805 if (I == 0)
11806 Out << "[with ";
11807 else
11808 Out << ", ";
11809
11810 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11811 Out << Id->getName();
11812 } else {
11813 Out << '$' << I;
11814 }
11815
11816 Out << " = ";
11817 Args[I].print(getPrintingPolicy(), Out,
11819 getPrintingPolicy(), Params, I));
11820 }
11821
11822 Out << ']';
11823 return std::string(Out.str());
11824}
11825
11827 CachedTokens &Toks) {
11828 if (!FD)
11829 return;
11830
11831 auto LPT = std::make_unique<LateParsedTemplate>();
11832
11833 // Take tokens to avoid allocations
11834 LPT->Toks.swap(Toks);
11835 LPT->D = FnD;
11836 LPT->FPO = getCurFPFeatures();
11837 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11838
11839 FD->setLateTemplateParsed(true);
11840}
11841
11843 if (!FD)
11844 return;
11845 FD->setLateTemplateParsed(false);
11846}
11847
11849 DeclContext *DC = CurContext;
11850
11851 while (DC) {
11852 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11853 const FunctionDecl *FD = RD->isLocalClass();
11854 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11855 } else if (DC->isTranslationUnit() || DC->isNamespace())
11856 return false;
11857
11858 DC = DC->getParent();
11859 }
11860 return false;
11861}
11862
11863namespace {
11864/// Walk the path from which a declaration was instantiated, and check
11865/// that every explicit specialization along that path is visible. This enforces
11866/// C++ [temp.expl.spec]/6:
11867///
11868/// If a template, a member template or a member of a class template is
11869/// explicitly specialized then that specialization shall be declared before
11870/// the first use of that specialization that would cause an implicit
11871/// instantiation to take place, in every translation unit in which such a
11872/// use occurs; no diagnostic is required.
11873///
11874/// and also C++ [temp.class.spec]/1:
11875///
11876/// A partial specialization shall be declared before the first use of a
11877/// class template specialization that would make use of the partial
11878/// specialization as the result of an implicit or explicit instantiation
11879/// in every translation unit in which such a use occurs; no diagnostic is
11880/// required.
11881class ExplicitSpecializationVisibilityChecker {
11882 Sema &S;
11883 SourceLocation Loc;
11886
11887public:
11888 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11890 : S(S), Loc(Loc), Kind(Kind) {}
11891
11892 void check(NamedDecl *ND) {
11893 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11894 return checkImpl(FD);
11895 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11896 return checkImpl(RD);
11897 if (auto *VD = dyn_cast<VarDecl>(ND))
11898 return checkImpl(VD);
11899 if (auto *ED = dyn_cast<EnumDecl>(ND))
11900 return checkImpl(ED);
11901 }
11902
11903private:
11904 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11905 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11906 : Sema::MissingImportKind::ExplicitSpecialization;
11907 const bool Recover = true;
11908
11909 // If we got a custom set of modules (because only a subset of the
11910 // declarations are interesting), use them, otherwise let
11911 // diagnoseMissingImport intelligently pick some.
11912 if (Modules.empty())
11913 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11914 else
11915 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11916 }
11917
11918 bool CheckMemberSpecialization(const NamedDecl *D) {
11919 return Kind == Sema::AcceptableKind::Visible
11922 }
11923
11924 bool CheckExplicitSpecialization(const NamedDecl *D) {
11925 return Kind == Sema::AcceptableKind::Visible
11928 }
11929
11930 bool CheckDeclaration(const NamedDecl *D) {
11931 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11933 }
11934
11935 // Check a specific declaration. There are three problematic cases:
11936 //
11937 // 1) The declaration is an explicit specialization of a template
11938 // specialization.
11939 // 2) The declaration is an explicit specialization of a member of an
11940 // templated class.
11941 // 3) The declaration is an instantiation of a template, and that template
11942 // is an explicit specialization of a member of a templated class.
11943 //
11944 // We don't need to go any deeper than that, as the instantiation of the
11945 // surrounding class / etc is not triggered by whatever triggered this
11946 // instantiation, and thus should be checked elsewhere.
11947 template<typename SpecDecl>
11948 void checkImpl(SpecDecl *Spec) {
11949 bool IsHiddenExplicitSpecialization = false;
11950 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11951 // Some invalid friend declarations are written as specializations but are
11952 // instantiated implicitly.
11953 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11954 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11955 if (SpecKind == TSK_ExplicitSpecialization) {
11956 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11957 ? !CheckMemberSpecialization(Spec)
11958 : !CheckExplicitSpecialization(Spec);
11959 } else {
11960 checkInstantiated(Spec);
11961 }
11962
11963 if (IsHiddenExplicitSpecialization)
11964 diagnose(Spec->getMostRecentDecl(), false);
11965 }
11966
11967 void checkInstantiated(FunctionDecl *FD) {
11968 if (auto *TD = FD->getPrimaryTemplate())
11969 checkTemplate(TD);
11970 }
11971
11972 void checkInstantiated(CXXRecordDecl *RD) {
11973 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11974 if (!SD)
11975 return;
11976
11977 auto From = SD->getSpecializedTemplateOrPartial();
11978 if (auto *TD = dyn_cast<ClassTemplateDecl *>(From))
11979 checkTemplate(TD);
11980 else if (auto *TD =
11981 dyn_cast<ClassTemplatePartialSpecializationDecl *>(From)) {
11982 if (!CheckDeclaration(TD))
11983 diagnose(TD, true);
11984 checkTemplate(TD);
11985 }
11986 }
11987
11988 void checkInstantiated(VarDecl *RD) {
11989 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11990 if (!SD)
11991 return;
11992
11993 auto From = SD->getSpecializedTemplateOrPartial();
11994 if (auto *TD = dyn_cast<VarTemplateDecl *>(From))
11995 checkTemplate(TD);
11996 else if (auto *TD =
11997 dyn_cast<VarTemplatePartialSpecializationDecl *>(From)) {
11998 if (!CheckDeclaration(TD))
11999 diagnose(TD, true);
12000 checkTemplate(TD);
12001 }
12002 }
12003
12004 void checkInstantiated(EnumDecl *FD) {}
12005
12006 template<typename TemplDecl>
12007 void checkTemplate(TemplDecl *TD) {
12008 if (TD->isMemberSpecialization()) {
12009 if (!CheckMemberSpecialization(TD))
12010 diagnose(TD->getMostRecentDecl(), false);
12011 }
12012 }
12013};
12014} // end anonymous namespace
12015
12017 if (!getLangOpts().Modules)
12018 return;
12019
12020 ExplicitSpecializationVisibilityChecker(*this, Loc,
12022 .check(Spec);
12023}
12024
12026 NamedDecl *Spec) {
12027 if (!getLangOpts().CPlusPlusModules)
12028 return checkSpecializationVisibility(Loc, Spec);
12029
12030 ExplicitSpecializationVisibilityChecker(*this, Loc,
12032 .check(Spec);
12033}
12034
12037 return N->getLocation();
12038 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12040 return FD->getLocation();
12043 return N->getLocation();
12044 }
12045 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12046 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12047 continue;
12048 return CSC.PointOfInstantiation;
12049 }
12050 return N->getLocation();
12051}
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)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
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 ExprResult BuildExpressionFromReflection(Sema &S, const APValue &RV, SourceLocation CaretCaretLoc)
Construct a new reflect expression that refers to the given entity with the given source-location of ...
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 QualType sortBuiltinTemplatePack(ASTContext &Context, ArrayRef< TemplateArgument > InputArgs)
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 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 void diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D)
Diagnose a missing template argument.
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 ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
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:158
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
const void * getReflectionOpaqueOperand() const
Definition APValue.h:787
APSInt & getInt()
Definition APValue.h:573
APSInt & getComplexIntImag()
Definition APValue.h:611
ValueKind getKind() const
Definition APValue.h:537
APFixedPoint & getFixedPoint()
Definition APValue.h:595
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
bool isMemberPointer() const
Definition APValue.h:560
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:167
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
bool isNullPointer() const
Definition APValue.cpp:1162
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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
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:3990
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.
Attr - This represents one attribute.
Definition Attr.h:47
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2424
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2442
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2492
TemplateName getNamedConcept() const
Definition TypeLoc.h:2466
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8527
Pointer to a block type.
Definition TypeBase.h:3653
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:3245
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:2141
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:740
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3924
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:1581
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
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:540
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:609
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
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:531
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, const TypeSourceInfo *TSI)
Definition ExprCXX.cpp:1983
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
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:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
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:187
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
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:1073
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:3362
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, TemplateName 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:3858
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:4622
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:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2261
bool isFileContext() const
Definition DeclBase.h:2199
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:2221
bool isTranslationUnit() const
Definition DeclBase.h:2204
bool isRecord() const
Definition DeclBase.h:2208
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
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2163
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:1315
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1416
ValueDecl * getDecl()
Definition Expr.h:1383
Captures information about "declaration specifiers".
Definition DeclSpec.h:279
bool isVirtualSpecified() const
Definition DeclSpec.h:721
void ClearStorageClassSpecs()
Definition DeclSpec.h:566
bool isNoreturnSpecified() const
Definition DeclSpec.h:734
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:561
SCS getStorageClassSpec() const
Definition DeclSpec.h:552
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:626
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:625
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:735
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:727
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:553
ParsedAttributes & getAttributes()
Definition DeclSpec.h:946
bool isInlineSpecified() const
Definition DeclSpec.h:710
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:562
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:722
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:909
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:713
bool hasExplicitSpecifier() const
Definition DeclSpec.h:724
bool hasConstexprSpecifier() const
Definition DeclSpec.h:910
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:1079
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
T * getAttr() const
Definition DeclBase.h:582
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:1235
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:855
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:825
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:1198
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2807
bool isInvalidDecl() const
Definition DeclBase.h:597
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:457
AccessSpecifier getAccess() const
Definition DeclBase.h:516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
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:936
bool hasAttr() const
Definition DeclBase.h:586
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
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:816
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:839
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2436
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2834
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2165
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2161
bool hasEllipsis() const
Definition DeclSpec.h:2833
bool isInvalidType() const
Definition DeclSpec.h:2822
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2181
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2153
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4159
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3564
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:574
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4109
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4199
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4714
static DependentTemplateIdExpr * Create(const ASTContext &Context, const DeclarationNameInfo &NameInfo, TemplateName Name, const TemplateArgumentListInfo &TemplateArgs)
Definition ExprCXX.cpp:423
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3510
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4457
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4192
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4464
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5262
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:114
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:872
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:3109
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:4110
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:146
ExtVectorType - Extended vector type.
Definition TypeBase.h:4497
Represents a member of a struct/union/class.
Definition Decl.h:3341
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1007
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1086
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
Represents a function declaration or definition.
Definition Decl.h:2082
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2645
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4280
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4609
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4388
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4247
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3820
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4219
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:4453
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2531
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4492
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3174
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4240
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:5181
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5605
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5921
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5917
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:5139
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:3922
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5377
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:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
Represents a linkage specification.
Definition DeclCXX.h:3053
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:4459
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
QualType getPointeeType() const
Definition TypeBase.h:3769
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:242
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:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
NamedDecl * getMostRecentDecl()
Definition Decl.h:503
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:719
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
Represent a C++ namespace.
Definition Decl.h:594
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:8254
Represents a pointer to an Objective C object.
Definition TypeBase.h:8310
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:1223
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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:1431
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:4417
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2664
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
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:8498
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
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:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8758
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3825
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8669
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:8854
QualType getCanonicalType() const
Definition TypeBase.h:8721
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8763
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3818
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
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:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
Represents a struct/union/class.
Definition Decl.h:4506
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4690
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5514
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
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:13924
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8632
A RAII object to temporarily push a declaration context.
Definition Sema.h:3639
Whether and why a template name is required in this lookup.
Definition Sema.h:11650
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11658
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12708
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12742
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7902
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
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:13871
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13322
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2721
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9525
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9529
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9537
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9532
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:9841
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:1498
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:4322
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:2106
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:11621
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12219
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12222
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12226
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:1331
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:229
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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...
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:934
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:774
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:1235
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:12398
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12416
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12406
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12426
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:11671
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11678
@ None
This is not assumed to be a template name.
Definition Sema.h:11673
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11675
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:11607
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:929
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14737
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14725
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14734
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14728
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14752
const LangOptions & getLangOpts() const
Definition Sema.h:927
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:1330
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:1329
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.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
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:649
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:1471
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 CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateName Template, const TemplateArgumentListInfo *TemplateArgs)
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...
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:13962
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:15787
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.
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
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:1332
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:4835
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:6905
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6884
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:14251
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.
static QualType getTypeOfConstantTemplateParameter(const TemplateArgument &Arg)
Determine the declared type of the constant template parameter that Arg names, if any.
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:11648
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:525
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:11831
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11841
@ TPC_FriendFunctionTemplate
Definition Sema.h:11839
@ TPC_ClassTemplateMember
Definition Sema.h:11837
@ TPC_FunctionTemplate
Definition Sema.h:11836
@ TPC_FriendClassTemplate
Definition Sema.h:11838
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11840
friend class InitializationSequence
Definition Sema.h:1613
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)
bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
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:6501
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)
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:6585
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1323
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:3632
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11613
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:9850
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13165
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:8845
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13959
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:4718
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
StringRef getKindName() const
Definition Decl.h:4094
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:5014
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5150
TagKind getTagKind() const
Definition Decl.h:4098
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...
TemplateTemplateParmDecl * getAsTemplateTemplateParmDecl() const
Retrieve the template template parameter that this template name refers to, if any.
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:653
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:3869
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:224
Represents a declaration of a type.
Definition Decl.h:3694
const Type * getTypeForDecl() const
Definition Decl.h:3719
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3728
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:892
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:6549
A container of type source information.
Definition TypeBase.h:8640
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:8651
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:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBooleanType() const
Definition TypeBase.h:9432
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2483
bool isRValueReferenceType() const
Definition TypeBase.h:8938
bool isVoidPointerType() const
Definition Type.cpp:845
bool isArrayType() const
Definition TypeBase.h:9005
bool isPointerType() const
Definition TypeBase.h:8906
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9589
bool isReferenceType() const
Definition TypeBase.h:8930
bool isEnumeralType() const
Definition TypeBase.h:9037
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2282
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:595
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9417
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:9093
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isLValueReferenceType() const
Definition TypeBase.h:8934
bool isBitIntType() const
Definition TypeBase.h:9181
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:9029
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2235
bool isMemberPointerType() const
Definition TypeBase.h:8987
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9438
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:5223
bool isPointerOrReferenceType() const
Definition TypeBase.h:8910
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8902
bool isVectorType() const
Definition TypeBase.h:9045
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9522
bool isNullPtrType() const
Definition TypeBase.h:9332
bool isRecordType() const
Definition TypeBase.h:9033
QualType getUnderlyingType() const
Definition Decl.h:3798
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4393
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:2313
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1110
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1142
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1322
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1319
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1138
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1192
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1162
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
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:464
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:6354
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3978
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3437
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3501
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:934
TLSKind getTLSKind() const
Definition Decl.cpp:2149
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2764
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:2897
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:2792
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:2771
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2890
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:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4398
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,...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1979
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
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
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1843
@ 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:924
@ 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:153
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:597
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1102
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1094
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1088
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1090
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_public
Definition Specifiers.h:128
@ AS_none
Definition Specifiers.h:131
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:252
@ SC_Extern
Definition Specifiers.h:255
@ TSCS_unspecified
Definition Specifiers.h:240
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)
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:444
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6262
@ Enum
The "enum" keyword.
Definition TypeBase.h:6276
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:555
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:1813
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
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:373
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:421
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:425
@ Success
Template argument deduction was successful.
Definition Sema.h:375
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:427
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
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:218
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:834
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:835
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:844
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:6237
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6258
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6251
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6255
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2250
CharacterLiteralKind
Definition Expr.h:1648
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
#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:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
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:651
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
Extra information about a function prototype.
Definition TypeBase.h:5690
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3518
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3535
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3500
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:937
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12257
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12253
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12246
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12243
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12243
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13373
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13477
A stack object to be created when performing template instantiation.
Definition Sema.h:13567
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13720
NamedDecl * Previous
Definition Sema.h:360
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:1121