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
5249 if (DependentScopeDeclRefExpr *ArgExpr =
5250 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5251 SS.Adopt(ArgExpr->getQualifierLoc());
5252 NameInfo = ArgExpr->getNameInfo();
5253 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5254 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5255 if (ArgExpr->isImplicitAccess()) {
5256 SS.Adopt(ArgExpr->getQualifierLoc());
5257 NameInfo = ArgExpr->getMemberNameInfo();
5258 }
5259 }
5260
5261 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5262 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5263 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5264
5265 if (Result.getAsSingle<TypeDecl>() ||
5266 Result.wasNotFoundInCurrentInstantiation()) {
5267 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5268 // Suggest that the user add 'typename' before the NNS.
5270 Diag(Loc, getLangOpts().MSVCCompat
5271 ? diag::ext_ms_template_type_arg_missing_typename
5272 : diag::err_template_arg_must_be_type_suggest)
5273 << FixItHint::CreateInsertion(Loc, "typename ");
5275
5276 // Recover by synthesizing a type using the location information that we
5277 // already have.
5278 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5279 SS.getScopeRep(), II);
5280 TypeLocBuilder TLB;
5282 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5284 TL.setNameLoc(NameInfo.getLoc());
5285 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5286
5287 // Overwrite our input TemplateArgumentLoc so that we can recover
5288 // properly.
5291
5292 break;
5293 }
5294 }
5295 // fallthrough
5296 [[fallthrough]];
5297 }
5298 default: {
5299 // We allow instantiating a template with template argument packs when
5300 // building deduction guides or mapping constraint template parameters.
5301 if (Arg.getKind() == TemplateArgument::Pack &&
5302 (CodeSynthesisContexts.back().Kind ==
5305 SugaredConverted.push_back(Arg);
5306 CanonicalConverted.push_back(Arg);
5307 return false;
5308 }
5309 // We have a template type parameter but the template argument
5310 // is not a type.
5311 SourceRange SR = AL.getSourceRange();
5312 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5314
5315 return true;
5316 }
5317 }
5318
5319 if (CheckTemplateArgument(TSI))
5320 return true;
5321
5322 // Objective-C ARC:
5323 // If an explicitly-specified template argument type is a lifetime type
5324 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5325 if (getLangOpts().ObjCAutoRefCount &&
5326 ArgType->isObjCLifetimeType() &&
5327 !ArgType.getObjCLifetime()) {
5328 Qualifiers Qs;
5330 ArgType = Context.getQualifiedType(ArgType, Qs);
5331 }
5332
5333 SugaredConverted.push_back(TemplateArgument(ArgType));
5334 CanonicalConverted.push_back(
5335 TemplateArgument(Context.getCanonicalType(ArgType)));
5336 return false;
5337}
5338
5339/// Substitute template arguments into the default template argument for
5340/// the given template type parameter.
5341///
5342/// \param SemaRef the semantic analysis object for which we are performing
5343/// the substitution.
5344///
5345/// \param Template the template that we are synthesizing template arguments
5346/// for.
5347///
5348/// \param TemplateLoc the location of the template name that started the
5349/// template-id we are checking.
5350///
5351/// \param RAngleLoc the location of the right angle bracket ('>') that
5352/// terminates the template-id.
5353///
5354/// \param Param the template template parameter whose default we are
5355/// substituting into.
5356///
5357/// \param Converted the list of template arguments provided for template
5358/// parameters that precede \p Param in the template parameter list.
5359///
5360/// \param Output the resulting substituted template argument.
5361///
5362/// \returns true if an error occurred.
5364 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5365 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5366 ArrayRef<TemplateArgument> SugaredConverted,
5367 ArrayRef<TemplateArgument> CanonicalConverted,
5368 TemplateArgumentLoc &Output) {
5369 Output = Param->getDefaultArgument();
5370
5371 // If the argument type is dependent, instantiate it now based
5372 // on the previously-computed template arguments.
5373 if (Output.getArgument().isInstantiationDependent()) {
5374 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5375 SugaredConverted,
5376 SourceRange(TemplateLoc, RAngleLoc));
5377 if (Inst.isInvalid())
5378 return true;
5379
5380 // Only substitute for the innermost template argument list.
5381 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5382 /*Final=*/true);
5383 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5384 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5385
5386 bool ForLambdaCallOperator = false;
5387 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5388 ForLambdaCallOperator = Rec->isLambda();
5389 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5390 !ForLambdaCallOperator);
5391
5392 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5393 Param->getDefaultArgumentLoc(),
5394 Param->getDeclName()))
5395 return true;
5396 }
5397
5398 return false;
5399}
5400
5401/// Substitute template arguments into the default template argument for
5402/// the given non-type template parameter.
5403///
5404/// \param SemaRef the semantic analysis object for which we are performing
5405/// the substitution.
5406///
5407/// \param Template the template that we are synthesizing template arguments
5408/// for.
5409///
5410/// \param TemplateLoc the location of the template name that started the
5411/// template-id we are checking.
5412///
5413/// \param RAngleLoc the location of the right angle bracket ('>') that
5414/// terminates the template-id.
5415///
5416/// \param Param the non-type template parameter whose default we are
5417/// substituting into.
5418///
5419/// \param Converted the list of template arguments provided for template
5420/// parameters that precede \p Param in the template parameter list.
5421///
5422/// \returns the substituted template argument, or NULL if an error occurred.
5424 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5425 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5426 ArrayRef<TemplateArgument> SugaredConverted,
5427 ArrayRef<TemplateArgument> CanonicalConverted,
5428 TemplateArgumentLoc &Output) {
5429 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5430 SugaredConverted,
5431 SourceRange(TemplateLoc, RAngleLoc));
5432 if (Inst.isInvalid())
5433 return true;
5434
5435 // Only substitute for the innermost template argument list.
5436 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5437 /*Final=*/true);
5438 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5439 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5440
5441 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5442 EnterExpressionEvaluationContext ConstantEvaluated(
5444 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5445 TemplateArgLists, Output);
5446}
5447
5448/// Substitute template arguments into the default template argument for
5449/// the given template template parameter.
5450///
5451/// \param SemaRef the semantic analysis object for which we are performing
5452/// the substitution.
5453///
5454/// \param Template the template that we are synthesizing template arguments
5455/// for.
5456///
5457/// \param TemplateLoc the location of the template name that started the
5458/// template-id we are checking.
5459///
5460/// \param RAngleLoc the location of the right angle bracket ('>') that
5461/// terminates the template-id.
5462///
5463/// \param Param the template template parameter whose default we are
5464/// substituting into.
5465///
5466/// \param Converted the list of template arguments provided for template
5467/// parameters that precede \p Param in the template parameter list.
5468///
5469/// \param QualifierLoc Will be set to the nested-name-specifier (with
5470/// source-location information) that precedes the template name.
5471///
5472/// \returns the substituted template argument, or NULL if an error occurred.
5474 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5475 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5477 ArrayRef<TemplateArgument> SugaredConverted,
5478 ArrayRef<TemplateArgument> CanonicalConverted,
5479 NestedNameSpecifierLoc &QualifierLoc) {
5481 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5482 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5483 if (Inst.isInvalid())
5484 return TemplateName();
5485
5486 // Only substitute for the innermost template argument list.
5487 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5488 /*Final=*/true);
5489 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5490 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5491
5492 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5493
5494 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5495 QualifierLoc = A.getTemplateQualifierLoc();
5496 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5498 A.getTemplateNameLoc(), TemplateArgLists);
5499}
5500
5502 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5503 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5504 ArrayRef<TemplateArgument> SugaredConverted,
5505 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5506 HasDefaultArg = false;
5507
5508 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5509 if (!hasReachableDefaultArgument(TypeParm))
5510 return TemplateArgumentLoc();
5511
5512 HasDefaultArg = true;
5513 TemplateArgumentLoc Output;
5514 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5515 RAngleLoc, TypeParm, SugaredConverted,
5516 CanonicalConverted, Output))
5517 return TemplateArgumentLoc();
5518 return Output;
5519 }
5520
5521 if (NonTypeTemplateParmDecl *NonTypeParm
5522 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5523 if (!hasReachableDefaultArgument(NonTypeParm))
5524 return TemplateArgumentLoc();
5525
5526 HasDefaultArg = true;
5527 TemplateArgumentLoc Output;
5528 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5529 RAngleLoc, NonTypeParm, SugaredConverted,
5530 CanonicalConverted, Output))
5531 return TemplateArgumentLoc();
5532 return Output;
5533 }
5534
5535 TemplateTemplateParmDecl *TempTempParm
5537 if (!hasReachableDefaultArgument(TempTempParm))
5538 return TemplateArgumentLoc();
5539
5540 HasDefaultArg = true;
5541 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5542 NestedNameSpecifierLoc QualifierLoc;
5544 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5545 SugaredConverted, CanonicalConverted, QualifierLoc);
5546 if (TName.isNull())
5547 return TemplateArgumentLoc();
5548
5549 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5550 QualifierLoc, A.getTemplateNameLoc());
5551}
5552
5553/// Convert a template-argument that we parsed as a type into a template, if
5554/// possible. C++ permits injected-class-names to perform dual service as
5555/// template template arguments and as template type arguments.
5558 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5559 if (!TagLoc)
5560 return TemplateArgumentLoc();
5561
5562 // If this type was written as an injected-class-name, it can be used as a
5563 // template template argument.
5564 // If this type was written as an injected-class-name, it may have been
5565 // converted to a RecordType during instantiation. If the RecordType is
5566 // *not* wrapped in a TemplateSpecializationType and denotes a class
5567 // template specialization, it must have come from an injected-class-name.
5568
5569 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5570 if (Name.isNull())
5571 return TemplateArgumentLoc();
5572
5573 return TemplateArgumentLoc(Context, Name,
5574 /*TemplateKWLoc=*/SourceLocation(),
5575 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5576}
5577
5580 SourceLocation TemplateLoc,
5581 SourceLocation RAngleLoc,
5582 unsigned ArgumentPackIndex,
5585 // Check template type parameters.
5586 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5587 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5588 CTAI.CanonicalConverted);
5589
5590 const TemplateArgument &Arg = ArgLoc.getArgument();
5591 // Check non-type template parameters.
5592 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5593 // Do substitution on the type of the non-type template parameter
5594 // with the template arguments we've seen thus far. But if the
5595 // template has a dependent context then we cannot substitute yet.
5596 QualType NTTPType = NTTP->getType();
5597 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5598 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5599
5600 if (NTTPType->isInstantiationDependentType()) {
5601 // Do substitution on the type of the non-type template parameter.
5602 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5603 CTAI.SugaredConverted,
5604 SourceRange(TemplateLoc, RAngleLoc));
5605 if (Inst.isInvalid())
5606 return true;
5607
5609 /*Final=*/true);
5610 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5611 // If the parameter is a pack expansion, expand this slice of the pack.
5612 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5613 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5614 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5615 NTTP->getDeclName());
5616 } else {
5617 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5618 NTTP->getDeclName());
5619 }
5620
5621 // If that worked, check the non-type template parameter type
5622 // for validity.
5623 if (!NTTPType.isNull())
5624 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5625 NTTP->getLocation());
5626 if (NTTPType.isNull())
5627 return true;
5628 }
5629
5630 auto checkExpr = [&](Expr *E) -> Expr * {
5631 TemplateArgument SugaredResult, CanonicalResult;
5633 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5634 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5635 // If the current template argument causes an error, give up now.
5636 if (Res.isInvalid())
5637 return nullptr;
5638 CTAI.SugaredConverted.push_back(SugaredResult);
5639 CTAI.CanonicalConverted.push_back(CanonicalResult);
5640 return Res.get();
5641 };
5642
5643 switch (Arg.getKind()) {
5645 llvm_unreachable("Should never see a NULL template argument here");
5646
5648 Expr *E = Arg.getAsExpr();
5649 Expr *R = checkExpr(E);
5650 if (!R)
5651 return true;
5652 // If the resulting expression is new, then use it in place of the
5653 // old expression in the template argument.
5654 if (R != E) {
5655 TemplateArgument TA(R, /*IsCanonical=*/false);
5656 ArgLoc = TemplateArgumentLoc(TA, R);
5657 }
5658 break;
5659 }
5660
5661 // As for the converted NTTP kinds, they still might need another
5662 // conversion, as the new corresponding parameter might be different.
5663 // Ideally, we would always perform substitution starting with sugared types
5664 // and never need these, as we would still have expressions. Since these are
5665 // needed so rarely, it's probably a better tradeoff to just convert them
5666 // back to expressions.
5671 // FIXME: StructuralValue is untested here.
5672 ExprResult R =
5674 assert(R.isUsable());
5675 if (!checkExpr(R.get()))
5676 return true;
5677 break;
5678 }
5679
5682 // We were given a template template argument. It may not be ill-formed;
5683 // see below.
5686 // We have a template argument such as \c T::template X, which we
5687 // parsed as a template template argument. However, since we now
5688 // know that we need a non-type template argument, convert this
5689 // template name into an expression.
5690
5691 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5692 ArgLoc.getTemplateNameLoc());
5693
5694 CXXScopeSpec SS;
5695 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5696 // FIXME: the template-template arg was a DependentTemplateName,
5697 // so it was provided with a template keyword. However, its source
5698 // location is not stored in the template argument structure.
5699 SourceLocation TemplateKWLoc;
5701 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5702 nullptr);
5703
5704 // If we parsed the template argument as a pack expansion, create a
5705 // pack expansion expression.
5708 if (E.isInvalid())
5709 return true;
5710 }
5711
5712 TemplateArgument SugaredResult, CanonicalResult;
5714 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5715 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5716 if (E.isInvalid())
5717 return true;
5718
5719 CTAI.SugaredConverted.push_back(SugaredResult);
5720 CTAI.CanonicalConverted.push_back(CanonicalResult);
5721 break;
5722 }
5723
5724 // We have a template argument that actually does refer to a class
5725 // template, alias template, or template template parameter, and
5726 // therefore cannot be a non-type template argument.
5727 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5728 << ArgLoc.getSourceRange();
5730
5731 return true;
5732
5734 // We have a non-type template parameter but the template
5735 // argument is a type.
5736
5737 // C++ [temp.arg]p2:
5738 // In a template-argument, an ambiguity between a type-id and
5739 // an expression is resolved to a type-id, regardless of the
5740 // form of the corresponding template-parameter.
5741 //
5742 // We warn specifically about this case, since it can be rather
5743 // confusing for users.
5744 QualType T = Arg.getAsType();
5745 SourceRange SR = ArgLoc.getSourceRange();
5746 if (T->isFunctionType())
5747 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5748 else
5749 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5751 return true;
5752 }
5753
5755 llvm_unreachable("Caller must expand template argument packs");
5756 }
5757
5758 return false;
5759 }
5760
5761
5762 // Check template template parameters.
5764
5765 TemplateParameterList *Params = TempParm->getTemplateParameters();
5766 if (TempParm->isExpandedParameterPack())
5767 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5768
5769 // Substitute into the template parameter list of the template
5770 // template parameter, since previously-supplied template arguments
5771 // may appear within the template template parameter.
5772 //
5773 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5774 {
5775 // Set up a template instantiation context.
5777 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5778 CTAI.SugaredConverted,
5779 SourceRange(TemplateLoc, RAngleLoc));
5780 if (Inst.isInvalid())
5781 return true;
5782
5783 Params = SubstTemplateParams(
5784 Params, CurContext,
5786 /*Final=*/true),
5787 /*EvaluateConstraints=*/false);
5788 if (!Params)
5789 return true;
5790 }
5791
5792 // C++1z [temp.local]p1: (DR1004)
5793 // When [the injected-class-name] is used [...] as a template-argument for
5794 // a template template-parameter [...] it refers to the class template
5795 // itself.
5796 if (Arg.getKind() == TemplateArgument::Type) {
5798 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5799 if (!ConvertedArg.getArgument().isNull())
5800 ArgLoc = ConvertedArg;
5801 }
5802
5803 switch (Arg.getKind()) {
5805 llvm_unreachable("Should never see a NULL template argument here");
5806
5809 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5810 CTAI.PartialOrdering,
5811 &CTAI.StrictPackMatch))
5812 return true;
5813
5814 CTAI.SugaredConverted.push_back(Arg);
5815 CTAI.CanonicalConverted.push_back(
5816 Context.getCanonicalTemplateArgument(Arg));
5817 break;
5818
5821 auto Kind = 0;
5822 switch (TempParm->templateParameterKind()) {
5824 Kind = 1;
5825 break;
5827 Kind = 2;
5828 break;
5829 default:
5830 break;
5831 }
5832
5833 // We have a template template parameter but the template
5834 // argument does not refer to a template.
5835 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5836 << Kind << getLangOpts().CPlusPlus11;
5837 return true;
5838 }
5839
5844 llvm_unreachable("non-type argument with template template parameter");
5845
5847 llvm_unreachable("Caller must expand template argument packs");
5848 }
5849
5850 return false;
5851}
5852
5853/// Diagnose a missing template argument.
5854template<typename TemplateParmDecl>
5856 TemplateDecl *TD,
5857 const TemplateParmDecl *D,
5859 // Dig out the most recent declaration of the template parameter; there may be
5860 // declarations of the template that are more recent than TD.
5862 ->getTemplateParameters()
5863 ->getParam(D->getIndex()));
5864
5865 // If there's a default argument that's not reachable, diagnose that we're
5866 // missing a module import.
5868 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5870 D->getDefaultArgumentLoc(), Modules,
5872 /*Recover*/true);
5873 return true;
5874 }
5875
5876 // FIXME: If there's a more recent default argument that *is* visible,
5877 // diagnose that it was declared too late.
5878
5880
5881 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5882 << /*not enough args*/0
5884 << TD;
5885 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5886 return true;
5887}
5888
5889/// Check that the given template argument list is well-formed
5890/// for specializing the given template.
5892 TemplateDecl *Template, SourceLocation TemplateLoc,
5893 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5894 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5895 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5897 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5898 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5900}
5901
5902/// Check that the given template argument list is well-formed
5903/// for specializing the given template.
5906 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5907 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5908 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5910
5912 *ConstraintsNotSatisfied = false;
5913
5914 // Make a copy of the template arguments for processing. Only make the
5915 // changes at the end when successful in matching the arguments to the
5916 // template.
5917 TemplateArgumentListInfo NewArgs = TemplateArgs;
5918
5919 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5920
5921 // C++23 [temp.arg.general]p1:
5922 // [...] The type and form of each template-argument specified in
5923 // a template-id shall match the type and form specified for the
5924 // corresponding parameter declared by the template in its
5925 // template-parameter-list.
5926 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5927 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5928 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5929 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5930 LocalInstantiationScope InstScope(*this, true);
5931 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5932 ParamEnd = Params->end(),
5933 Param = ParamBegin;
5934 Param != ParamEnd;
5935 /* increment in loop */) {
5936 if (size_t ParamIdx = Param - ParamBegin;
5937 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5938 // All written arguments should have been consumed by this point.
5939 assert(ArgIdx == NumArgs && "bad default argument deduction");
5940 if (ParamIdx == DefaultArgs.StartPos) {
5941 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5942 // Default arguments from a DeducedTemplateName are already converted.
5943 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5944 CTAI.SugaredConverted.push_back(DefArg);
5945 CTAI.CanonicalConverted.push_back(
5946 Context.getCanonicalTemplateArgument(DefArg));
5947 ++Param;
5948 }
5949 continue;
5950 }
5951 }
5952
5953 // If we have an expanded parameter pack, make sure we don't have too
5954 // many arguments.
5955 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5956 if (*Expansions == SugaredArgumentPack.size()) {
5957 // We're done with this parameter pack. Pack up its arguments and add
5958 // them to the list.
5959 CTAI.SugaredConverted.push_back(
5960 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5961 SugaredArgumentPack.clear();
5962
5963 CTAI.CanonicalConverted.push_back(
5964 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5965 CanonicalArgumentPack.clear();
5966
5967 // This argument is assigned to the next parameter.
5968 ++Param;
5969 continue;
5970 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5971 // Not enough arguments for this parameter pack.
5972 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5973 << /*not enough args*/0
5975 << Template;
5977 return true;
5978 }
5979 }
5980
5981 // Check for builtins producing template packs in this context, we do not
5982 // support them yet.
5983 if (const NonTypeTemplateParmDecl *NTTP =
5984 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5985 NTTP && NTTP->isPackExpansion()) {
5986 auto TL = NTTP->getTypeSourceInfo()
5987 ->getTypeLoc()
5990 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5991 for (const auto &UPP : Unexpanded) {
5992 auto *TST = dyn_cast<const TemplateSpecializationType *>(UPP.first);
5993 if (!TST)
5994 continue;
5995 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5996 // Expanding a built-in pack in this context is not yet supported.
5997 Diag(TL.getEllipsisLoc(),
5998 diag::err_unsupported_builtin_template_pack_expansion)
5999 << TST->getTemplateName();
6000 return true;
6001 }
6002 }
6003
6004 if (ArgIdx < NumArgs) {
6005 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
6006 bool NonPackParameter =
6007 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
6008 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
6009
6010 if (ArgIsExpansion && CTAI.MatchingTTP) {
6011 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
6012 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
6013 ++Param) {
6014 TemplateArgument &Arg = Args[Param - First];
6015 Arg = ArgLoc.getArgument();
6016 if (!(*Param)->isTemplateParameterPack() ||
6017 getExpandedPackSize(*Param))
6018 Arg = Arg.getPackExpansionPattern();
6019 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
6020 SaveAndRestore _1(CTAI.PartialOrdering, false);
6021 SaveAndRestore _2(CTAI.MatchingTTP, true);
6022 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
6023 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6025 return true;
6026 Arg = NewArgLoc.getArgument();
6027 CTAI.CanonicalConverted.back().setIsDefaulted(
6028 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6029 CTAI.CanonicalConverted,
6030 Params->getDepth()));
6031 }
6032 ArgLoc = TemplateArgumentLoc(
6035 } else {
6036 SaveAndRestore _1(CTAI.PartialOrdering, false);
6037 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6038 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6040 return true;
6041 CTAI.CanonicalConverted.back().setIsDefaulted(
6042 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6043 *Param, CTAI.CanonicalConverted,
6044 Params->getDepth()));
6045 if (ArgIsExpansion && NonPackParameter) {
6046 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6047 // alias template, builtin template, or concept, and it's not part of
6048 // a parameter pack. This can't be canonicalized, so reject it now.
6050 Template)) {
6051 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6053 : 0;
6054 Diag(ArgLoc.getLocation(),
6055 diag::err_template_expansion_into_fixed_list)
6056 << DiagSelect << ArgLoc.getSourceRange();
6058 return true;
6059 }
6060 }
6061 }
6062
6063 // We're now done with this argument.
6064 ++ArgIdx;
6065
6066 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6067 // Directly convert the remaining arguments, because we don't know what
6068 // parameters they'll match up with.
6069
6070 if (!SugaredArgumentPack.empty()) {
6071 // If we were part way through filling in an expanded parameter pack,
6072 // fall back to just producing individual arguments.
6073 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6074 SugaredArgumentPack.begin(),
6075 SugaredArgumentPack.end());
6076 SugaredArgumentPack.clear();
6077
6078 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6079 CanonicalArgumentPack.begin(),
6080 CanonicalArgumentPack.end());
6081 CanonicalArgumentPack.clear();
6082 }
6083
6084 while (ArgIdx < NumArgs) {
6085 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6086 CTAI.SugaredConverted.push_back(Arg);
6087 CTAI.CanonicalConverted.push_back(
6088 Context.getCanonicalTemplateArgument(Arg));
6089 ++ArgIdx;
6090 }
6091
6092 return false;
6093 }
6094
6095 if ((*Param)->isTemplateParameterPack()) {
6096 // The template parameter was a template parameter pack, so take the
6097 // deduced argument and place it on the argument pack. Note that we
6098 // stay on the same template parameter so that we can deduce more
6099 // arguments.
6100 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6101 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6102 } else {
6103 // Move to the next template parameter.
6104 ++Param;
6105 }
6106 continue;
6107 }
6108
6109 // If we're checking a partial template argument list, we're done.
6110 if (PartialTemplateArgs) {
6111 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6112 CTAI.SugaredConverted.push_back(
6113 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6114 CTAI.CanonicalConverted.push_back(
6115 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6116 }
6117 return false;
6118 }
6119
6120 // If we have a template parameter pack with no more corresponding
6121 // arguments, just break out now and we'll fill in the argument pack below.
6122 if ((*Param)->isTemplateParameterPack()) {
6123 assert(!getExpandedPackSize(*Param) &&
6124 "Should have dealt with this already");
6125
6126 // A non-expanded parameter pack before the end of the parameter list
6127 // only occurs for an ill-formed template parameter list, unless we've
6128 // got a partial argument list for a function template, so just bail out.
6129 if (Param + 1 != ParamEnd) {
6130 assert(
6131 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6132 "Concept templates must have parameter packs at the end.");
6133 return true;
6134 }
6135
6136 CTAI.SugaredConverted.push_back(
6137 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6138 SugaredArgumentPack.clear();
6139
6140 CTAI.CanonicalConverted.push_back(
6141 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6142 CanonicalArgumentPack.clear();
6143
6144 ++Param;
6145 continue;
6146 }
6147
6148 // Check whether we have a default argument.
6149 bool HasDefaultArg;
6150
6151 // Retrieve the default template argument from the template
6152 // parameter. For each kind of template parameter, we substitute the
6153 // template arguments provided thus far and any "outer" template arguments
6154 // (when the template parameter was part of a nested template) into
6155 // the default argument.
6157 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6158 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6159
6160 if (Arg.getArgument().isNull()) {
6161 if (!HasDefaultArg) {
6162 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6163 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6164 NewArgs);
6165 if (NonTypeTemplateParmDecl *NTTP =
6166 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6167 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6168 NewArgs);
6169 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6171 NewArgs);
6172 }
6173 return true;
6174 }
6175
6176 // Introduce an instantiation record that describes where we are using
6177 // the default template argument. We're not actually instantiating a
6178 // template here, we just create this object to put a note into the
6179 // context stack.
6180 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6181 CTAI.SugaredConverted,
6182 SourceRange(TemplateLoc, RAngleLoc));
6183 if (Inst.isInvalid())
6184 return true;
6185
6186 SaveAndRestore _1(CTAI.PartialOrdering, false);
6187 SaveAndRestore _2(CTAI.MatchingTTP, false);
6188 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6189 // Check the default template argument.
6190 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6191 CTAI, CTAK_Specified))
6192 return true;
6193
6194 CTAI.SugaredConverted.back().setIsDefaulted(true);
6195 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6196
6197 // Core issue 150 (assumed resolution): if this is a template template
6198 // parameter, keep track of the default template arguments from the
6199 // template definition.
6200 if (isTemplateTemplateParameter)
6201 NewArgs.addArgument(Arg);
6202
6203 // Move to the next template parameter and argument.
6204 ++Param;
6205 ++ArgIdx;
6206 }
6207
6208 // If we're performing a partial argument substitution, allow any trailing
6209 // pack expansions; they might be empty. This can happen even if
6210 // PartialTemplateArgs is false (the list of arguments is complete but
6211 // still dependent).
6212 if (CTAI.MatchingTTP ||
6214 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6215 while (ArgIdx < NumArgs &&
6216 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6217 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6218 CTAI.SugaredConverted.push_back(Arg);
6219 CTAI.CanonicalConverted.push_back(
6220 Context.getCanonicalTemplateArgument(Arg));
6221 }
6222 }
6223
6224 // If we have any leftover arguments, then there were too many arguments.
6225 // Complain and fail.
6226 if (ArgIdx < NumArgs) {
6227 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6228 << /*too many args*/1
6230 << Template
6231 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6233 return true;
6234 }
6235
6236 // No problems found with the new argument list, propagate changes back
6237 // to caller.
6238 if (UpdateArgsWithConversions)
6239 TemplateArgs = std::move(NewArgs);
6240
6241 if (!PartialTemplateArgs) {
6242 // Setup the context/ThisScope for the case where we are needing to
6243 // re-instantiate constraints outside of normal instantiation.
6244 DeclContext *NewContext = Template->getDeclContext();
6245
6246 // If this template is in a template, make sure we extract the templated
6247 // decl.
6248 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6249 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6250 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6251
6252 Qualifiers ThisQuals;
6253 if (const auto *Method =
6254 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6255 ThisQuals = Method->getMethodQualifiers();
6256
6257 ContextRAII Context(*this, NewContext);
6258 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6259
6261 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6262 /*RelativeToPrimary=*/true,
6263 /*Pattern=*/nullptr,
6264 /*ForConceptInstantiation=*/true);
6265 if (!isa<ConceptDecl>(Template) &&
6267 Template, MLTAL,
6268 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6271 return true;
6272 }
6273 }
6274
6275 return false;
6276}
6277
6278namespace {
6279 class UnnamedLocalNoLinkageFinder
6280 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6281 {
6282 Sema &S;
6283 SourceRange SR;
6284
6286
6287 public:
6288 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6289
6290 bool Visit(QualType T) {
6291 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6292 }
6293
6294#define TYPE(Class, Parent) \
6295 bool Visit##Class##Type(const Class##Type *);
6296#define ABSTRACT_TYPE(Class, Parent) \
6297 bool Visit##Class##Type(const Class##Type *) { return false; }
6298#define NON_CANONICAL_TYPE(Class, Parent) \
6299 bool Visit##Class##Type(const Class##Type *) { return false; }
6300#include "clang/AST/TypeNodes.inc"
6301
6302 bool VisitTagDecl(const TagDecl *Tag);
6303 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6304 };
6305} // end anonymous namespace
6306
6307bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6308 return false;
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6312 return Visit(T->getElementType());
6313}
6314
6315bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6316 return Visit(T->getPointeeType());
6317}
6318
6319bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6320 const BlockPointerType* T) {
6321 return Visit(T->getPointeeType());
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6325 const LValueReferenceType* T) {
6326 return Visit(T->getPointeeType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6330 const RValueReferenceType* T) {
6331 return Visit(T->getPointeeType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6335 const MemberPointerType *T) {
6336 if (Visit(T->getPointeeType()))
6337 return true;
6338 if (auto *RD = T->getMostRecentCXXRecordDecl())
6339 return VisitTagDecl(RD);
6340 return VisitNestedNameSpecifier(T->getQualifier());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6344 const ConstantArrayType* T) {
6345 return Visit(T->getElementType());
6346}
6347
6348bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6349 const IncompleteArrayType* T) {
6350 return Visit(T->getElementType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6354 const VariableArrayType* T) {
6355 return Visit(T->getElementType());
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6359 const DependentSizedArrayType* T) {
6360 return Visit(T->getElementType());
6361}
6362
6363bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6365 return Visit(T->getElementType());
6366}
6367
6368bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6369 const DependentSizedMatrixType *T) {
6370 return Visit(T->getElementType());
6371}
6372
6373bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6375 return Visit(T->getPointeeType());
6376}
6377
6378bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6379 return Visit(T->getElementType());
6380}
6381
6382bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6383 const DependentVectorType *T) {
6384 return Visit(T->getElementType());
6385}
6386
6387bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6388 return Visit(T->getElementType());
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6392 const ConstantMatrixType *T) {
6393 return Visit(T->getElementType());
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6397 const FunctionProtoType* T) {
6398 for (const auto &A : T->param_types()) {
6399 if (Visit(A))
6400 return true;
6401 }
6402
6403 return Visit(T->getReturnType());
6404}
6405
6406bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6407 const FunctionNoProtoType* T) {
6408 return Visit(T->getReturnType());
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6412 const UnresolvedUsingType*) {
6413 return false;
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6417 return false;
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6421 return Visit(T->getUnmodifiedType());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6425 return false;
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6429 const PackIndexingType *) {
6430 return false;
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6434 const UnaryTransformType*) {
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6439 return Visit(T->getDeducedType());
6440}
6441
6442bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6443 const DeducedTemplateSpecializationType *T) {
6444 return Visit(T->getDeducedType());
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6448 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6452 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6456 const TemplateTypeParmType*) {
6457 return false;
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6461 const SubstTemplateTypeParmPackType *) {
6462 return false;
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6466 const SubstBuiltinTemplatePackType *) {
6467 return false;
6468}
6469
6470bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6471 const TemplateSpecializationType*) {
6472 return false;
6473}
6474
6475bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6476 const InjectedClassNameType* T) {
6477 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6478}
6479
6480bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6481 const DependentNameType* T) {
6482 return VisitNestedNameSpecifier(T->getQualifier());
6483}
6484
6485bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6486 const PackExpansionType* T) {
6487 return Visit(T->getPattern());
6488}
6489
6490bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6491 return false;
6492}
6493
6494bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6495 const ObjCInterfaceType *) {
6496 return false;
6497}
6498
6499bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6500 const ObjCObjectPointerType *) {
6501 return false;
6502}
6503
6504bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6505 return Visit(T->getValueType());
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6509 const OverflowBehaviorType *T) {
6510 return Visit(T->getUnderlyingType());
6511}
6512
6513bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6514 return false;
6515}
6516
6517bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6518 return false;
6519}
6520
6521bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6522 const ArrayParameterType *T) {
6523 return VisitConstantArrayType(T);
6524}
6525
6526bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6527 const DependentBitIntType *T) {
6528 return false;
6529}
6530
6531bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6532 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6533 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6534 ? diag::warn_cxx98_compat_template_arg_local_type
6535 : diag::ext_template_arg_local_type)
6536 << S.Context.getCanonicalTagType(Tag) << SR;
6537 return true;
6538 }
6539
6540 if (!Tag->hasNameForLinkage()) {
6541 S.Diag(SR.getBegin(),
6542 S.getLangOpts().CPlusPlus11 ?
6543 diag::warn_cxx98_compat_template_arg_unnamed_type :
6544 diag::ext_template_arg_unnamed_type) << SR;
6545 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6546 return true;
6547 }
6548
6549 return false;
6550}
6551
6552bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6553 NestedNameSpecifier NNS) {
6554 switch (NNS.getKind()) {
6559 return false;
6561 return Visit(QualType(NNS.getAsType(), 0));
6562 }
6563 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6564}
6565
6566bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6567 const HLSLAttributedResourceType *T) {
6568 if (T->hasContainedType() && Visit(T->getContainedType()))
6569 return true;
6570 return Visit(T->getWrappedType());
6571}
6572
6573bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6574 const HLSLInlineSpirvType *T) {
6575 for (auto &Operand : T->getOperands())
6576 if (Operand.isConstant() && Operand.isLiteral())
6577 if (Visit(Operand.getResultType()))
6578 return true;
6579 return false;
6580}
6581
6583 assert(ArgInfo && "invalid TypeSourceInfo");
6584 QualType Arg = ArgInfo->getType();
6585 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6586 QualType CanonArg = Context.getCanonicalType(Arg);
6587
6588 if (CanonArg->isVariablyModifiedType()) {
6589 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6590 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6591 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6592 }
6593
6594 // C++03 [temp.arg.type]p2:
6595 // A local type, a type with no linkage, an unnamed type or a type
6596 // compounded from any of these types shall not be used as a
6597 // template-argument for a template type-parameter.
6598 //
6599 // C++11 allows these, and even in C++03 we allow them as an extension with
6600 // a warning.
6601 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6602 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6603 (void)Finder.Visit(CanonArg);
6604 }
6605
6606 return false;
6607}
6608
6614
6615/// Determine whether the given template argument is a null pointer
6616/// value of the appropriate type.
6619 QualType ParamType, Expr *Arg,
6620 Decl *Entity = nullptr) {
6621 if (Arg->isValueDependent() || Arg->isTypeDependent())
6622 return NPV_NotNullPointer;
6623
6624 // dllimport'd entities aren't constant but are available inside of template
6625 // arguments.
6626 if (Entity && Entity->hasAttr<DLLImportAttr>())
6627 return NPV_NotNullPointer;
6628
6629 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6630 llvm_unreachable(
6631 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6632
6633 if (!S.getLangOpts().CPlusPlus11)
6634 return NPV_NotNullPointer;
6635
6636 // Determine whether we have a constant expression.
6638 if (ArgRV.isInvalid())
6639 return NPV_Error;
6640 Arg = ArgRV.get();
6641
6642 Expr::EvalResult EvalResult;
6644 EvalResult.Diag = &Notes;
6645 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6646 EvalResult.HasSideEffects) {
6647 SourceLocation DiagLoc = Arg->getExprLoc();
6648
6649 // If our only note is the usual "invalid subexpression" note, just point
6650 // the caret at its location rather than producing an essentially
6651 // redundant note.
6652 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6653 diag::note_invalid_subexpr_in_const_expr) {
6654 DiagLoc = Notes[0].first;
6655 Notes.clear();
6656 }
6657
6658 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6659 << Arg->getType() << Arg->getSourceRange();
6660 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6661 S.Diag(Notes[I].first, Notes[I].second);
6662
6664 return NPV_Error;
6665 }
6666
6667 // C++11 [temp.arg.nontype]p1:
6668 // - an address constant expression of type std::nullptr_t
6669 if (Arg->getType()->isNullPtrType())
6670 return NPV_NullPointer;
6671
6672 // - a constant expression that evaluates to a null pointer value (4.10); or
6673 // - a constant expression that evaluates to a null member pointer value
6674 // (4.11); or
6675 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6676 (EvalResult.Val.isMemberPointer() &&
6677 !EvalResult.Val.getMemberPointerDecl())) {
6678 // If our expression has an appropriate type, we've succeeded.
6679 bool ObjCLifetimeConversion;
6680 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6681 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6682 ObjCLifetimeConversion))
6683 return NPV_NullPointer;
6684
6685 // The types didn't match, but we know we got a null pointer; complain,
6686 // then recover as if the types were correct.
6687 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6688 << Arg->getType() << ParamType << Arg->getSourceRange();
6690 return NPV_NullPointer;
6691 }
6692
6693 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6694 // We found a pointer that isn't null, but doesn't refer to an object.
6695 // We could just return NPV_NotNullPointer, but we can print a better
6696 // message with the information we have here.
6697 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6698 << EvalResult.Val.getAsString(S.Context, ParamType);
6700 return NPV_Error;
6701 }
6702
6703 // If we don't have a null pointer value, but we do have a NULL pointer
6704 // constant, suggest a cast to the appropriate type.
6706 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6707 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6708 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6710 ")");
6712 return NPV_NullPointer;
6713 }
6714
6715 // FIXME: If we ever want to support general, address-constant expressions
6716 // as non-type template arguments, we should return the ExprResult here to
6717 // be interpreted by the caller.
6718 return NPV_NotNullPointer;
6719}
6720
6721/// Checks whether the given template argument is compatible with its
6722/// template parameter.
6723static bool
6725 QualType ParamType, Expr *ArgIn,
6726 Expr *Arg, QualType ArgType) {
6727 bool ObjCLifetimeConversion;
6728 if (ParamType->isPointerType() &&
6729 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6730 S.IsQualificationConversion(ArgType, ParamType, false,
6731 ObjCLifetimeConversion)) {
6732 // For pointer-to-object types, qualification conversions are
6733 // permitted.
6734 } else {
6735 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6736 if (!ParamRef->getPointeeType()->isFunctionType()) {
6737 // C++ [temp.arg.nontype]p5b3:
6738 // For a non-type template-parameter of type reference to
6739 // object, no conversions apply. The type referred to by the
6740 // reference may be more cv-qualified than the (otherwise
6741 // identical) type of the template- argument. The
6742 // template-parameter is bound directly to the
6743 // template-argument, which shall be an lvalue.
6744
6745 // FIXME: Other qualifiers?
6746 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6747 unsigned ArgQuals = ArgType.getCVRQualifiers();
6748
6749 if ((ParamQuals | ArgQuals) != ParamQuals) {
6750 S.Diag(Arg->getBeginLoc(),
6751 diag::err_template_arg_ref_bind_ignores_quals)
6752 << ParamType << Arg->getType() << Arg->getSourceRange();
6754 return true;
6755 }
6756 }
6757 }
6758
6759 // At this point, the template argument refers to an object or
6760 // function with external linkage. We now need to check whether the
6761 // argument and parameter types are compatible.
6762 if (!S.Context.hasSameUnqualifiedType(ArgType,
6763 ParamType.getNonReferenceType())) {
6764 // We can't perform this conversion or binding.
6765 if (ParamType->isReferenceType())
6766 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6767 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6768 else
6769 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6770 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6772 return true;
6773 }
6774 }
6775
6776 return false;
6777}
6778
6779/// Checks whether the given template argument is the address
6780/// of an object or function according to C++ [temp.arg.nontype]p1.
6782 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6783 bool IsSpecified, TemplateArgument &SugaredConverted,
6784 TemplateArgument &CanonicalConverted) {
6785 Expr *Arg = ArgIn;
6786 QualType ArgType = Arg->getType();
6787
6788 bool AddressTaken = false;
6789 SourceLocation AddrOpLoc;
6790 if (S.getLangOpts().MicrosoftExt) {
6791 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6792 // dereference and address-of operators.
6793 Arg = Arg->IgnoreParenCasts();
6794
6795 bool ExtWarnMSTemplateArg = false;
6796 UnaryOperatorKind FirstOpKind;
6797 SourceLocation FirstOpLoc;
6798 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6799 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6800 if (UnOpKind == UO_Deref)
6801 ExtWarnMSTemplateArg = true;
6802 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6803 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6804 if (!AddrOpLoc.isValid()) {
6805 FirstOpKind = UnOpKind;
6806 FirstOpLoc = UnOp->getOperatorLoc();
6807 }
6808 } else
6809 break;
6810 }
6811 if (FirstOpLoc.isValid()) {
6812 if (ExtWarnMSTemplateArg)
6813 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6814 << ArgIn->getSourceRange();
6815
6816 if (FirstOpKind == UO_AddrOf)
6817 AddressTaken = true;
6818 else if (Arg->getType()->isPointerType()) {
6819 // We cannot let pointers get dereferenced here, that is obviously not a
6820 // constant expression.
6821 assert(FirstOpKind == UO_Deref);
6822 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6823 << Arg->getSourceRange();
6824 }
6825 }
6826 } else {
6827 // See through any implicit casts we added to fix the type.
6828 // Also ignore parentheses for deduced template arguments.
6829 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6830
6831 // C++ [temp.arg.nontype]p1:
6832 //
6833 // A template-argument for a non-type, non-template
6834 // template-parameter shall be one of: [...]
6835 //
6836 // -- the address of an object or function with external
6837 // linkage, including function templates and function
6838 // template-ids but excluding non-static class members,
6839 // expressed as & id-expression where the & is optional if
6840 // the name refers to a function or array, or if the
6841 // corresponding template-parameter is a reference; or
6842
6843 // In C++98/03 mode, give an extension warning on any extra parentheses.
6844 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6845 if (IsSpecified) {
6846 bool ExtraParens = false;
6847 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6848 if (!ExtraParens) {
6849 S.DiagCompat(Arg->getBeginLoc(),
6850 diag_compat::template_arg_extra_parens)
6851 << Arg->getSourceRange();
6852 ExtraParens = true;
6853 }
6854
6855 Arg = Parens->getSubExpr();
6856 }
6857 }
6858
6859 while (SubstNonTypeTemplateParmExpr *subst =
6860 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6861 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6862
6863 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6864 if (UnOp->getOpcode() == UO_AddrOf) {
6865 Arg = UnOp->getSubExpr();
6866 AddressTaken = true;
6867 AddrOpLoc = UnOp->getOperatorLoc();
6868 }
6869 }
6870
6871 while (SubstNonTypeTemplateParmExpr *subst =
6872 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6873 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6874 }
6875
6876 ValueDecl *Entity = nullptr;
6877 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6878 Entity = DRE->getDecl();
6879 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6880 Entity = CUE->getGuidDecl();
6881
6882 // If our parameter has pointer type, check for a null template value.
6883 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6884 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6885 Entity)) {
6886 case NPV_NullPointer:
6887 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6888 SugaredConverted = TemplateArgument(ParamType,
6889 /*isNullPtr=*/true);
6890 CanonicalConverted =
6892 /*isNullPtr=*/true);
6893 return false;
6894
6895 case NPV_Error:
6896 return true;
6897
6898 case NPV_NotNullPointer:
6899 break;
6900 }
6901 }
6902
6903 // Stop checking the precise nature of the argument if it is value dependent,
6904 // it should be checked when instantiated.
6905 if (Arg->isValueDependent()) {
6906 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6907 CanonicalConverted =
6908 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6909 return false;
6910 }
6911
6912 if (!Entity) {
6913 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6914 << Arg->getSourceRange();
6916 return true;
6917 }
6918
6919 // Cannot refer to non-static data members
6920 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6921 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6922 << Entity << Arg->getSourceRange();
6924 return true;
6925 }
6926
6927 // Cannot refer to non-static member functions
6928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6929 if (!Method->isStatic()) {
6930 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6931 << Method << Arg->getSourceRange();
6933 return true;
6934 }
6935 }
6936
6937 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6938 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6939 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6940
6941 // A non-type template argument must refer to an object or function.
6942 if (!Func && !Var && !Guid) {
6943 // We found something, but we don't know specifically what it is.
6944 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6945 << Arg->getSourceRange();
6946 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6947 return true;
6948 }
6949
6950 // Address / reference template args must have external linkage in C++98.
6951 if (Entity->getFormalLinkage() == Linkage::Internal) {
6952 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_object_internal)
6953 << !Func << Entity << Arg->getSourceRange();
6954 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6955 << !Func;
6956 } else if (!Entity->hasLinkage()) {
6957 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6958 << !Func << Entity << Arg->getSourceRange();
6959 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6960 << !Func;
6961 return true;
6962 }
6963
6964 if (Var) {
6965 // A value of reference type is not an object.
6966 if (Var->getType()->isReferenceType()) {
6967 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6968 << Var->getType() << Arg->getSourceRange();
6970 return true;
6971 }
6972
6973 // A template argument must have static storage duration.
6974 if (Var->getTLSKind()) {
6975 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6976 << Arg->getSourceRange();
6977 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6978 return true;
6979 }
6980 }
6981
6982 if (AddressTaken && ParamType->isReferenceType()) {
6983 // If we originally had an address-of operator, but the
6984 // parameter has reference type, complain and (if things look
6985 // like they will work) drop the address-of operator.
6986 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6987 ParamType.getNonReferenceType())) {
6988 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6989 << ParamType;
6991 return true;
6992 }
6993
6994 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6995 << ParamType
6996 << FixItHint::CreateRemoval(AddrOpLoc);
6998
6999 ArgType = Entity->getType();
7000 }
7001
7002 // If the template parameter has pointer type, either we must have taken the
7003 // address or the argument must decay to a pointer.
7004 if (!AddressTaken && ParamType->isPointerType()) {
7005 if (Func) {
7006 // Function-to-pointer decay.
7007 ArgType = S.Context.getPointerType(Func->getType());
7008 } else if (Entity->getType()->isArrayType()) {
7009 // Array-to-pointer decay.
7010 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7011 } else {
7012 // If the template parameter has pointer type but the address of
7013 // this object was not taken, complain and (possibly) recover by
7014 // taking the address of the entity.
7015 ArgType = S.Context.getPointerType(Entity->getType());
7016 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7017 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7018 << ParamType;
7020 return true;
7021 }
7022
7023 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7024 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7025
7027 }
7028 }
7029
7030 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7031 Arg, ArgType))
7032 return true;
7033
7034 // Create the template argument.
7035 SugaredConverted = TemplateArgument(Entity, ParamType);
7036 CanonicalConverted =
7038 S.Context.getCanonicalType(ParamType));
7039 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7040 return false;
7041}
7042
7043/// Checks whether the given template argument is a pointer to
7044/// member constant according to C++ [temp.arg.nontype]p1.
7046 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7047 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7048 bool Invalid = false;
7049
7050 Expr *Arg = ResultArg;
7051 bool ObjCLifetimeConversion;
7052
7053 // C++ [temp.arg.nontype]p1:
7054 //
7055 // A template-argument for a non-type, non-template
7056 // template-parameter shall be one of: [...]
7057 //
7058 // -- a pointer to member expressed as described in 5.3.1.
7059 DeclRefExpr *DRE = nullptr;
7060
7061 // In C++98/03 mode, give an extension warning on any extra parentheses.
7062 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7063 bool ExtraParens = false;
7064 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7065 if (!Invalid && !ExtraParens) {
7066 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7067 << Arg->getSourceRange();
7068 ExtraParens = true;
7069 }
7070
7071 Arg = Parens->getSubExpr();
7072 }
7073
7074 while (SubstNonTypeTemplateParmExpr *subst =
7075 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7076 Arg = subst->getReplacement()->IgnoreImpCasts();
7077
7078 // A pointer-to-member constant written &Class::member.
7079 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7080 if (UnOp->getOpcode() == UO_AddrOf) {
7081 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7082 if (DRE && !DRE->getQualifier())
7083 DRE = nullptr;
7084 }
7085 }
7086 // A constant of pointer-to-member type.
7087 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7088 ValueDecl *VD = DRE->getDecl();
7089 if (VD->getType()->isMemberPointerType()) {
7091 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7092 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7093 CanonicalConverted =
7094 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7095 } else {
7096 SugaredConverted = TemplateArgument(VD, ParamType);
7097 CanonicalConverted =
7099 S.Context.getCanonicalType(ParamType));
7100 }
7101 return Invalid;
7102 }
7103 }
7104
7105 DRE = nullptr;
7106 }
7107
7108 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7109
7110 // Check for a null pointer value.
7111 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7112 Entity)) {
7113 case NPV_Error:
7114 return true;
7115 case NPV_NullPointer:
7116 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7117 SugaredConverted = TemplateArgument(ParamType,
7118 /*isNullPtr*/ true);
7119 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7120 /*isNullPtr*/ true);
7121 return false;
7122 case NPV_NotNullPointer:
7123 break;
7124 }
7125
7126 if (S.IsQualificationConversion(ResultArg->getType(),
7127 ParamType.getNonReferenceType(), false,
7128 ObjCLifetimeConversion)) {
7129 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7130 ResultArg->getValueKind())
7131 .get();
7132 } else if (!S.Context.hasSameUnqualifiedType(
7133 ResultArg->getType(), ParamType.getNonReferenceType())) {
7134 // We can't perform this conversion.
7135 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7136 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7138 return true;
7139 }
7140
7141 if (!DRE)
7142 return S.Diag(Arg->getBeginLoc(),
7143 diag::err_template_arg_not_pointer_to_member_form)
7144 << Arg->getSourceRange();
7145
7146 if (isa<FieldDecl>(DRE->getDecl()) ||
7148 isa<CXXMethodDecl>(DRE->getDecl())) {
7149 assert((isa<FieldDecl>(DRE->getDecl()) ||
7152 ->isImplicitObjectMemberFunction()) &&
7153 "Only non-static member pointers can make it here");
7154
7155 // Okay: this is the address of a non-static member, and therefore
7156 // a member pointer constant.
7157 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7158 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7159 CanonicalConverted =
7160 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7161 } else {
7162 ValueDecl *D = DRE->getDecl();
7163 SugaredConverted = TemplateArgument(D, ParamType);
7164 CanonicalConverted =
7166 S.Context.getCanonicalType(ParamType));
7167 }
7168 return Invalid;
7169 }
7170
7171 // We found something else, but we don't know specifically what it is.
7172 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7173 << Arg->getSourceRange();
7174 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7175 return true;
7176}
7177
7178/// Check a template argument against its corresponding
7179/// non-type template parameter.
7180///
7181/// This routine implements the semantics of C++ [temp.arg.nontype].
7182/// If an error occurred, it returns ExprError(); otherwise, it
7183/// returns the converted template argument. \p ParamType is the
7184/// type of the non-type template parameter after it has been instantiated.
7186 Expr *Arg,
7187 TemplateArgument &SugaredConverted,
7188 TemplateArgument &CanonicalConverted,
7189 bool StrictCheck,
7191 SourceLocation StartLoc = Arg->getBeginLoc();
7192 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7193 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7194 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7195 DeductionArg = NewDeductionArg;
7196 if (ArgPE) {
7197 // Recreate a pack expansion if we unwrapped one.
7198 Arg = new (Context) PackExpansionExpr(
7199 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7200 } else {
7201 Arg = DeductionArg;
7202 }
7203 };
7204
7205 // If the parameter type somehow involves auto, deduce the type now.
7206 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7207 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7208 if (IsDeduced) {
7209 // When checking a deduced template argument, deduce from its type even if
7210 // the type is dependent, in order to check the types of non-type template
7211 // arguments line up properly in partial ordering.
7212 TypeSourceInfo *TSI =
7213 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7215 InitializedEntity Entity =
7218 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7219 Expr *Inits[1] = {DeductionArg};
7220 ParamType =
7222 if (ParamType.isNull())
7223 return ExprError();
7224 } else {
7225 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7226 Param->getTemplateDepth() + 1);
7227 ParamType = QualType();
7229 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7230 /*DependentDeduction=*/true,
7231 // We do not check constraints right now because the
7232 // immediately-declared constraint of the auto type is
7233 // also an associated constraint, and will be checked
7234 // along with the other associated constraints after
7235 // checking the template argument list.
7236 /*IgnoreConstraints=*/true);
7238 ParamType = TSI->getType();
7239 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7241 return ExprError();
7242 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7243 Diag(Arg->getExprLoc(),
7244 diag::err_non_type_template_parm_type_deduction_failure)
7245 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7246 << Arg->getSourceRange();
7248 return ExprError();
7249 }
7250 ParamType = SubstAutoTypeDependent(ParamType);
7251 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7252 }
7253 }
7254 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7255 // an error. The error message normally references the parameter
7256 // declaration, but here we'll pass the argument location because that's
7257 // where the parameter type is deduced.
7258 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7259 if (ParamType.isNull()) {
7261 return ExprError();
7262 }
7263 }
7264
7265 // We should have already dropped all cv-qualifiers by now.
7266 assert(!ParamType.hasQualifiers() &&
7267 "non-type template parameter type cannot be qualified");
7268
7269 // If either the parameter has a dependent type or the argument is
7270 // type-dependent, there's nothing we can check now.
7271 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7272 // Force the argument to the type of the parameter to maintain invariants.
7273 if (!IsDeduced) {
7275 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7276 ParamType->isLValueReferenceType() ? VK_LValue
7277 : ParamType->isRValueReferenceType() ? VK_XValue
7278 : VK_PRValue);
7279 if (E.isInvalid())
7280 return ExprError();
7281 setDeductionArg(E.get());
7282 }
7283 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7284 CanonicalConverted = TemplateArgument(
7285 Context.getCanonicalTemplateArgument(SugaredConverted));
7286 return Arg;
7287 }
7288
7289 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7290 if (CTAK == CTAK_Deduced && !StrictCheck &&
7291 (ParamType->isReferenceType()
7292 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7293 DeductionArg->getType())
7294 : !Context.hasSameUnqualifiedType(ParamType,
7295 DeductionArg->getType()))) {
7296 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7297 // we should actually be checking the type of the template argument in P,
7298 // not the type of the template argument deduced from A, against the
7299 // template parameter type.
7300 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7301 << Arg->getType() << ParamType.getUnqualifiedType();
7303 return ExprError();
7304 }
7305
7306 // If the argument is a pack expansion, we don't know how many times it would
7307 // expand. If we continue checking the argument, this will make the template
7308 // definition ill-formed if it would be ill-formed for any number of
7309 // expansions during instantiation time. When partial ordering or matching
7310 // template template parameters, this is exactly what we want. Otherwise, the
7311 // normal template rules apply: we accept the template if it would be valid
7312 // for any number of expansions (i.e. none).
7313 if (ArgPE && !StrictCheck) {
7314 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7315 CanonicalConverted = TemplateArgument(
7316 Context.getCanonicalTemplateArgument(SugaredConverted));
7317 return Arg;
7318 }
7319
7320 // Avoid making a copy when initializing a template parameter of class type
7321 // from a template parameter object of the same type. This is going beyond
7322 // the standard, but is required for soundness: in
7323 // template<A a> struct X { X *p; X<a> *q; };
7324 // ... we need p and q to have the same type.
7325 //
7326 // Similarly, don't inject a call to a copy constructor when initializing
7327 // from a template parameter of the same type.
7328 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7329 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7330 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7331 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7332 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7333
7334 SugaredConverted = TemplateArgument(TPO, ParamType);
7335 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7336 ParamType.getCanonicalType());
7337 return Arg;
7338 }
7340 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7341 CanonicalConverted =
7342 Context.getCanonicalTemplateArgument(SugaredConverted);
7343 return Arg;
7344 }
7345 }
7346
7347 // The initialization of the parameter from the argument is
7348 // a constant-evaluated context.
7351
7352 bool IsConvertedConstantExpression = true;
7353 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7355 StartLoc, /*DirectInit=*/false, DeductionArg);
7356 Expr *Inits[1] = {DeductionArg};
7357 InitializedEntity Entity =
7359 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7360 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7361 if (Result.isInvalid() || !Result.get())
7362 return ExprError();
7364 if (Result.isInvalid() || !Result.get())
7365 return ExprError();
7366 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7367 /*DiscardedValue=*/false,
7368 /*IsConstexpr=*/true,
7369 /*IsTemplateArgument=*/true)
7370 .get());
7371 IsConvertedConstantExpression = false;
7372 }
7373
7374 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7375 // C++17 [temp.arg.nontype]p1:
7376 // A template-argument for a non-type template parameter shall be
7377 // a converted constant expression of the type of the template-parameter.
7378 APValue Value;
7379 ExprResult ArgResult;
7380 if (IsConvertedConstantExpression) {
7382 DeductionArg, ParamType,
7383 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7384 assert(!ArgResult.isUnset());
7385 if (ArgResult.isInvalid()) {
7387 return ExprError();
7388 }
7389 } else {
7390 ArgResult = DeductionArg;
7391 }
7392
7393 // For a value-dependent argument, CheckConvertedConstantExpression is
7394 // permitted (and expected) to be unable to determine a value.
7395 if (ArgResult.get()->isValueDependent()) {
7396 setDeductionArg(ArgResult.get());
7397 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7398 CanonicalConverted =
7399 Context.getCanonicalTemplateArgument(SugaredConverted);
7400 return Arg;
7401 }
7402
7403 APValue PreNarrowingValue;
7405 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7406 false, PreNarrowingValue);
7407 if (ArgResult.isInvalid())
7408 return ExprError();
7409 setDeductionArg(ArgResult.get());
7410
7411 if (Value.isLValue()) {
7412 APValue::LValueBase Base = Value.getLValueBase();
7413 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7414 // For a non-type template-parameter of pointer or reference type,
7415 // the value of the constant expression shall not refer to
7416 assert(ParamType->isPointerOrReferenceType() ||
7417 ParamType->isNullPtrType());
7418 // -- a temporary object
7419 // -- a string literal
7420 // -- the result of a typeid expression, or
7421 // -- a predefined __func__ variable
7422 if (Base &&
7423 (!VD ||
7425 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7426 << Arg->getSourceRange();
7427 return ExprError();
7428 }
7429
7430 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7431 VD->getType()->isArrayType() &&
7432 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7433 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7434 if (ArgPE) {
7435 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7436 CanonicalConverted =
7437 Context.getCanonicalTemplateArgument(SugaredConverted);
7438 } else {
7439 SugaredConverted = TemplateArgument(VD, ParamType);
7440 CanonicalConverted =
7441 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7442 ParamType.getCanonicalType());
7443 }
7444 return Arg;
7445 }
7446
7447 // -- a subobject [until C++20]
7448 if (!getLangOpts().CPlusPlus20) {
7449 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7450 Value.isLValueOnePastTheEnd()) {
7451 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7452 << Value.getAsString(Context, ParamType);
7453 return ExprError();
7454 }
7455 assert((VD || !ParamType->isReferenceType()) &&
7456 "null reference should not be a constant expression");
7457 assert((!VD || !ParamType->isNullPtrType()) &&
7458 "non-null value of type nullptr_t?");
7459 }
7460 }
7461
7462 if (Value.isAddrLabelDiff())
7463 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7464
7465 if (ArgPE) {
7466 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7467 CanonicalConverted =
7468 Context.getCanonicalTemplateArgument(SugaredConverted);
7469 } else {
7470 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7471 CanonicalConverted =
7473 }
7474 return Arg;
7475 }
7476
7477 // These should have all been handled above using the C++17 rules.
7478 assert(!ArgPE && !StrictCheck);
7479
7480 // C++ [temp.arg.nontype]p5:
7481 // The following conversions are performed on each expression used
7482 // as a non-type template-argument. If a non-type
7483 // template-argument cannot be converted to the type of the
7484 // corresponding template-parameter then the program is
7485 // ill-formed.
7486 if (ParamType->isIntegralOrEnumerationType()) {
7487 // C++11:
7488 // -- for a non-type template-parameter of integral or
7489 // enumeration type, conversions permitted in a converted
7490 // constant expression are applied.
7491 //
7492 // C++98:
7493 // -- for a non-type template-parameter of integral or
7494 // enumeration type, integral promotions (4.5) and integral
7495 // conversions (4.7) are applied.
7496
7497 if (getLangOpts().CPlusPlus11) {
7498 // C++ [temp.arg.nontype]p1:
7499 // A template-argument for a non-type, non-template template-parameter
7500 // shall be one of:
7501 //
7502 // -- for a non-type template-parameter of integral or enumeration
7503 // type, a converted constant expression of the type of the
7504 // template-parameter; or
7505 llvm::APSInt Value;
7507 Arg, ParamType, Value, CCEKind::TemplateArg);
7508 if (ArgResult.isInvalid())
7509 return ExprError();
7510 Arg = ArgResult.get();
7511
7512 // We can't check arbitrary value-dependent arguments.
7513 if (Arg->isValueDependent()) {
7514 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7515 CanonicalConverted =
7516 Context.getCanonicalTemplateArgument(SugaredConverted);
7517 return Arg;
7518 }
7519
7520 // Widen the argument value to sizeof(parameter type). This is almost
7521 // always a no-op, except when the parameter type is bool. In
7522 // that case, this may extend the argument from 1 bit to 8 bits.
7523 QualType IntegerType = ParamType;
7524 if (const auto *ED = IntegerType->getAsEnumDecl())
7525 IntegerType = ED->getIntegerType();
7526 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7527 ? Context.getIntWidth(IntegerType)
7528 : Context.getTypeSize(IntegerType));
7529
7530 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7531 CanonicalConverted =
7532 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7533 return Arg;
7534 }
7535
7536 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7537 if (ArgResult.isInvalid())
7538 return ExprError();
7539 Arg = ArgResult.get();
7540
7541 QualType ArgType = Arg->getType();
7542
7543 // C++ [temp.arg.nontype]p1:
7544 // A template-argument for a non-type, non-template
7545 // template-parameter shall be one of:
7546 //
7547 // -- an integral constant-expression of integral or enumeration
7548 // type; or
7549 // -- the name of a non-type template-parameter; or
7550 llvm::APSInt Value;
7551 if (!ArgType->isIntegralOrEnumerationType()) {
7552 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7553 << ArgType << Arg->getSourceRange();
7555 return ExprError();
7556 }
7557 if (!Arg->isValueDependent()) {
7558 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7559 QualType T;
7560
7561 public:
7562 TmplArgICEDiagnoser(QualType T) : T(T) { }
7563
7564 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7565 SourceLocation Loc) override {
7566 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7567 }
7568 } Diagnoser(ArgType);
7569
7570 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7571 if (!Arg)
7572 return ExprError();
7573 }
7574
7575 // From here on out, all we care about is the unqualified form
7576 // of the argument type.
7577 ArgType = ArgType.getUnqualifiedType();
7578
7579 // Try to convert the argument to the parameter's type.
7580 if (Context.hasSameType(ParamType, ArgType)) {
7581 // Okay: no conversion necessary
7582 } else if (ParamType->isBooleanType()) {
7583 // This is an integral-to-boolean conversion.
7584 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7585 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7586 !ParamType->isEnumeralType()) {
7587 // This is an integral promotion or conversion.
7588 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7589 } else {
7590 // We can't perform this conversion.
7591 Diag(StartLoc, diag::err_template_arg_not_convertible)
7592 << Arg->getType() << ParamType << Arg->getSourceRange();
7594 return ExprError();
7595 }
7596
7597 // Add the value of this argument to the list of converted
7598 // arguments. We use the bitwidth and signedness of the template
7599 // parameter.
7600 if (Arg->isValueDependent()) {
7601 // The argument is value-dependent. Create a new
7602 // TemplateArgument with the converted expression.
7603 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7604 CanonicalConverted =
7605 Context.getCanonicalTemplateArgument(SugaredConverted);
7606 return Arg;
7607 }
7608
7609 QualType IntegerType = ParamType;
7610 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7611 IntegerType = ED->getIntegerType();
7612 }
7613
7614 if (ParamType->isBooleanType()) {
7615 // Value must be zero or one.
7616 Value = Value != 0;
7617 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7618 if (Value.getBitWidth() != AllowedBits)
7619 Value = Value.extOrTrunc(AllowedBits);
7620 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7621 } else {
7622 llvm::APSInt OldValue = Value;
7623
7624 // Coerce the template argument's value to the value it will have
7625 // based on the template parameter's type.
7626 unsigned AllowedBits = IntegerType->isBitIntType()
7627 ? Context.getIntWidth(IntegerType)
7628 : Context.getTypeSize(IntegerType);
7629 if (Value.getBitWidth() != AllowedBits)
7630 Value = Value.extOrTrunc(AllowedBits);
7631 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7632
7633 // Complain if an unsigned parameter received a negative value.
7634 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7635 (OldValue.isSigned() && OldValue.isNegative())) {
7636 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7637 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7638 << Arg->getSourceRange();
7640 }
7641
7642 // Complain if we overflowed the template parameter's type.
7643 unsigned RequiredBits;
7644 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7645 RequiredBits = OldValue.getActiveBits();
7646 else if (OldValue.isUnsigned())
7647 RequiredBits = OldValue.getActiveBits() + 1;
7648 else
7649 RequiredBits = OldValue.getSignificantBits();
7650 if (RequiredBits > AllowedBits) {
7651 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7652 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7653 << Arg->getSourceRange();
7655 }
7656 }
7657
7658 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7659 SugaredConverted = TemplateArgument(Context, Value, T);
7660 CanonicalConverted =
7661 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7662 return Arg;
7663 }
7664
7665 QualType ArgType = Arg->getType();
7666 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7667 bool IsSpecified = CTAK == CTAK_Specified;
7668
7669 // Handle pointer-to-function, reference-to-function, and
7670 // pointer-to-member-function all in (roughly) the same way.
7671 if (// -- For a non-type template-parameter of type pointer to
7672 // function, only the function-to-pointer conversion (4.3) is
7673 // applied. If the template-argument represents a set of
7674 // overloaded functions (or a pointer to such), the matching
7675 // function is selected from the set (13.4).
7676 (ParamType->isPointerType() &&
7677 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7678 // -- For a non-type template-parameter of type reference to
7679 // function, no conversions apply. If the template-argument
7680 // represents a set of overloaded functions, the matching
7681 // function is selected from the set (13.4).
7682 (ParamType->isReferenceType() &&
7683 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7684 // -- For a non-type template-parameter of type pointer to
7685 // member function, no conversions apply. If the
7686 // template-argument represents a set of overloaded member
7687 // functions, the matching member function is selected from
7688 // the set (13.4).
7689 (ParamType->isMemberPointerType() &&
7690 ParamType->castAs<MemberPointerType>()->getPointeeType()
7691 ->isFunctionType())) {
7692
7693 if (Arg->getType() == Context.OverloadTy) {
7694 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7695 true,
7696 FoundResult)) {
7697 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7698 return ExprError();
7699
7700 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7701 if (Res.isInvalid())
7702 return ExprError();
7703 Arg = Res.get();
7704 ArgType = Arg->getType();
7705 } else
7706 return ExprError();
7707 }
7708
7709 if (!ParamType->isMemberPointerType()) {
7711 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7712 CanonicalConverted))
7713 return ExprError();
7714 return Arg;
7715 }
7716
7718 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7719 return ExprError();
7720 return Arg;
7721 }
7722
7723 if (ParamType->isPointerType()) {
7724 // -- for a non-type template-parameter of type pointer to
7725 // object, qualification conversions (4.4) and the
7726 // array-to-pointer conversion (4.2) are applied.
7727 // C++0x also allows a value of std::nullptr_t.
7728 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7729 "Only object pointers allowed here");
7730
7732 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7733 CanonicalConverted))
7734 return ExprError();
7735 return Arg;
7736 }
7737
7738 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7739 // -- For a non-type template-parameter of type reference to
7740 // object, no conversions apply. The type referred to by the
7741 // reference may be more cv-qualified than the (otherwise
7742 // identical) type of the template-argument. The
7743 // template-parameter is bound directly to the
7744 // template-argument, which must be an lvalue.
7745 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7746 "Only object references allowed here");
7747
7748 if (Arg->getType() == Context.OverloadTy) {
7750 ParamRefType->getPointeeType(),
7751 true,
7752 FoundResult)) {
7753 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7754 return ExprError();
7755 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7756 if (Res.isInvalid())
7757 return ExprError();
7758 Arg = Res.get();
7759 ArgType = Arg->getType();
7760 } else
7761 return ExprError();
7762 }
7763
7765 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7766 CanonicalConverted))
7767 return ExprError();
7768 return Arg;
7769 }
7770
7771 // Deal with parameters of type std::nullptr_t.
7772 if (ParamType->isNullPtrType()) {
7773 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7774 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7775 CanonicalConverted =
7776 Context.getCanonicalTemplateArgument(SugaredConverted);
7777 return Arg;
7778 }
7779
7780 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7781 case NPV_NotNullPointer:
7782 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7783 << Arg->getType() << ParamType;
7785 return ExprError();
7786
7787 case NPV_Error:
7788 return ExprError();
7789
7790 case NPV_NullPointer:
7791 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7792 SugaredConverted = TemplateArgument(ParamType,
7793 /*isNullPtr=*/true);
7794 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7795 /*isNullPtr=*/true);
7796 return Arg;
7797 }
7798 }
7799
7800 // -- For a non-type template-parameter of type pointer to data
7801 // member, qualification conversions (4.4) are applied.
7802 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7803
7805 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7806 return ExprError();
7807 return Arg;
7808}
7809
7813
7816 const TemplateArgumentLoc &Arg) {
7817 // C++0x [temp.arg.template]p1:
7818 // A template-argument for a template template-parameter shall be
7819 // the name of a class template or an alias template, expressed as an
7820 // id-expression. When the template-argument names a class template, only
7821 // primary class templates are considered when matching the
7822 // template template argument with the corresponding parameter;
7823 // partial specializations are not considered even if their
7824 // parameter lists match that of the template template parameter.
7825 //
7826
7828 unsigned DiagFoundKind = 0;
7829
7830 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7831 switch (TTP->templateParameterKind()) {
7833 DiagFoundKind = 3;
7834 break;
7836 DiagFoundKind = 2;
7837 break;
7838 default:
7839 DiagFoundKind = 1;
7840 break;
7841 }
7842 Kind = TTP->templateParameterKind();
7843 } else if (isa<ConceptDecl>(Template)) {
7845 DiagFoundKind = 3;
7846 } else if (isa<FunctionTemplateDecl>(Template)) {
7848 DiagFoundKind = 0;
7849 } else if (isa<VarTemplateDecl>(Template)) {
7851 DiagFoundKind = 2;
7852 } else if (isa<ClassTemplateDecl>(Template) ||
7856 DiagFoundKind = 1;
7857 } else {
7858 assert(false && "Unexpected Decl");
7859 }
7860
7861 if (Kind == Param->templateParameterKind()) {
7862 return true;
7863 }
7864
7865 unsigned DiagKind = 0;
7866 switch (Param->templateParameterKind()) {
7868 DiagKind = 2;
7869 break;
7871 DiagKind = 1;
7872 break;
7873 default:
7874 DiagKind = 0;
7875 break;
7876 }
7877 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7878 << DiagKind;
7879 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7880 << DiagFoundKind << Template;
7881 return false;
7882}
7883
7884/// Check a template argument against its corresponding
7885/// template template parameter.
7886///
7887/// This routine implements the semantics of C++ [temp.arg.template].
7888/// It returns true if an error occurred, and false otherwise.
7890 TemplateParameterList *Params,
7892 bool PartialOrdering,
7893 bool *StrictPackMatch) {
7895 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7896 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7897 if (!Template) {
7898 // FIXME: Handle AssumedTemplateNames
7899 // Any dependent template name is fine.
7900 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7901 return false;
7902 }
7903
7904 if (Template->isInvalidDecl())
7905 return true;
7906
7908 return true;
7909 }
7910
7911 // C++1z [temp.arg.template]p3: (DR 150)
7912 // A template-argument matches a template template-parameter P when P
7913 // is at least as specialized as the template-argument A.
7915 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7916 PartialOrdering, StrictPackMatch))
7917 return true;
7918 // P2113
7919 // C++20[temp.func.order]p2
7920 // [...] If both deductions succeed, the partial ordering selects the
7921 // more constrained template (if one exists) as determined below.
7922 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7923 Params->getAssociatedConstraints(ParamsAC);
7924 // C++20[temp.arg.template]p3
7925 // [...] In this comparison, if P is unconstrained, the constraints on A
7926 // are not considered.
7927 if (ParamsAC.empty())
7928 return false;
7929
7930 Template->getAssociatedConstraints(TemplateAC);
7931
7932 bool IsParamAtLeastAsConstrained;
7933 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7934 IsParamAtLeastAsConstrained))
7935 return true;
7936 if (!IsParamAtLeastAsConstrained) {
7937 Diag(Arg.getLocation(),
7938 diag::err_template_template_parameter_not_at_least_as_constrained)
7939 << Template << Param << Arg.getSourceRange();
7940 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7941 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7943 TemplateAC);
7944 return true;
7945 }
7946 return false;
7947}
7948
7950 unsigned HereDiagID,
7951 unsigned ExternalDiagID) {
7952 if (Decl.getLocation().isValid())
7953 return S.Diag(Decl.getLocation(), HereDiagID);
7954
7955 SmallString<128> Str;
7956 llvm::raw_svector_ostream Out(Str);
7958 PP.TerseOutput = 1;
7959 Decl.print(Out, PP);
7960 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7961}
7962
7964 std::optional<SourceRange> ParamRange) {
7966 noteLocation(*this, Decl, diag::note_template_decl_here,
7967 diag::note_template_decl_external);
7968 if (ParamRange && ParamRange->isValid()) {
7969 assert(Decl.getLocation().isValid() &&
7970 "Parameter range has location when Decl does not");
7971 DB << *ParamRange;
7972 }
7973}
7974
7976 noteLocation(*this, Decl, diag::note_template_param_here,
7977 diag::note_template_param_external);
7978}
7979
7980/// Given a non-type template argument that refers to a
7981/// declaration and the type of its corresponding non-type template
7982/// parameter, produce an expression that properly refers to that
7983/// declaration.
7985 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7986 // C++ [temp.param]p8:
7987 //
7988 // A non-type template-parameter of type "array of T" or
7989 // "function returning T" is adjusted to be of type "pointer to
7990 // T" or "pointer to function returning T", respectively.
7991 if (ParamType->isArrayType())
7992 ParamType = Context.getArrayDecayedType(ParamType);
7993 else if (ParamType->isFunctionType())
7994 ParamType = Context.getPointerType(ParamType);
7995
7996 // For a NULL non-type template argument, return nullptr casted to the
7997 // parameter's type.
7998 if (Arg.getKind() == TemplateArgument::NullPtr) {
7999 return ImpCastExprToType(
8000 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8001 ParamType,
8002 ParamType->getAs<MemberPointerType>()
8003 ? CK_NullToMemberPointer
8004 : CK_NullToPointer);
8005 }
8006 assert(Arg.getKind() == TemplateArgument::Declaration &&
8007 "Only declaration template arguments permitted here");
8008
8009 ValueDecl *VD = Arg.getAsDecl();
8010
8011 CXXScopeSpec SS;
8012 if (ParamType->isMemberPointerType()) {
8013 // If this is a pointer to member, we need to use a qualified name to
8014 // form a suitable pointer-to-member constant.
8015 assert(VD->getDeclContext()->isRecord() &&
8016 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8018 CanQualType ClassType =
8019 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
8020 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
8021 SS.MakeTrivial(Context, Qualifier, Loc);
8022 }
8023
8025 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8026 if (RefExpr.isInvalid())
8027 return ExprError();
8028
8029 // For a pointer, the argument declaration is the pointee. Take its address.
8030 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8031 if (ParamType->isPointerType() && !ElemT.isNull() &&
8032 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8033 // Decay an array argument if we want a pointer to its first element.
8034 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8035 if (RefExpr.isInvalid())
8036 return ExprError();
8037 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8038 // For any other pointer, take the address (or form a pointer-to-member).
8039 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8040 if (RefExpr.isInvalid())
8041 return ExprError();
8042 } else if (ParamType->isRecordType()) {
8043 assert(isa<TemplateParamObjectDecl>(VD) &&
8044 "arg for class template param not a template parameter object");
8045 // No conversions apply in this case.
8046 return RefExpr;
8047 } else {
8048 assert(ParamType->isReferenceType() &&
8049 "unexpected type for decl template argument");
8050 // If the parameter has reference type, wrap it in paretheses so that this
8051 // expression will have the correct type under `decltype`.
8052 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8053 }
8054
8055 // At this point we should have the right value category.
8056 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8057 "value kind mismatch for non-type template argument");
8058
8059 // The type of the template parameter can differ from the type of the
8060 // argument in various ways; convert it now if necessary.
8061 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8062 QualType SrcExprType = RefExpr.get()->getType();
8063 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8064 CastKind CK;
8065 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8066 IsFunctionConversion(SrcExprType, DestExprType)) {
8067 CK = CK_NoOp;
8068 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8069 CK = CK_BitCast;
8070 } else {
8071 // FIXME: Pointers to members can need conversion derived-to-base or
8072 // base-to-derived conversions. We currently don't retain enough
8073 // information to convert properly (we need to track a cast path or
8074 // subobject number in the template argument).
8075 llvm_unreachable(
8076 "unexpected conversion required for non-type template argument");
8077 }
8078 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8079 RefExpr.get()->getValueKind());
8080 }
8081
8082 return RefExpr;
8083}
8084
8085/// Construct a new expression that refers to the given
8086/// integral template argument with the given source-location
8087/// information.
8088///
8089/// This routine takes care of the mapping from an integral template
8090/// argument (which may have any integral type) to the appropriate
8091/// literal value.
8093 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8094 assert(OrigT->isIntegralOrEnumerationType());
8095
8096 // If this is an enum type that we're instantiating, we need to use an integer
8097 // type the same size as the enumerator. We don't want to build an
8098 // IntegerLiteral with enum type. The integer type of an enum type can be of
8099 // any integral type with C++11 enum classes, make sure we create the right
8100 // type of literal for it.
8101 QualType T = OrigT;
8102 if (const auto *ED = OrigT->getAsEnumDecl())
8103 T = ED->getIntegerType();
8104
8105 Expr *E;
8106 if (T->isAnyCharacterType()) {
8108 if (T->isWideCharType())
8110 else if (T->isChar8Type() && S.getLangOpts().Char8)
8112 else if (T->isChar16Type())
8114 else if (T->isChar32Type())
8116 else
8118
8119 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8120 } else if (T->isBooleanType()) {
8121 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8122 } else {
8123 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8124 }
8125
8126 if (OrigT->isEnumeralType()) {
8127 // FIXME: This is a hack. We need a better way to handle substituted
8128 // non-type template parameters.
8129 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8130 nullptr, S.CurFPFeatureOverrides(),
8131 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8132 Loc, Loc);
8133 }
8134
8135 return E;
8136}
8137
8138/// Construct a new reflect expression that refers to the given
8139/// entity with the given source-location of the reflection operator.
8141 SourceLocation CaretCaretLoc) {
8142 // TODO(Reflection): Add support for NamespaceReference, TemplateReference,
8143 // and DeclRefExpr.
8145 S.Context, CaretCaretLoc,
8146 static_cast<TypeSourceInfo *>(
8147 const_cast<void *>(RV.getReflectionOpaqueOperand())));
8148}
8149
8151 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8152 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8153 auto *ILE = new (S.Context)
8154 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8155 ILE->setType(T);
8156 return ILE;
8157 };
8158
8159 switch (Val.getKind()) {
8161 // This cannot occur in a template argument at all.
8162 case APValue::Array:
8163 case APValue::Struct:
8164 case APValue::Union:
8165 // These can only occur within a template parameter object, which is
8166 // represented as a TemplateArgument::Declaration.
8167 llvm_unreachable("unexpected template argument value");
8168
8169 case APValue::Int:
8171 Loc);
8172
8173 case APValue::Float:
8174 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8175 T, Loc);
8176
8179 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8180 Val.getFixedPoint().getScale());
8181
8182 case APValue::ComplexInt: {
8183 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8185 S, ElemT, Val.getComplexIntReal(), Loc),
8187 S, ElemT, Val.getComplexIntImag(), Loc)});
8188 }
8189
8190 case APValue::ComplexFloat: {
8191 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8192 return MakeInitList(
8194 ElemT, Loc),
8196 ElemT, Loc)});
8197 }
8198
8199 case APValue::Vector: {
8200 QualType ElemT = T->castAs<VectorType>()->getElementType();
8202 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8204 S, ElemT, Val.getVectorElt(I), Loc));
8205 return MakeInitList(Elts);
8206 }
8207
8208 case APValue::Matrix:
8209 llvm_unreachable("Matrix template argument expression not yet supported");
8210
8211 case APValue::None:
8213 llvm_unreachable("Unexpected APValue kind.");
8214 case APValue::LValue:
8216 // There isn't necessarily a valid equivalent source-level syntax for
8217 // these; in particular, a naive lowering might violate access control.
8218 // So for now we lower to a ConstantExpr holding the value, wrapped around
8219 // an OpaqueValueExpr.
8220 // FIXME: We should have a better representation for this.
8222 if (T->isReferenceType()) {
8223 T = T->getPointeeType();
8224 VK = VK_LValue;
8225 }
8226 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8227 return ConstantExpr::Create(S.Context, OVE, Val);
8228 }
8230 return BuildExpressionFromReflection(S, Val, Loc).get();
8231 }
8232 llvm_unreachable("Unhandled APValue::ValueKind enum");
8233}
8234
8237 SourceLocation Loc) {
8238 switch (Arg.getKind()) {
8244 llvm_unreachable("not a non-type template argument");
8245
8247 return Arg.getAsExpr();
8248
8252 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8253
8256 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8257
8260 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8261 }
8262 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8263}
8264
8265/// Match two template parameters within template parameter lists.
8267 Sema &S, NamedDecl *New,
8268 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8269 const NamedDecl *OldInstFrom, bool Complain,
8271 // Check the actual kind (type, non-type, template).
8272 if (Old->getKind() != New->getKind()) {
8273 if (Complain) {
8274 unsigned NextDiag = diag::err_template_param_different_kind;
8275 if (TemplateArgLoc.isValid()) {
8276 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8277 NextDiag = diag::note_template_param_different_kind;
8278 }
8279 S.Diag(New->getLocation(), NextDiag)
8280 << (Kind != Sema::TPL_TemplateMatch);
8281 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8282 << (Kind != Sema::TPL_TemplateMatch);
8283 }
8284
8285 return false;
8286 }
8287
8288 // Check that both are parameter packs or neither are parameter packs.
8289 // However, if we are matching a template template argument to a
8290 // template template parameter, the template template parameter can have
8291 // a parameter pack where the template template argument does not.
8292 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8293 if (Complain) {
8294 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8295 if (TemplateArgLoc.isValid()) {
8296 S.Diag(TemplateArgLoc,
8297 diag::err_template_arg_template_params_mismatch);
8298 NextDiag = diag::note_template_parameter_pack_non_pack;
8299 }
8300
8301 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8303 : 2;
8304 S.Diag(New->getLocation(), NextDiag)
8305 << ParamKind << New->isParameterPack();
8306 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8307 << ParamKind << Old->isParameterPack();
8308 }
8309
8310 return false;
8311 }
8312 // For non-type template parameters, check the type of the parameter.
8313 if (NonTypeTemplateParmDecl *OldNTTP =
8314 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8316
8317 // If we are matching a template template argument to a template
8318 // template parameter and one of the non-type template parameter types
8319 // is dependent, then we must wait until template instantiation time
8320 // to actually compare the arguments.
8322 (!OldNTTP->getType()->isDependentType() &&
8323 !NewNTTP->getType()->isDependentType())) {
8324 // C++20 [temp.over.link]p6:
8325 // Two [non-type] template-parameters are equivalent [if] they have
8326 // equivalent types ignoring the use of type-constraints for
8327 // placeholder types
8328 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8329 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8330 if (!S.Context.hasSameType(OldType, NewType)) {
8331 if (Complain) {
8332 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8333 if (TemplateArgLoc.isValid()) {
8334 S.Diag(TemplateArgLoc,
8335 diag::err_template_arg_template_params_mismatch);
8336 NextDiag = diag::note_template_nontype_parm_different_type;
8337 }
8338 S.Diag(NewNTTP->getLocation(), NextDiag)
8339 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8340 S.Diag(OldNTTP->getLocation(),
8341 diag::note_template_nontype_parm_prev_declaration)
8342 << OldNTTP->getType();
8343 }
8344 return false;
8345 }
8346 }
8347 }
8348 // For template template parameters, check the template parameter types.
8349 // The template parameter lists of template template
8350 // parameters must agree.
8351 else if (TemplateTemplateParmDecl *OldTTP =
8352 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8354 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8355 return false;
8357 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8358 OldTTP->getTemplateParameters(), Complain,
8361 : Kind),
8362 TemplateArgLoc))
8363 return false;
8364 }
8365
8369 const Expr *NewC = nullptr, *OldC = nullptr;
8370
8372 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8373 NewC = TC->getImmediatelyDeclaredConstraint();
8374 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8375 OldC = TC->getImmediatelyDeclaredConstraint();
8376 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8377 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8378 ->getPlaceholderTypeConstraint())
8379 NewC = E;
8380 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8381 ->getPlaceholderTypeConstraint())
8382 OldC = E;
8383 } else
8384 llvm_unreachable("unexpected template parameter type");
8385
8386 auto Diagnose = [&] {
8387 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8388 diag::err_template_different_type_constraint);
8389 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8390 diag::note_template_prev_declaration) << /*declaration*/0;
8391 };
8392
8393 if (!NewC != !OldC) {
8394 if (Complain)
8395 Diagnose();
8396 return false;
8397 }
8398
8399 if (NewC) {
8400 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8401 NewC)) {
8402 if (Complain)
8403 Diagnose();
8404 return false;
8405 }
8406 }
8407 }
8408
8409 return true;
8410}
8411
8412/// Diagnose a known arity mismatch when comparing template argument
8413/// lists.
8414static
8419 SourceLocation TemplateArgLoc) {
8420 unsigned NextDiag = diag::err_template_param_list_different_arity;
8421 if (TemplateArgLoc.isValid()) {
8422 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8423 NextDiag = diag::note_template_param_list_different_arity;
8424 }
8425 S.Diag(New->getTemplateLoc(), NextDiag)
8426 << (New->size() > Old->size())
8427 << (Kind != Sema::TPL_TemplateMatch)
8428 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8429 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8430 << (Kind != Sema::TPL_TemplateMatch)
8431 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8432}
8433
8436 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8437 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8438 if (Old->size() != New->size()) {
8439 if (Complain)
8441 TemplateArgLoc);
8442
8443 return false;
8444 }
8445
8446 // C++0x [temp.arg.template]p3:
8447 // A template-argument matches a template template-parameter (call it P)
8448 // when each of the template parameters in the template-parameter-list of
8449 // the template-argument's corresponding class template or alias template
8450 // (call it A) matches the corresponding template parameter in the
8451 // template-parameter-list of P. [...]
8452 TemplateParameterList::iterator NewParm = New->begin();
8453 TemplateParameterList::iterator NewParmEnd = New->end();
8454 for (TemplateParameterList::iterator OldParm = Old->begin(),
8455 OldParmEnd = Old->end();
8456 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8457 if (NewParm == NewParmEnd) {
8458 if (Complain)
8460 TemplateArgLoc);
8461 return false;
8462 }
8463 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8464 OldInstFrom, Complain, Kind,
8465 TemplateArgLoc))
8466 return false;
8467 }
8468
8469 // Make sure we exhausted all of the arguments.
8470 if (NewParm != NewParmEnd) {
8471 if (Complain)
8473 TemplateArgLoc);
8474
8475 return false;
8476 }
8477
8478 if (Kind != TPL_TemplateParamsEquivalent) {
8479 const Expr *NewRC = New->getRequiresClause();
8480 const Expr *OldRC = Old->getRequiresClause();
8481
8482 auto Diagnose = [&] {
8483 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8484 diag::err_template_different_requires_clause);
8485 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8486 diag::note_template_prev_declaration) << /*declaration*/0;
8487 };
8488
8489 if (!NewRC != !OldRC) {
8490 if (Complain)
8491 Diagnose();
8492 return false;
8493 }
8494
8495 if (NewRC) {
8496 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8497 NewRC)) {
8498 if (Complain)
8499 Diagnose();
8500 return false;
8501 }
8502 }
8503 }
8504
8505 return true;
8506}
8507
8508bool
8510 if (!S)
8511 return false;
8512
8513 // Find the nearest enclosing declaration scope.
8514 S = S->getDeclParent();
8515
8516 // C++ [temp.pre]p6: [P2096]
8517 // A template, explicit specialization, or partial specialization shall not
8518 // have C linkage.
8519 DeclContext *Ctx = S->getEntity();
8520 if (Ctx && Ctx->isExternCContext()) {
8521 SourceRange Range =
8522 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8523 ? TemplateParams->getParam(0)->getSourceRange()
8524 : TemplateParams->getSourceRange();
8525 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8526 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8527 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8528 return true;
8529 }
8530 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8531
8532 // C++ [temp]p2:
8533 // A template-declaration can appear only as a namespace scope or
8534 // class scope declaration.
8535 // C++ [temp.expl.spec]p3:
8536 // An explicit specialization may be declared in any scope in which the
8537 // corresponding primary template may be defined.
8538 // C++ [temp.class.spec]p6: [P2096]
8539 // A partial specialization may be declared in any scope in which the
8540 // corresponding primary template may be defined.
8541 if (Ctx) {
8542 if (Ctx->isFileContext())
8543 return false;
8544 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8545 // C++ [temp.mem]p2:
8546 // A local class shall not have member templates.
8547
8548 // Trace the outer context chain, bypassing nested records and OpenMP
8549 // captured regions, to determine if the class in defined inside a
8550 // function or method.
8551 const DeclContext *OutCtx = RD->getDeclContext();
8552 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(OutCtx))
8553 OutCtx = OutCtx->getParent();
8554
8555 if (OutCtx && OutCtx->isFunctionOrMethod())
8556 return Diag(TemplateParams->getTemplateLoc(),
8557 diag::err_template_inside_local_class)
8558 << TemplateParams->getSourceRange();
8559
8560 return false;
8561 }
8562 }
8563
8564 return Diag(TemplateParams->getTemplateLoc(),
8565 diag::err_template_outside_namespace_or_class_scope)
8566 << TemplateParams->getSourceRange();
8567}
8568
8569/// Determine what kind of template specialization the given declaration
8570/// is.
8572 if (!D)
8573 return TSK_Undeclared;
8574
8575 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8576 return Record->getTemplateSpecializationKind();
8577 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8578 return Function->getTemplateSpecializationKind();
8579 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8580 return Var->getTemplateSpecializationKind();
8581
8582 return TSK_Undeclared;
8583}
8584
8585/// Check whether a specialization is well-formed in the current
8586/// context.
8587///
8588/// This routine determines whether a template specialization can be declared
8589/// in the current context (C++ [temp.expl.spec]p2).
8590///
8591/// \param S the semantic analysis object for which this check is being
8592/// performed.
8593///
8594/// \param Specialized the entity being specialized or instantiated, which
8595/// may be a kind of template (class template, function template, etc.) or
8596/// a member of a class template (member function, static data member,
8597/// member class).
8598///
8599/// \param PrevDecl the previous declaration of this entity, if any.
8600///
8601/// \param Loc the location of the explicit specialization or instantiation of
8602/// this entity.
8603///
8604/// \param IsPartialSpecialization whether this is a partial specialization of
8605/// a class template.
8606///
8607/// \returns true if there was an error that we cannot recover from, false
8608/// otherwise.
8610 NamedDecl *Specialized,
8611 NamedDecl *PrevDecl,
8612 SourceLocation Loc,
8614 // Keep these "kind" numbers in sync with the %select statements in the
8615 // various diagnostics emitted by this routine.
8616 int EntityKind = 0;
8617 if (isa<ClassTemplateDecl>(Specialized))
8618 EntityKind = IsPartialSpecialization? 1 : 0;
8619 else if (isa<VarTemplateDecl>(Specialized))
8620 EntityKind = IsPartialSpecialization ? 3 : 2;
8621 else if (isa<FunctionTemplateDecl>(Specialized))
8622 EntityKind = 4;
8623 else if (isa<CXXMethodDecl>(Specialized))
8624 EntityKind = 5;
8625 else if (isa<VarDecl>(Specialized))
8626 EntityKind = 6;
8627 else if (isa<RecordDecl>(Specialized))
8628 EntityKind = 7;
8629 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8630 EntityKind = 8;
8631 else {
8632 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8633 << S.getLangOpts().CPlusPlus11;
8634 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8635 return true;
8636 }
8637
8638 // C++ [temp.expl.spec]p2:
8639 // An explicit specialization may be declared in any scope in which
8640 // the corresponding primary template may be defined.
8642 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8643 << Specialized;
8644 return true;
8645 }
8646
8647 // C++ [temp.class.spec]p6:
8648 // A class template partial specialization may be declared in any
8649 // scope in which the primary template may be defined.
8650 DeclContext *SpecializedContext =
8651 Specialized->getDeclContext()->getRedeclContext();
8653
8654 // Make sure that this redeclaration (or definition) occurs in the same
8655 // scope or an enclosing namespace.
8656 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8657 : DC->Equals(SpecializedContext))) {
8658 if (isa<TranslationUnitDecl>(SpecializedContext))
8659 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8660 << EntityKind << Specialized;
8661 else {
8662 auto *ND = cast<NamedDecl>(SpecializedContext);
8663 int Diag = diag::err_template_spec_redecl_out_of_scope;
8664 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8665 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8666 S.Diag(Loc, Diag) << EntityKind << Specialized
8667 << ND << isa<CXXRecordDecl>(ND);
8668 }
8669
8670 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8671
8672 // Don't allow specializing in the wrong class during error recovery.
8673 // Otherwise, things can go horribly wrong.
8674 if (DC->isRecord())
8675 return true;
8676 }
8677
8678 return false;
8679}
8680
8682 if (!E->isTypeDependent())
8683 return SourceLocation();
8684 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8685 Checker.TraverseStmt(E);
8686 if (Checker.MatchLoc.isInvalid())
8687 return E->getSourceRange();
8688 return Checker.MatchLoc;
8689}
8690
8691static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8692 if (!TL.getType()->isDependentType())
8693 return SourceLocation();
8694 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8695 Checker.TraverseTypeLoc(TL);
8696 if (Checker.MatchLoc.isInvalid())
8697 return TL.getSourceRange();
8698 return Checker.MatchLoc;
8699}
8700
8701/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8702/// that checks non-type template partial specialization arguments.
8704 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8705 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8706 bool HasError = false;
8707 for (unsigned I = 0; I != NumArgs; ++I) {
8708 if (Args[I].getKind() == TemplateArgument::Pack) {
8710 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8711 Args[I].pack_size(), IsDefaultArgument))
8712 return true;
8713
8714 continue;
8715 }
8716
8717 if (Args[I].getKind() != TemplateArgument::Expression)
8718 continue;
8719
8720 Expr *ArgExpr = Args[I].getAsExpr();
8721 if (ArgExpr->containsErrors()) {
8722 HasError = true;
8723 continue;
8724 }
8725
8726 // We can have a pack expansion of any of the bullets below.
8727 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8728 ArgExpr = Expansion->getPattern();
8729
8730 // Strip off any implicit casts we added as part of type checking.
8731 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8732 ArgExpr = ICE->getSubExpr();
8733
8734 // C++ [temp.class.spec]p8:
8735 // A non-type argument is non-specialized if it is the name of a
8736 // non-type parameter. All other non-type arguments are
8737 // specialized.
8738 //
8739 // Below, we check the two conditions that only apply to
8740 // specialized non-type arguments, so skip any non-specialized
8741 // arguments.
8742 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8743 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8744 continue;
8745
8746 if (isa<DependentTemplateIdExpr>(ArgExpr))
8747 continue;
8748
8749 // C++ [temp.class.spec]p9:
8750 // Within the argument list of a class template partial
8751 // specialization, the following restrictions apply:
8752 // -- A partially specialized non-type argument expression
8753 // shall not involve a template parameter of the partial
8754 // specialization except when the argument expression is a
8755 // simple identifier.
8756 // -- The type of a template parameter corresponding to a
8757 // specialized non-type argument shall not be dependent on a
8758 // parameter of the specialization.
8759 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8760 // We implement a compromise between the original rules and DR1315:
8761 // -- A specialized non-type template argument shall not be
8762 // type-dependent and the corresponding template parameter
8763 // shall have a non-dependent type.
8764 SourceRange ParamUseRange =
8765 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8766 if (ParamUseRange.isValid()) {
8767 if (IsDefaultArgument) {
8768 S.Diag(TemplateNameLoc,
8769 diag::err_dependent_non_type_arg_in_partial_spec);
8770 S.Diag(ParamUseRange.getBegin(),
8771 diag::note_dependent_non_type_default_arg_in_partial_spec)
8772 << ParamUseRange;
8773 } else {
8774 S.Diag(ParamUseRange.getBegin(),
8775 diag::err_dependent_non_type_arg_in_partial_spec)
8776 << ParamUseRange;
8777 }
8778 return true;
8779 }
8780
8781 ParamUseRange = findTemplateParameter(
8782 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8783 if (ParamUseRange.isValid()) {
8784 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8785 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8786 << Param->getType();
8788 return true;
8789 }
8790 }
8791
8792 return HasError;
8793}
8794
8796 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8797 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8798 // We have to be conservative when checking a template in a dependent
8799 // context.
8800 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8801 return false;
8802
8803 TemplateParameterList *TemplateParams =
8804 PrimaryTemplate->getTemplateParameters();
8805 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8807 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8808 if (!Param)
8809 continue;
8810
8811 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8812 Param, &TemplateArgs[I],
8813 1, I >= NumExplicit))
8814 return true;
8815 }
8816
8817 return false;
8818}
8819
8821 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8822 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8824 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8825 assert(TUK != TagUseKind::Reference && "References are not specializations");
8826
8827 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8828 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8829 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8830
8831 // Find the class template we're specializing
8832 TemplateName Name = TemplateId.Template.get();
8834 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8835
8836 if (!ClassTemplate) {
8837 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8838 << (Name.getAsTemplateDecl() &&
8840 return true;
8841 }
8842
8843 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8844 auto Message = DSA->getMessage();
8845 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8846 << ClassTemplate << !Message.empty() << Message;
8847 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8848 }
8849
8850 if (S->isTemplateParamScope())
8851 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8852
8853 DeclContext *DC = ClassTemplate->getDeclContext();
8854
8855 bool isMemberSpecialization = false;
8856 bool isPartialSpecialization = false;
8857
8858 if (SS.isSet()) {
8859 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8860 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8861 TemplateNameLoc, &TemplateId,
8862 /*IsMemberSpecialization=*/false))
8863 return true;
8864 }
8865
8866 // Check the validity of the template headers that introduce this
8867 // template.
8868 // FIXME: We probably shouldn't complain about these headers for
8869 // friend declarations.
8870 bool Invalid = false;
8871 TemplateParameterList *TemplateParams =
8873 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8874 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8875 if (Invalid)
8876 return true;
8877
8878 // Check that we can declare a template specialization here.
8879 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8880 return true;
8881
8882 if (TemplateParams && DC->isDependentContext()) {
8883 ContextRAII SavedContext(*this, DC);
8885 return true;
8886 }
8887
8888 if (TemplateParams && TemplateParams->size() > 0) {
8889 isPartialSpecialization = true;
8890
8891 if (TUK == TagUseKind::Friend) {
8892 Diag(KWLoc, diag::err_partial_specialization_friend)
8893 << SourceRange(LAngleLoc, RAngleLoc);
8894 return true;
8895 }
8896
8897 // C++ [temp.class.spec]p10:
8898 // The template parameter list of a specialization shall not
8899 // contain default template argument values.
8900 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8901 Decl *Param = TemplateParams->getParam(I);
8902 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8903 if (TTP->hasDefaultArgument()) {
8904 Diag(TTP->getDefaultArgumentLoc(),
8905 diag::err_default_arg_in_partial_spec);
8906 TTP->removeDefaultArgument();
8907 }
8908 } else if (NonTypeTemplateParmDecl *NTTP
8909 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8910 if (NTTP->hasDefaultArgument()) {
8911 Diag(NTTP->getDefaultArgumentLoc(),
8912 diag::err_default_arg_in_partial_spec)
8913 << NTTP->getDefaultArgument().getSourceRange();
8914 NTTP->removeDefaultArgument();
8915 }
8916 } else {
8918 if (TTP->hasDefaultArgument()) {
8920 diag::err_default_arg_in_partial_spec)
8922 TTP->removeDefaultArgument();
8923 }
8924 }
8925 }
8926 } else if (TemplateParams) {
8927 if (TUK == TagUseKind::Friend)
8928 Diag(KWLoc, diag::err_template_spec_friend)
8930 SourceRange(TemplateParams->getTemplateLoc(),
8931 TemplateParams->getRAngleLoc()))
8932 << SourceRange(LAngleLoc, RAngleLoc);
8933 } else {
8934 assert(TUK == TagUseKind::Friend &&
8935 "should have a 'template<>' for this decl");
8936 }
8937
8938 // Check that the specialization uses the same tag kind as the
8939 // original template.
8941 assert(Kind != TagTypeKind::Enum &&
8942 "Invalid enum tag in class template spec!");
8943 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8944 TUK == TagUseKind::Definition, KWLoc,
8945 ClassTemplate->getIdentifier())) {
8946 Diag(KWLoc, diag::err_use_with_wrong_tag)
8947 << ClassTemplate
8949 ClassTemplate->getTemplatedDecl()->getKindName());
8950 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8951 diag::note_previous_use);
8952 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8953 }
8954
8955 // Translate the parser's template argument list in our AST format.
8956 TemplateArgumentListInfo TemplateArgs =
8957 makeTemplateArgumentListInfo(*this, TemplateId);
8958
8959 // Check for unexpanded parameter packs in any of the template arguments.
8960 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8961 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8962 isPartialSpecialization
8965 return true;
8966
8967 // Check that the template argument list is well-formed for this
8968 // template.
8970 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8971 /*DefaultArgs=*/{},
8972 /*PartialTemplateArgs=*/false, CTAI,
8973 /*UpdateArgsWithConversions=*/true))
8974 return true;
8975
8976 // Find the class template (partial) specialization declaration that
8977 // corresponds to these arguments.
8978 if (isPartialSpecialization) {
8980 TemplateArgs.size(),
8981 CTAI.CanonicalConverted))
8982 return true;
8983
8984 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8985 // also do it during instantiation.
8986 if (!Name.isDependent() &&
8987 !TemplateSpecializationType::anyDependentTemplateArguments(
8988 TemplateArgs, CTAI.CanonicalConverted)) {
8989 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8990 << ClassTemplate->getDeclName();
8991 isPartialSpecialization = false;
8992 Invalid = true;
8993 }
8994 }
8995
8996 llvm::FoldingSetInsertToken InsertToken;
8997 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8998
8999 if (isPartialSpecialization)
9000 PrevDecl = ClassTemplate->findPartialSpecialization(
9001 CTAI.CanonicalConverted, TemplateParams, InsertToken);
9002 else
9003 PrevDecl =
9004 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
9005
9007
9008 // Check whether we can declare a class template specialization in
9009 // the current scope.
9010 if (TUK != TagUseKind::Friend &&
9012 TemplateNameLoc,
9013 isPartialSpecialization))
9014 return true;
9015
9016 if (!isPartialSpecialization) {
9017 // Create a new class template specialization declaration node for
9018 // this explicit specialization or friend declaration.
9020 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9021 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
9022 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9024 if (TemplateParameterLists.size() > 0) {
9025 Specialization->setTemplateParameterListsInfo(Context,
9026 TemplateParameterLists);
9027 }
9028
9029 if (!PrevDecl)
9030 ClassTemplate->AddSpecialization(Specialization, InsertToken);
9031 } else {
9033 Context.getCanonicalTemplateSpecializationType(
9035 TemplateName(ClassTemplate->getCanonicalDecl()),
9036 CTAI.CanonicalConverted));
9037 if (Context.hasSameType(
9038 CanonType,
9039 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
9040 (!Context.getLangOpts().CPlusPlus20 ||
9041 !TemplateParams->hasAssociatedConstraints())) {
9042 // C++ [temp.class.spec]p9b3:
9043 //
9044 // -- The argument list of the specialization shall not be identical
9045 // to the implicit argument list of the primary template.
9046 //
9047 // This rule has since been removed, because it's redundant given DR1495,
9048 // but we keep it because it produces better diagnostics and recovery.
9049 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9050 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9051 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9052 return CheckClassTemplate(
9053 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9054 TemplateNameLoc, Attr, TemplateParams, AS_none,
9055 /*ModulePrivateLoc=*/SourceLocation(),
9056 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9057 TemplateParameterLists.data(), isMemberSpecialization);
9058 }
9059
9060 // Create a new class template partial specialization declaration node.
9062 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9065 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9066 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9067 Partial->setTemplateArgsAsWritten(TemplateArgs);
9068 SetNestedNameSpecifier(*this, Partial, SS);
9069 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9071 Context, TemplateParameterLists.drop_back(1));
9072 }
9073
9074 if (!PrevPartial)
9075 ClassTemplate->AddPartialSpecialization(Partial, InsertToken);
9076 Specialization = Partial;
9077
9078 // If we are providing an explicit specialization of a member class
9079 // template specialization, make a note of that.
9080 if (isMemberSpecialization)
9081 Partial->setMemberSpecialization();
9082
9084 }
9085
9086 // C++ [temp.expl.spec]p6:
9087 // If a template, a member template or the member of a class template is
9088 // explicitly specialized then that specialization shall be declared
9089 // before the first use of that specialization that would cause an implicit
9090 // instantiation to take place, in every translation unit in which such a
9091 // use occurs; no diagnostic is required.
9092 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9093 bool Okay = false;
9094 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9095 // Is there any previous explicit specialization declaration?
9097 Okay = true;
9098 break;
9099 }
9100 }
9101
9102 if (!Okay) {
9103 SourceRange Range(TemplateNameLoc, RAngleLoc);
9104 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9105 << Context.getCanonicalTagType(Specialization) << Range;
9106
9107 Diag(PrevDecl->getPointOfInstantiation(),
9108 diag::note_instantiation_required_here)
9109 << (PrevDecl->getTemplateSpecializationKind()
9111 return true;
9112 }
9113 }
9114
9115 // If this is not a friend, note that this is an explicit specialization.
9116 if (TUK != TagUseKind::Friend)
9117 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9118
9119 // Check that this isn't a redefinition of this specialization.
9120 if (TUK == TagUseKind::Definition) {
9121 RecordDecl *Def = Specialization->getDefinition();
9122 NamedDecl *Hidden = nullptr;
9123 bool HiddenDefVisible = false;
9124 if (Def && SkipBody &&
9125 isRedefinitionAllowedFor(Def, TemplateNameLoc, &Hidden,
9126 HiddenDefVisible)) {
9127 SkipBody->ShouldSkip = true;
9128 SkipBody->Previous = Def;
9129 if (!HiddenDefVisible && Hidden)
9131 } else if (Def) {
9132 SourceRange Range(TemplateNameLoc, RAngleLoc);
9133 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9134 Diag(Def->getLocation(), diag::note_previous_definition);
9135 Specialization->setInvalidDecl();
9136 return true;
9137 }
9138 }
9139
9142
9143 // Add alignment attributes if necessary; these attributes are checked when
9144 // the ASTContext lays out the structure.
9145 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9146 if (LangOpts.HLSL)
9147 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9150 }
9151
9152 if (ModulePrivateLoc.isValid())
9153 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9154 << (isPartialSpecialization? 1 : 0)
9155 << FixItHint::CreateRemoval(ModulePrivateLoc);
9156
9157 // C++ [temp.expl.spec]p9:
9158 // A template explicit specialization is in the scope of the
9159 // namespace in which the template was defined.
9160 //
9161 // We actually implement this paragraph where we set the semantic
9162 // context (in the creation of the ClassTemplateSpecializationDecl),
9163 // but we also maintain the lexical context where the actual
9164 // definition occurs.
9165 Specialization->setLexicalDeclContext(CurContext);
9166
9167 // We may be starting the definition of this specialization.
9168 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9169 Specialization->startDefinition();
9170
9171 if (TUK == TagUseKind::Friend) {
9172 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9173 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9174 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9176 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9177 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9178
9179 // Build the fully-sugared type for this class template
9180 // specialization as the user wrote in the specialization
9181 // itself. This means that we'll pretty-print the type retrieved
9182 // from the specialization's declaration the way that the user
9183 // actually wrote the specialization, rather than formatting the
9184 // name based on the "canonical" representation used to store the
9185 // template arguments in the specialization.
9187 TemplateNameLoc,
9188 WrittenTy,
9189 /*FIXME:*/KWLoc);
9190 Friend->setAccess(AS_public);
9191 CurContext->addDecl(Friend);
9192 } else {
9193 // Add the specialization into its lexical context, so that it can
9194 // be seen when iterating through the list of declarations in that
9195 // context. However, specializations are not found by name lookup.
9196 CurContext->addDecl(Specialization);
9197 }
9198
9199 if (SkipBody && SkipBody->ShouldSkip)
9200 return SkipBody->Previous;
9201
9202 Specialization->setInvalidDecl(Invalid);
9204 return Specialization;
9205}
9206
9208 MultiTemplateParamsArg TemplateParameterLists,
9209 Declarator &D) {
9210 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9211 ActOnDocumentableDecl(NewDecl);
9212 return NewDecl;
9213}
9214
9216 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9217 const IdentifierInfo *Name, SourceLocation NameLoc) {
9218 DeclContext *DC = CurContext;
9219
9220 if (!DC->getRedeclContext()->isFileContext()) {
9221 Diag(NameLoc,
9222 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9223 return nullptr;
9224 }
9225
9226 if (TemplateParameterLists.size() > 1) {
9227 Diag(NameLoc, diag::err_concept_extra_headers);
9228 return nullptr;
9229 }
9230
9231 TemplateParameterList *Params = TemplateParameterLists.front();
9232
9233 if (Params->size() == 0) {
9234 Diag(NameLoc, diag::err_concept_no_parameters);
9235 return nullptr;
9236 }
9237
9238 // Ensure that the parameter pack, if present, is the last parameter in the
9239 // template.
9240 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9241 ParamEnd = Params->end();
9242 ParamIt != ParamEnd; ++ParamIt) {
9243 Decl const *Param = *ParamIt;
9244 if (Param->isParameterPack()) {
9245 if (++ParamIt == ParamEnd)
9246 break;
9247 Diag(Param->getLocation(),
9248 diag::err_template_param_pack_must_be_last_template_parameter);
9249 return nullptr;
9250 }
9251 }
9252
9253 ConceptDecl *NewDecl =
9254 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9255
9256 if (NewDecl->hasAssociatedConstraints()) {
9257 // C++2a [temp.concept]p4:
9258 // A concept shall not have associated constraints.
9259 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9260 NewDecl->setInvalidDecl();
9261 }
9262
9263 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9264 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9266 LookupName(Previous, S);
9267 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9268 /*AllowInlineNamespace*/ false);
9269
9270 // We cannot properly handle redeclarations until we parse the constraint
9271 // expression, so only inject the name if we are sure we are not redeclaring a
9272 // symbol
9273 if (Previous.empty())
9274 PushOnScopeChains(NewDecl, S, true);
9275
9276 return NewDecl;
9277}
9278
9280 bool Found = false;
9281 LookupResult::Filter F = R.makeFilter();
9282 while (F.hasNext()) {
9283 NamedDecl *D = F.next();
9284 if (D == C) {
9285 F.erase();
9286 Found = true;
9287 break;
9288 }
9289 }
9290 F.done();
9291 return Found;
9292}
9293
9296 Expr *ConstraintExpr,
9297 const ParsedAttributesView &Attrs) {
9298 assert(!C->hasDefinition() && "Concept already defined");
9299 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9300 C->setInvalidDecl();
9301 return nullptr;
9302 }
9303 C->setDefinition(ConstraintExpr);
9304 ProcessDeclAttributeList(S, C, Attrs);
9305
9306 // Check for conflicting previous declaration.
9307 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9308 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9310 LookupName(Previous, S);
9311 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9312 /*AllowInlineNamespace*/ false);
9313 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9314 bool AddToScope = true;
9315 CheckConceptRedefinition(C, Previous, AddToScope);
9316
9318 if (!WasAlreadyAdded && AddToScope)
9319 PushOnScopeChains(C, S);
9320
9321 return C;
9322}
9323
9325 LookupResult &Previous, bool &AddToScope) {
9326 AddToScope = true;
9327
9328 if (Previous.empty())
9329 return;
9330
9331 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9332 if (!OldConcept) {
9333 auto *Old = Previous.getRepresentativeDecl();
9334 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9335 << NewDecl->getDeclName();
9336 notePreviousDefinition(Old, NewDecl->getLocation());
9337 AddToScope = false;
9338 return;
9339 }
9340 // Check if we can merge with a concept declaration.
9341 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9342 if (!IsSame) {
9343 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9344 << NewDecl->getDeclName();
9345 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9346 AddToScope = false;
9347 return;
9348 }
9349 if (hasReachableDefinition(OldConcept) &&
9350 IsRedefinitionInModule(NewDecl, OldConcept)) {
9351 Diag(NewDecl->getLocation(), diag::err_redefinition)
9352 << NewDecl->getDeclName();
9353 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9354 AddToScope = false;
9355 return;
9356 }
9357 if (!Previous.isSingleResult()) {
9358 // FIXME: we should produce an error in case of ambig and failed lookups.
9359 // Other decls (e.g. namespaces) also have this shortcoming.
9360 return;
9361 }
9362 // We unwrap canonical decl late to check for module visibility.
9363 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9364}
9365
9367 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9368 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9369 Diag(Loc, diag::err_recursive_concept) << CE;
9370 Diag(CE->getLocation(), diag::note_declared_at);
9371 CE->setInvalidDecl();
9372 return true;
9373 }
9374 // Concept template parameters don't have a definition and can't
9375 // be defined recursively.
9376 return false;
9377}
9378
9379/// \brief Strips various properties off an implicit instantiation
9380/// that has just been explicitly specialized.
9381static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9382 if (MinGW || (isa<FunctionDecl>(D) &&
9383 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9384 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9385
9386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9387 FD->setInlineSpecified(false);
9388}
9389
9390/// Create an ExplicitInstantiationDecl to record source-location info for an
9391/// explicit template instantiation statement, and add it to \p CurContext.
9392///
9393/// For class templates / nested classes, the caller should build a
9394/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9395/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9396///
9397/// For function / variable templates, the caller should pass TypeAsWritten for
9398/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9400 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9401 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9402 NestedNameSpecifierLoc QualifierLoc,
9403 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9404 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9406 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9407 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9408 Context.addExplicitInstantiationDecl(Spec, EID);
9409 CurContext->addDecl(EID);
9410}
9411
9412/// Compute the diagnostic location for an explicit instantiation
9413// declaration or definition.
9414static SourceLocation
9416 SourceLocation PointOfInstantiation) {
9417 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9418 if (EID->getTemplateSpecializationKind() ==
9420 return EID->getTemplateLoc();
9421
9422 // Explicit instantiations following a specialization have no effect and
9423 // hence no PointOfInstantiation. In that case, walk decl backwards
9424 // until a valid name loc is found.
9425 SourceLocation PrevDiagLoc = PointOfInstantiation;
9426 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9427 Prev = Prev->getPreviousDecl()) {
9428 PrevDiagLoc = Prev->getLocation();
9429 }
9430 assert(PrevDiagLoc.isValid() &&
9431 "Explicit instantiation without point of instantiation?");
9432 return PrevDiagLoc;
9433}
9434
9435bool
9438 NamedDecl *PrevDecl,
9440 SourceLocation PrevPointOfInstantiation,
9441 bool &HasNoEffect) {
9442 HasNoEffect = false;
9443
9444 switch (NewTSK) {
9445 case TSK_Undeclared:
9447 assert(
9448 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9449 "previous declaration must be implicit!");
9450 return false;
9451
9453 switch (PrevTSK) {
9454 case TSK_Undeclared:
9456 // Okay, we're just specializing something that is either already
9457 // explicitly specialized or has merely been mentioned without any
9458 // instantiation.
9459 return false;
9460
9462 if (PrevPointOfInstantiation.isInvalid()) {
9463 // The declaration itself has not actually been instantiated, so it is
9464 // still okay to specialize it.
9466 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9467 return false;
9468 }
9469 // Fall through
9470 [[fallthrough]];
9471
9474 assert((PrevTSK == TSK_ImplicitInstantiation ||
9475 PrevPointOfInstantiation.isValid()) &&
9476 "Explicit instantiation without point of instantiation?");
9477
9478 // C++ [temp.expl.spec]p6:
9479 // If a template, a member template or the member of a class template
9480 // is explicitly specialized then that specialization shall be declared
9481 // before the first use of that specialization that would cause an
9482 // implicit instantiation to take place, in every translation unit in
9483 // which such a use occurs; no diagnostic is required.
9484 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9485 // Is there any previous explicit specialization declaration?
9487 return false;
9488 }
9489
9490 Diag(NewLoc, diag::err_specialization_after_instantiation)
9491 << PrevDecl;
9492 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9493 << (PrevTSK != TSK_ImplicitInstantiation);
9494
9495 return true;
9496 }
9497 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9498
9500 switch (PrevTSK) {
9502 // This explicit instantiation declaration is redundant (that's okay).
9503 HasNoEffect = true;
9504 return false;
9505
9506 case TSK_Undeclared:
9508 // We're explicitly instantiating something that may have already been
9509 // implicitly instantiated; that's fine.
9510 return false;
9511
9513 // C++0x [temp.explicit]p4:
9514 // For a given set of template parameters, if an explicit instantiation
9515 // of a template appears after a declaration of an explicit
9516 // specialization for that template, the explicit instantiation has no
9517 // effect.
9518 HasNoEffect = true;
9519 return false;
9520
9522 // C++0x [temp.explicit]p10:
9523 // If an entity is the subject of both an explicit instantiation
9524 // declaration and an explicit instantiation definition in the same
9525 // translation unit, the definition shall follow the declaration.
9526 Diag(NewLoc,
9527 diag::err_explicit_instantiation_declaration_after_definition);
9528
9529 // Explicit instantiations following a specialization have no effect and
9530 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9531 // until a valid name loc is found.
9532 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9533 diag::note_explicit_instantiation_definition_here);
9534 HasNoEffect = true;
9535 return false;
9536 }
9537 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9538
9540 switch (PrevTSK) {
9541 case TSK_Undeclared:
9543 // We're explicitly instantiating something that may have already been
9544 // implicitly instantiated; that's fine.
9545 return false;
9546
9548 // C++ DR 259, C++0x [temp.explicit]p4:
9549 // For a given set of template parameters, if an explicit
9550 // instantiation of a template appears after a declaration of
9551 // an explicit specialization for that template, the explicit
9552 // instantiation has no effect.
9553 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9554 << PrevDecl;
9555 Diag(PrevDecl->getLocation(),
9556 diag::note_previous_template_specialization);
9557 HasNoEffect = true;
9558 return false;
9559
9561 // We're explicitly instantiating a definition for something for which we
9562 // were previously asked to suppress instantiations. That's fine.
9563
9564 // C++0x [temp.explicit]p4:
9565 // For a given set of template parameters, if an explicit instantiation
9566 // of a template appears after a declaration of an explicit
9567 // specialization for that template, the explicit instantiation has no
9568 // effect.
9569 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9570 // Is there any previous explicit specialization declaration?
9572 HasNoEffect = true;
9573 break;
9574 }
9575 }
9576
9577 return false;
9578
9580 // C++0x [temp.spec]p5:
9581 // For a given template and a given set of template-arguments,
9582 // - an explicit instantiation definition shall appear at most once
9583 // in a program,
9584
9585 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9586 Diag(NewLoc, (getLangOpts().MSVCCompat)
9587 ? diag::ext_explicit_instantiation_duplicate
9588 : diag::err_explicit_instantiation_duplicate)
9589 << PrevDecl;
9590 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9591 diag::note_previous_explicit_instantiation);
9592 HasNoEffect = true;
9593 return false;
9594 }
9595 }
9596
9597 llvm_unreachable("Missing specialization/instantiation case?");
9598}
9599
9601 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9603 // Remove anything from Previous that isn't a function template in
9604 // the correct context.
9605 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9606 LookupResult::Filter F = Previous.makeFilter();
9607 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9608 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9609 while (F.hasNext()) {
9610 NamedDecl *D = F.next()->getUnderlyingDecl();
9611 if (!isa<FunctionTemplateDecl>(D)) {
9612 F.erase();
9613 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9614 continue;
9615 }
9616
9617 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9619 F.erase();
9620 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9621 continue;
9622 }
9623 }
9624 F.done();
9625
9626 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9627 if (Previous.empty()) {
9628 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9629 if (IsFriend && FriendQualifier.isDependent() &&
9630 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9631 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9633 Context, Previous.asUnresolvedSet(), ExplicitTemplateArgs);
9634 return false;
9635 }
9636
9637 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9638 << IsFriend;
9639 for (auto &P : DiscardedCandidates)
9640 Diag(P.second->getLocation(),
9641 diag::note_dependent_function_template_spec_discard_reason)
9642 << P.first << IsFriend;
9643 return true;
9644 }
9645
9647 ExplicitTemplateArgs);
9648 return false;
9649}
9650
9652 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9653 LookupResult &Previous, bool QualifiedFriend) {
9654 // The set of function template specializations that could match this
9655 // explicit function template specialization.
9656 UnresolvedSet<8> Candidates;
9657 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9658 /*ForTakingAddress=*/false);
9659
9660 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9661 ConvertedTemplateArgs;
9662
9663 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9664 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9665 I != E; ++I) {
9666 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9667 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9668 // Only consider templates found within the same semantic lookup scope as
9669 // FD.
9670 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9672 continue;
9673
9674 QualType FT = FD->getType();
9675 // C++11 [dcl.constexpr]p8:
9676 // A constexpr specifier for a non-static member function that is not
9677 // a constructor declares that member function to be const.
9678 //
9679 // When matching a constexpr member function template specialization
9680 // against the primary template, we don't yet know whether the
9681 // specialization has an implicit 'const' (because we don't know whether
9682 // it will be a static member function until we know which template it
9683 // specializes). This rule was removed in C++14.
9684 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9685 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9687 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9688 if (OldMD && OldMD->isConst()) {
9689 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9691 EPI.TypeQuals.addConst();
9692 FT = Context.getFunctionType(FPT->getReturnType(),
9693 FPT->getParamTypes(), EPI);
9694 }
9695 }
9696
9698 if (ExplicitTemplateArgs)
9699 Args = *ExplicitTemplateArgs;
9700
9701 // C++ [temp.expl.spec]p11:
9702 // A trailing template-argument can be left unspecified in the
9703 // template-id naming an explicit function template specialization
9704 // provided it can be deduced from the function argument type.
9705 // Perform template argument deduction to determine whether we may be
9706 // specializing this template.
9707 // FIXME: It is somewhat wasteful to build
9708 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9709 FunctionDecl *Specialization = nullptr;
9711 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9712 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9714 // Template argument deduction failed; record why it failed, so
9715 // that we can provide nifty diagnostics.
9716 FailedCandidates.addCandidate().set(
9717 I.getPair(), FunTmpl->getTemplatedDecl(),
9718 MakeDeductionFailureInfo(Context, TDK, Info));
9719 (void)TDK;
9720 continue;
9721 }
9722
9723 // Target attributes are part of the cuda function signature, so
9724 // the deduced template's cuda target must match that of the
9725 // specialization. Given that C++ template deduction does not
9726 // take target attributes into account, we reject candidates
9727 // here that have a different target.
9728 if (LangOpts.CUDA &&
9729 CUDA().IdentifyTarget(Specialization,
9730 /* IgnoreImplicitHDAttr = */ true) !=
9731 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9732 FailedCandidates.addCandidate().set(
9733 I.getPair(), FunTmpl->getTemplatedDecl(),
9736 continue;
9737 }
9738
9739 // Record this candidate.
9740 if (ExplicitTemplateArgs)
9741 ConvertedTemplateArgs[Specialization] = std::move(Args);
9742 Candidates.addDecl(Specialization, I.getAccess());
9743 }
9744 }
9745
9746 // For a qualified friend declaration (with no explicit marker to indicate
9747 // that a template specialization was intended), note all (template and
9748 // non-template) candidates.
9749 if (QualifiedFriend && Candidates.empty()) {
9750 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9751 << FD->getDeclName() << FDLookupContext;
9752 // FIXME: We should form a single candidate list and diagnose all
9753 // candidates at once, to get proper sorting and limiting.
9754 for (auto *OldND : Previous) {
9755 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9756 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9757 }
9758 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9759 return true;
9760 }
9761
9762 // Find the most specialized function template.
9764 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9765 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9766 PDiag(diag::err_function_template_spec_ambiguous)
9767 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9768 PDiag(diag::note_function_template_spec_matched));
9769
9770 if (Result == Candidates.end())
9771 return true;
9772
9773 // Ignore access information; it doesn't figure into redeclaration checking.
9775
9776 if (const auto *PT = Specialization->getPrimaryTemplate();
9777 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9778 auto Message = DSA->getMessage();
9779 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9780 << PT << !Message.empty() << Message;
9781 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9782 }
9783
9784 // C++23 [except.spec]p13:
9785 // An exception specification is considered to be needed when:
9786 // - [...]
9787 // - the exception specification is compared to that of another declaration
9788 // (e.g., an explicit specialization or an overriding virtual function);
9789 // - [...]
9790 //
9791 // The exception specification of a defaulted function is evaluated as
9792 // described above only when needed; similarly, the noexcept-specifier of a
9793 // specialization of a function template or member function of a class
9794 // template is instantiated only when needed.
9795 //
9796 // The standard doesn't specify what the "comparison with another declaration"
9797 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9798 // not state which properties of an explicit specialization must match the
9799 // primary template.
9800 //
9801 // We assume that an explicit specialization must correspond with (per
9802 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9803 // the declaration produced by substitution into the function template.
9804 //
9805 // Since the determination whether two function declarations correspond does
9806 // not consider exception specification, we only need to instantiate it once
9807 // we determine the primary template when comparing types per
9808 // [basic.link]p11.1.
9809 auto *SpecializationFPT =
9810 Specialization->getType()->castAs<FunctionProtoType>();
9811 // If the function has a dependent exception specification, resolve it after
9812 // we have selected the primary template so we can check whether it matches.
9813 if (getLangOpts().CPlusPlus17 &&
9814 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9815 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9816 return true;
9817
9819 = Specialization->getTemplateSpecializationInfo();
9820 assert(SpecInfo && "Function template specialization info missing?");
9821
9822 // Note: do not overwrite location info if previous template
9823 // specialization kind was explicit.
9825 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9826 Specialization->setLocation(FD->getLocation());
9827 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9828 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9829 // function can differ from the template declaration with respect to
9830 // the constexpr specifier.
9831 // FIXME: We need an update record for this AST mutation.
9832 // FIXME: What if there are multiple such prior declarations (for instance,
9833 // from different modules)?
9834 Specialization->setConstexprKind(FD->getConstexprKind());
9835 }
9836
9837 // FIXME: Check if the prior specialization has a point of instantiation.
9838 // If so, we have run afoul of .
9839
9840 // If this is a friend declaration, then we're not really declaring
9841 // an explicit specialization.
9842 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9843
9844 // Check the scope of this explicit specialization.
9845 if (!isFriend &&
9847 Specialization->getPrimaryTemplate(),
9849 false))
9850 return true;
9851
9852 // C++ [temp.expl.spec]p6:
9853 // If a template, a member template or the member of a class template is
9854 // explicitly specialized then that specialization shall be declared
9855 // before the first use of that specialization that would cause an implicit
9856 // instantiation to take place, in every translation unit in which such a
9857 // use occurs; no diagnostic is required.
9858 bool HasNoEffect = false;
9859 if (!isFriend &&
9864 SpecInfo->getPointOfInstantiation(),
9865 HasNoEffect))
9866 return true;
9867
9868 // Mark the prior declaration as an explicit specialization, so that later
9869 // clients know that this is an explicit specialization.
9870 // A dependent friend specialization which has a definition should be treated
9871 // as explicit specialization, despite being invalid.
9872 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9873 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9874 // Since explicit specializations do not inherit '=delete' from their
9875 // primary function template - check if the 'specialization' that was
9876 // implicitly generated (during template argument deduction for partial
9877 // ordering) from the most specialized of all the function templates that
9878 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9879 // first check that it was implicitly generated during template argument
9880 // deduction by making sure it wasn't referenced, and then reset the deleted
9881 // flag to not-deleted, so that we can inherit that information from 'FD'.
9882 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9883 !Specialization->getCanonicalDecl()->isReferenced()) {
9884 // FIXME: This assert will not hold in the presence of modules.
9885 assert(
9886 Specialization->getCanonicalDecl() == Specialization &&
9887 "This must be the only existing declaration of this specialization");
9888 // FIXME: We need an update record for this AST mutation.
9889 Specialization->setDeletedAsWritten(false);
9890 }
9891 // FIXME: We need an update record for this AST mutation.
9894 }
9895
9896 // Turn the given function declaration into a function template
9897 // specialization, with the template arguments from the previous
9898 // specialization.
9899 // Take copies of (semantic and syntactic) template argument lists.
9901 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9902 FD->setFunctionTemplateSpecialization(
9903 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertToken=*/{},
9905 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9906
9907 // A function template specialization inherits the target attributes
9908 // of its template. (We require the attributes explicitly in the
9909 // code to match, but a template may have implicit attributes by
9910 // virtue e.g. of being constexpr, and it passes these implicit
9911 // attributes on to its specializations.)
9912 if (LangOpts.CUDA)
9913 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9914
9915 // The "previous declaration" for this function template specialization is
9916 // the prior function template specialization.
9917 Previous.clear();
9918 Previous.addDecl(Specialization);
9919 return false;
9920}
9921
9922bool
9924 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9925 "Only for non-template members");
9926
9927 // Try to find the member we are instantiating.
9928 NamedDecl *FoundInstantiation = nullptr;
9929 NamedDecl *Instantiation = nullptr;
9930 NamedDecl *InstantiatedFrom = nullptr;
9931 MemberSpecializationInfo *MSInfo = nullptr;
9932
9933 if (Previous.empty()) {
9934 // Nowhere to look anyway.
9935 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9936 UnresolvedSet<8> Candidates;
9937 for (NamedDecl *Candidate : Previous) {
9938 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9939 // Ignore any candidates that aren't member functions.
9940 if (!Method)
9941 continue;
9942
9943 QualType Adjusted = Function->getType();
9944 if (!hasExplicitCallingConv(Adjusted))
9945 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9946 // Ignore any candidates with the wrong type.
9947 // This doesn't handle deduced return types, but both function
9948 // declarations should be undeduced at this point.
9949 // FIXME: The exception specification should probably be ignored when
9950 // comparing the types.
9951 if (!Context.hasSameType(Adjusted, Method->getType()))
9952 continue;
9953
9954 // Ignore any candidates with unsatisfied constraints.
9955 if (ConstraintSatisfaction Satisfaction;
9956 Method->getTrailingRequiresClause() &&
9957 (CheckFunctionConstraints(Method, Satisfaction,
9958 /*UsageLoc=*/Member->getLocation(),
9959 /*ForOverloadResolution=*/true) ||
9960 !Satisfaction.IsSatisfied))
9961 continue;
9962
9963 Candidates.addDecl(Candidate);
9964 }
9965
9966 // If we have no viable candidates left after filtering, we are done.
9967 if (Candidates.empty())
9968 return false;
9969
9970 // Find the function that is more constrained than every other function it
9971 // has been compared to.
9972 UnresolvedSetIterator Best = Candidates.begin();
9973 CXXMethodDecl *BestMethod = nullptr;
9974 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9975 I != E; ++I) {
9976 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9977 if (I == Best ||
9978 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9979 Best = I;
9980 BestMethod = Method;
9981 }
9982 }
9983
9984 FoundInstantiation = *Best;
9985 Instantiation = BestMethod;
9986 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9987 MSInfo = BestMethod->getMemberSpecializationInfo();
9988
9989 // Make sure the best candidate is more constrained than all of the others.
9990 bool Ambiguous = false;
9991 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9992 I != E; ++I) {
9993 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9994 if (I != Best &&
9995 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9996 Ambiguous = true;
9997 break;
9998 }
9999 }
10000
10001 if (Ambiguous) {
10002 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
10003 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10004 for (NamedDecl *Candidate : Candidates) {
10005 Candidate = Candidate->getUnderlyingDecl();
10006 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
10007 << Candidate;
10008 }
10009 return true;
10010 }
10011 } else if (isa<VarDecl>(Member)) {
10012 VarDecl *PrevVar;
10013 if (Previous.isSingleResult() &&
10014 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10015 if (PrevVar->isStaticDataMember()) {
10016 FoundInstantiation = Previous.getRepresentativeDecl();
10017 Instantiation = PrevVar;
10018 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10019 MSInfo = PrevVar->getMemberSpecializationInfo();
10020 }
10021 } else if (isa<RecordDecl>(Member)) {
10022 CXXRecordDecl *PrevRecord;
10023 if (Previous.isSingleResult() &&
10024 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10025 FoundInstantiation = Previous.getRepresentativeDecl();
10026 Instantiation = PrevRecord;
10027 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10028 MSInfo = PrevRecord->getMemberSpecializationInfo();
10029 }
10030 } else if (isa<EnumDecl>(Member)) {
10031 EnumDecl *PrevEnum;
10032 if (Previous.isSingleResult() &&
10033 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10034 FoundInstantiation = Previous.getRepresentativeDecl();
10035 Instantiation = PrevEnum;
10036 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10037 MSInfo = PrevEnum->getMemberSpecializationInfo();
10038 }
10039 }
10040
10041 if (!Instantiation) {
10042 // There is no previous declaration that matches. Since member
10043 // specializations are always out-of-line, the caller will complain about
10044 // this mismatch later.
10045 return false;
10046 }
10047
10048 // A member specialization in a friend declaration isn't really declaring
10049 // an explicit specialization, just identifying a specific (possibly implicit)
10050 // specialization. Don't change the template specialization kind.
10051 //
10052 // FIXME: Is this really valid? Other compilers reject.
10053 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10054 // Preserve instantiation information.
10055 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10056 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10057 cast<CXXMethodDecl>(InstantiatedFrom),
10059 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10060 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10061 cast<CXXRecordDecl>(InstantiatedFrom),
10063 }
10064
10065 Previous.clear();
10066 Previous.addDecl(FoundInstantiation);
10067 return false;
10068 }
10069
10070 // Make sure that this is a specialization of a member.
10071 if (!InstantiatedFrom) {
10072 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10073 << Member;
10074 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10075 return true;
10076 }
10077
10078 // C++ [temp.expl.spec]p6:
10079 // If a template, a member template or the member of a class template is
10080 // explicitly specialized then that specialization shall be declared
10081 // before the first use of that specialization that would cause an implicit
10082 // instantiation to take place, in every translation unit in which such a
10083 // use occurs; no diagnostic is required.
10084 assert(MSInfo && "Member specialization info missing?");
10085
10086 bool HasNoEffect = false;
10089 Instantiation,
10091 MSInfo->getPointOfInstantiation(),
10092 HasNoEffect))
10093 return true;
10094
10095 // Check the scope of this explicit specialization.
10097 InstantiatedFrom,
10098 Instantiation, Member->getLocation(),
10099 false))
10100 return true;
10101
10102 // Note that this member specialization is an "instantiation of" the
10103 // corresponding member of the original template.
10104 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10105 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10106 if (InstantiationFunction->getTemplateSpecializationKind() ==
10108 // Explicit specializations of member functions of class templates do not
10109 // inherit '=delete' from the member function they are specializing.
10110 if (InstantiationFunction->isDeleted()) {
10111 // FIXME: This assert will not hold in the presence of modules.
10112 assert(InstantiationFunction->getCanonicalDecl() ==
10113 InstantiationFunction);
10114 // FIXME: We need an update record for this AST mutation.
10115 InstantiationFunction->setDeletedAsWritten(false);
10116 }
10117 }
10118
10119 MemberFunction->setInstantiationOfMemberFunction(
10121 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10122 MemberVar->setInstantiationOfStaticDataMember(
10123 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10124 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10125 MemberClass->setInstantiationOfMemberClass(
10127 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10128 MemberEnum->setInstantiationOfMemberEnum(
10129 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10130 } else {
10131 llvm_unreachable("unknown member specialization kind");
10132 }
10133
10134 // Save the caller the trouble of having to figure out which declaration
10135 // this specialization matches.
10136 Previous.clear();
10137 Previous.addDecl(FoundInstantiation);
10138 return false;
10139}
10140
10141/// Complete the explicit specialization of a member of a class template by
10142/// updating the instantiated member to be marked as an explicit specialization.
10143///
10144/// \param OrigD The member declaration instantiated from the template.
10145/// \param Loc The location of the explicit specialization of the member.
10146template<typename DeclT>
10147static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10148 SourceLocation Loc) {
10149 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10150 return;
10151
10152 // FIXME: Inform AST mutation listeners of this AST mutation.
10153 // FIXME: If there are multiple in-class declarations of the member (from
10154 // multiple modules, or a declaration and later definition of a member type),
10155 // should we update all of them?
10156 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10157 OrigD->setLocation(Loc);
10158}
10159
10162 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10163 if (Instantiation == Member)
10164 return;
10165
10166 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10167 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10168 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10169 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10170 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10171 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10172 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10173 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10174 else
10175 llvm_unreachable("unknown member specialization kind");
10176}
10177
10178/// Check the scope of an explicit instantiation.
10179///
10180/// \returns true if a serious error occurs, false otherwise.
10182 SourceLocation InstLoc,
10183 bool WasQualifiedName) {
10185 DeclContext *CurContext = S.CurContext->getRedeclContext();
10186
10187 if (CurContext->isRecord()) {
10188 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10189 << D;
10190 return true;
10191 }
10192
10193 // C++11 [temp.explicit]p3:
10194 // An explicit instantiation shall appear in an enclosing namespace of its
10195 // template. If the name declared in the explicit instantiation is an
10196 // unqualified name, the explicit instantiation shall appear in the
10197 // namespace where its template is declared or, if that namespace is inline
10198 // (7.3.1), any namespace from its enclosing namespace set.
10199 //
10200 // This is DR275, which we do not retroactively apply to C++98/03.
10201 if (WasQualifiedName) {
10202 if (CurContext->Encloses(OrigContext))
10203 return false;
10204 } else {
10205 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10206 return false;
10207 }
10208
10209 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10210 if (WasQualifiedName)
10211 S.Diag(InstLoc,
10212 S.getLangOpts().CPlusPlus11?
10213 diag::err_explicit_instantiation_out_of_scope :
10214 diag::warn_explicit_instantiation_out_of_scope_0x)
10215 << D << NS;
10216 else
10217 S.Diag(InstLoc,
10218 S.getLangOpts().CPlusPlus11?
10219 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10220 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10221 << D << NS;
10222 } else
10223 S.Diag(InstLoc,
10224 S.getLangOpts().CPlusPlus11?
10225 diag::err_explicit_instantiation_must_be_global :
10226 diag::warn_explicit_instantiation_must_be_global_0x)
10227 << D;
10228 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10229 return false;
10230}
10231
10232/// Common checks for whether an explicit instantiation of \p D is valid.
10234 SourceLocation InstLoc,
10235 bool WasQualifiedName,
10237 // C++ [temp.explicit]p13:
10238 // An explicit instantiation declaration shall not name a specialization of
10239 // a template with internal linkage.
10242 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10243 return true;
10244 }
10245
10246 // C++11 [temp.explicit]p3: [DR 275]
10247 // An explicit instantiation shall appear in an enclosing namespace of its
10248 // template.
10249 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10250 return true;
10251
10252 return false;
10253}
10254
10255/// Determine whether the given scope specifier has a template-id in it.
10257 // C++11 [temp.explicit]p3:
10258 // If the explicit instantiation is for a member function, a member class
10259 // or a static data member of a class template specialization, the name of
10260 // the class template specialization in the qualified-id for the member
10261 // name shall be a simple-template-id.
10262 //
10263 // C++98 has the same restriction, just worded differently.
10264 for (NestedNameSpecifier NNS = SS.getScopeRep();
10266 /**/) {
10267 const Type *T = NNS.getAsType();
10269 return true;
10270 NNS = T->getPrefix();
10271 }
10272 return false;
10273}
10274
10275/// Make a dllexport or dllimport attr on a class template specialization take
10276/// effect.
10279 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10280 assert(A && "dllExportImportClassTemplateSpecialization called "
10281 "on Def without dllexport or dllimport");
10282
10283 // We reject explicit instantiations in class scope, so there should
10284 // never be any delayed exported classes to worry about.
10285 assert(S.DelayedDllExportClasses.empty() &&
10286 "delayed exports present at explicit instantiation");
10288
10289 // Propagate attribute to base class templates.
10290 for (auto &B : Def->bases()) {
10291 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10292 B.getType()->getAsCXXRecordDecl()))
10294 }
10295
10297}
10298
10300 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10301 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10302 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10303 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10304 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10305 // Find the class template we're specializing
10306 TemplateName Name = TemplateD.get();
10307 TemplateDecl *TD = Name.getAsTemplateDecl();
10308 // Check that the specialization uses the same tag kind as the
10309 // original template.
10311 assert(Kind != TagTypeKind::Enum &&
10312 "Invalid enum tag in class template explicit instantiation!");
10313
10314 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10315
10316 if (!ClassTemplate) {
10317 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10318 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10319 Diag(TD->getLocation(), diag::note_previous_use);
10320 return true;
10321 }
10322
10323 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10324 Kind, /*isDefinition*/false, KWLoc,
10325 ClassTemplate->getIdentifier())) {
10326 Diag(KWLoc, diag::err_use_with_wrong_tag)
10327 << ClassTemplate
10329 ClassTemplate->getTemplatedDecl()->getKindName());
10330 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10331 diag::note_previous_use);
10332 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10333 }
10334
10335 // C++0x [temp.explicit]p2:
10336 // There are two forms of explicit instantiation: an explicit instantiation
10337 // definition and an explicit instantiation declaration. An explicit
10338 // instantiation declaration begins with the extern keyword. [...]
10339 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10342
10344 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10345 // Check for dllexport class template instantiation declarations,
10346 // except for MinGW mode.
10347 for (const ParsedAttr &AL : Attr) {
10348 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10349 Diag(ExternLoc,
10350 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10351 Diag(AL.getLoc(), diag::note_attribute);
10352 break;
10353 }
10354 }
10355
10356 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10357 Diag(ExternLoc,
10358 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10359 Diag(A->getLocation(), diag::note_attribute);
10360 }
10361 }
10362
10363 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10364 // instantiation declarations for most purposes.
10365 bool DLLImportExplicitInstantiationDef = false;
10367 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10368 // Check for dllimport class template instantiation definitions.
10369 bool DLLImport =
10370 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10371 for (const ParsedAttr &AL : Attr) {
10372 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10373 DLLImport = true;
10374 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10375 // dllexport trumps dllimport here.
10376 DLLImport = false;
10377 break;
10378 }
10379 }
10380 if (DLLImport) {
10382 DLLImportExplicitInstantiationDef = true;
10383 }
10384 }
10385
10386 // Translate the parser's template argument list in our AST format.
10387 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10388 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10389
10390 // Check that the template argument list is well-formed for this
10391 // template.
10393 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10394 /*DefaultArgs=*/{}, false, CTAI,
10395 /*UpdateArgsWithConversions=*/true,
10396 /*ConstraintsNotSatisfied=*/nullptr))
10397 return true;
10398
10399 // Find the class template specialization declaration that
10400 // corresponds to these arguments.
10401 llvm::FoldingSetInsertToken InsertToken;
10403 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
10404
10405 TemplateSpecializationKind PrevDecl_TSK
10406 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10407
10408 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10409 Context.getTargetInfo().getTriple().isOSCygMing()) {
10410 // Check for dllexport class template instantiation definitions in MinGW
10411 // mode, if a previous declaration of the instantiation was seen.
10412 for (const ParsedAttr &AL : Attr) {
10413 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10414 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10415 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10416 } else {
10417 Diag(AL.getLoc(),
10418 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10419 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10420 }
10421 break;
10422 }
10423 }
10424 }
10425
10426 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10427 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10428 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10429 return AL.getKind() == ParsedAttr::AT_DLLExport;
10430 })) {
10431 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10432 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10433 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10434 }
10435 }
10436
10437 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10438 SS.isSet(), TSK))
10439 return true;
10440
10442
10443 bool HasNoEffect = false;
10444 if (PrevDecl) {
10445 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10446 PrevDecl, PrevDecl_TSK,
10447 PrevDecl->getPointOfInstantiation(),
10448 HasNoEffect))
10449 return PrevDecl;
10450
10451 // Even though HasNoEffect == true means that this explicit instantiation
10452 // has no effect on semantics, we go on to put its syntax in the AST.
10453
10454 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10455 PrevDecl_TSK == TSK_Undeclared) {
10456 // Since the only prior class template specialization with these
10457 // arguments was referenced but not declared, reuse that
10458 // declaration node as our own, updating the source location
10459 // for the template name to reflect our new declaration.
10460 // (Other source locations will be updated later.)
10461 Specialization = PrevDecl;
10462 Specialization->setLocation(TemplateNameLoc);
10463 PrevDecl = nullptr;
10464 }
10465
10466 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10467 DLLImportExplicitInstantiationDef) {
10468 // The new specialization might add a dllimport attribute.
10469 HasNoEffect = false;
10470 }
10471 }
10472
10473 if (!Specialization) {
10474 // Create a new class template specialization declaration node for
10475 // this explicit specialization.
10477 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10478 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10480
10481 // A MSInheritanceAttr attached to the previous declaration must be
10482 // propagated to the new node prior to instantiation.
10483 if (PrevDecl) {
10484 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10485 auto *Clone = A->clone(getASTContext());
10486 Clone->setInherited(true);
10487 Specialization->addAttr(Clone);
10488 Consumer.AssignInheritanceModel(Specialization);
10489 }
10490 }
10491
10492 if (!HasNoEffect && !PrevDecl) {
10493 // Insert the new specialization.
10494 ClassTemplate->AddSpecialization(Specialization, InsertToken);
10495 }
10496 }
10497
10498 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10499
10500 // Set source locations for keywords.
10501 Specialization->setExternKeywordLoc(ExternLoc);
10502 Specialization->setTemplateKeywordLoc(TemplateLoc);
10503 Specialization->setBraceRange(SourceRange());
10504
10505 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10508
10509 // Add the explicit instantiation into its lexical context. However,
10510 // since explicit instantiations are never found by name lookup, we
10511 // just put it into the declaration context directly.
10512 Specialization->setLexicalDeclContext(CurContext);
10513 CurContext->addDecl(Specialization);
10514
10515 // Syntax is now OK, so return if it has no other effect on semantics.
10516 if (HasNoEffect) {
10517 // Set the template specialization kind.
10518 Specialization->setTemplateSpecializationKind(TSK);
10519
10521 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10522 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10523 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10524 Context.getCanonicalTagType(Specialization));
10526 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10527 TemplateNameLoc, TSI, TSK);
10528 return Specialization;
10529 }
10530
10531 // C++ [temp.explicit]p3:
10532 // A definition of a class template or class member template
10533 // shall be in scope at the point of the explicit instantiation of
10534 // the class template or class member template.
10535 //
10536 // This check comes when we actually try to perform the
10537 // instantiation.
10539 = cast_or_null<ClassTemplateSpecializationDecl>(
10540 Specialization->getDefinition());
10541 if (!Def)
10543 /*Complain=*/true,
10544 CTAI.StrictPackMatch);
10545 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10546 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10547 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10548 }
10549
10550 // Instantiate the members of this class template specialization.
10551 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10552 Specialization->getDefinition());
10553 if (Def) {
10555 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10556 // TSK_ExplicitInstantiationDefinition
10557 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10559 DLLImportExplicitInstantiationDef)) {
10560 // FIXME: Need to notify the ASTMutationListener that we did this.
10562
10563 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10564 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10565 // An explicit instantiation definition can add a dll attribute to a
10566 // template with a previous instantiation declaration. MinGW doesn't
10567 // allow this.
10568 auto *A = cast<InheritableAttr>(
10570 A->setInherited(true);
10571 Def->addAttr(A);
10573 }
10574 }
10575
10576 // Fix a TSK_ImplicitInstantiation followed by a
10577 // TSK_ExplicitInstantiationDefinition
10578 bool NewlyDLLExported =
10579 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10580 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10581 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10582 // An explicit instantiation definition can add a dll attribute to a
10583 // template with a previous implicit instantiation. MinGW doesn't allow
10584 // this. We limit clang to only adding dllexport, to avoid potentially
10585 // strange codegen behavior. For example, if we extend this conditional
10586 // to dllimport, and we have a source file calling a method on an
10587 // implicitly instantiated template class instance and then declaring a
10588 // dllimport explicit instantiation definition for the same template
10589 // class, the codegen for the method call will not respect the dllimport,
10590 // while it will with cl. The Def will already have the DLL attribute,
10591 // since the Def and Specialization will be the same in the case of
10592 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10593 // attribute to the Specialization; we just need to make it take effect.
10594 assert(Def == Specialization &&
10595 "Def and Specialization should match for implicit instantiation");
10597 }
10598
10599 // In MinGW mode, export the template instantiation if the declaration
10600 // was marked dllexport.
10601 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10602 Context.getTargetInfo().getTriple().isOSCygMing() &&
10603 PrevDecl->hasAttr<DLLExportAttr>()) {
10605 }
10606
10607 // Set the template specialization kind. Make sure it is set before
10608 // instantiating the members which will trigger ASTConsumer callbacks.
10609 Specialization->setTemplateSpecializationKind(TSK);
10610 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10611 } else {
10612
10613 // Set the template specialization kind.
10614 Specialization->setTemplateSpecializationKind(TSK);
10615 }
10616
10618 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10619 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10620 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10621 Context.getCanonicalTagType(Specialization));
10623 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10624 TemplateNameLoc, TSI, TSK);
10625 return Specialization;
10626}
10627
10630 SourceLocation TemplateLoc, unsigned TagSpec,
10631 SourceLocation KWLoc, CXXScopeSpec &SS,
10632 IdentifierInfo *Name, SourceLocation NameLoc,
10633 const ParsedAttributesView &Attr) {
10634
10635 bool Owned = false;
10636 bool IsDependent = false;
10637 Decl *TagD =
10638 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10639 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10640 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10641 false, TypeResult(), /*IsTypeSpecifier*/ false,
10642 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10643 .get();
10644
10645 if (!TagD)
10646 return true;
10647
10648 assert(!IsDependent &&
10649 "explicit instantiation of dependent name not yet handled");
10650
10651 TagDecl *Tag = cast<TagDecl>(TagD);
10652 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10653
10654 if (Tag->isInvalidDecl())
10655 return true;
10656
10658 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10659 if (!Pattern) {
10660 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10661 << Context.getCanonicalTagType(Record);
10662 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10663 return true;
10664 }
10665
10666 // C++0x [temp.explicit]p2:
10667 // If the explicit instantiation is for a class or member class, the
10668 // elaborated-type-specifier in the declaration shall include a
10669 // simple-template-id.
10670 //
10671 // C++98 has the same restriction, just worded differently.
10673 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10674 << Record << SS.getRange();
10675
10676 // C++0x [temp.explicit]p2:
10677 // There are two forms of explicit instantiation: an explicit instantiation
10678 // definition and an explicit instantiation declaration. An explicit
10679 // instantiation declaration begins with the extern keyword. [...]
10683
10684 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10685
10686 // Verify that it is okay to explicitly instantiate here.
10687 CXXRecordDecl *PrevDecl
10688 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10689 if (!PrevDecl && Record->getDefinition())
10690 PrevDecl = Record;
10691 if (PrevDecl) {
10693 bool HasNoEffect = false;
10694 assert(MSInfo && "No member specialization information?");
10695 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10696 PrevDecl,
10698 MSInfo->getPointOfInstantiation(),
10699 HasNoEffect))
10700 return true;
10701 if (HasNoEffect) {
10705 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10706 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10707 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10708 TL.setElaboratedKeywordLoc(KWLoc);
10709 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10710 TL.setNameLoc(NameLoc);
10712 TemplateLoc, NestedNameSpecifierLoc(),
10713 nullptr, NameLoc, TSI, TSK);
10714 return TagD;
10715 }
10716 }
10717
10718 CXXRecordDecl *RecordDef
10719 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10720 if (!RecordDef) {
10721 // C++ [temp.explicit]p3:
10722 // A definition of a member class of a class template shall be in scope
10723 // at the point of an explicit instantiation of the member class.
10724 CXXRecordDecl *Def
10725 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10726 if (!Def) {
10727 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10728 << 0 << Record->getDeclName() << Record->getDeclContext();
10729 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10730 << Pattern;
10731 return true;
10732 } else {
10733 if (InstantiateClass(NameLoc, Record, Def,
10735 TSK))
10736 return true;
10737
10738 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10739 if (!RecordDef)
10740 return true;
10741 }
10742 }
10743
10744 // Instantiate all of the members of the class.
10745 InstantiateClassMembers(NameLoc, RecordDef,
10747
10749 MarkVTableUsed(NameLoc, RecordDef, true);
10750
10753 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10754 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10755 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10756 TL.setElaboratedKeywordLoc(KWLoc);
10757 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10758 TL.setNameLoc(NameLoc);
10760 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10761 NameLoc, TSI, TSK);
10762 return TagD;
10763}
10764
10766 SourceLocation ExternLoc,
10767 SourceLocation TemplateLoc,
10768 Declarator &D) {
10769 // Explicit instantiations always require a name.
10770 // TODO: check if/when DNInfo should replace Name.
10772 DeclarationName Name = NameInfo.getName();
10773 if (!Name) {
10774 if (!D.isInvalidType())
10776 diag::err_explicit_instantiation_requires_name)
10778
10779 return true;
10780 }
10781
10782 // Get the innermost enclosing declaration scope.
10783 S = S->getDeclParent();
10784
10785 // Determine the type of the declaration.
10787 QualType R = T->getType();
10788 if (R.isNull())
10789 return true;
10790
10791 // C++ [dcl.stc]p1:
10792 // A storage-class-specifier shall not be specified in [...] an explicit
10793 // instantiation (14.7.2) directive.
10795 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10796 << Name;
10797 return true;
10798 } else if (D.getDeclSpec().getStorageClassSpec()
10800 // Complain about then remove the storage class specifier.
10801 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10803
10805 }
10806
10807 // C++0x [temp.explicit]p1:
10808 // [...] An explicit instantiation of a function template shall not use the
10809 // inline or constexpr specifiers.
10810 // Presumably, this also applies to member functions of class templates as
10811 // well.
10815 diag::err_explicit_instantiation_inline :
10816 diag::warn_explicit_instantiation_inline_0x)
10818 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10819 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10820 // not already specified.
10822 diag::err_explicit_instantiation_constexpr);
10823
10824 // A deduction guide is not on the list of entities that can be explicitly
10825 // instantiated.
10827 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10828 << /*explicit instantiation*/ 0;
10829 return true;
10830 }
10831
10832 // C++0x [temp.explicit]p2:
10833 // There are two forms of explicit instantiation: an explicit instantiation
10834 // definition and an explicit instantiation declaration. An explicit
10835 // instantiation declaration begins with the extern keyword. [...]
10839
10840 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10842 /*ObjectType=*/QualType());
10843
10844 if (!R->isFunctionType()) {
10845 // C++ [temp.explicit]p1:
10846 // A [...] static data member of a class template can be explicitly
10847 // instantiated from the member definition associated with its class
10848 // template.
10849 // C++1y [temp.explicit]p1:
10850 // A [...] variable [...] template specialization can be explicitly
10851 // instantiated from its template.
10852 if (Previous.isAmbiguous())
10853 return true;
10854
10855 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10856 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10857 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10858
10859 if (!PrevTemplate) {
10860 if (!Prev || !Prev->isStaticDataMember()) {
10861 // We expect to see a static data member here.
10862 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10863 << Name;
10864 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10865 P != PEnd; ++P)
10866 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10867 return true;
10868 }
10869
10871 // FIXME: Check for explicit specialization?
10873 diag::err_explicit_instantiation_data_member_not_instantiated)
10874 << Prev;
10875 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10876 // FIXME: Can we provide a note showing where this was declared?
10877 return true;
10878 }
10879 } else {
10880 // Explicitly instantiate a variable template.
10881
10882 // C++1y [dcl.spec.auto]p6:
10883 // ... A program that uses auto or decltype(auto) in a context not
10884 // explicitly allowed in this section is ill-formed.
10885 //
10886 // This includes auto-typed variable template instantiations.
10887 if (R->isUndeducedType()) {
10888 Diag(T->getTypeLoc().getBeginLoc(),
10889 diag::err_auto_not_allowed_var_inst);
10890 return true;
10891 }
10892
10894 // C++1y [temp.explicit]p3:
10895 // If the explicit instantiation is for a variable, the unqualified-id
10896 // in the declaration shall be a template-id.
10898 diag::err_explicit_instantiation_without_template_id)
10899 << PrevTemplate;
10900 Diag(PrevTemplate->getLocation(),
10901 diag::note_explicit_instantiation_here);
10902 return true;
10903 }
10904
10905 // Translate the parser's template argument list into our AST format.
10906 TemplateArgumentListInfo TemplateArgs =
10908
10909 DeclResult Res =
10910 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10911 TemplateArgs, /*SetWrittenArgs=*/true);
10912 if (Res.isInvalid())
10913 return true;
10914
10915 if (!Res.isUsable()) {
10916 // We somehow specified dependent template arguments in an explicit
10917 // instantiation. This should probably only happen during error
10918 // recovery.
10919 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10920 return true;
10921 }
10922
10923 // Ignore access control bits, we don't need them for redeclaration
10924 // checking.
10925 Prev = cast<VarDecl>(Res.get());
10926 ArgsAsWritten =
10928 }
10929
10930 // C++0x [temp.explicit]p2:
10931 // If the explicit instantiation is for a member function, a member class
10932 // or a static data member of a class template specialization, the name of
10933 // the class template specialization in the qualified-id for the member
10934 // name shall be a simple-template-id.
10935 //
10936 // C++98 has the same restriction, just worded differently.
10937 //
10938 // This does not apply to variable template specializations, where the
10939 // template-id is in the unqualified-id instead.
10940 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10942 diag::ext_explicit_instantiation_without_qualified_id)
10943 << Prev << D.getCXXScopeSpec().getRange();
10944
10945 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10946
10947 // Verify that it is okay to explicitly instantiate here.
10950 bool HasNoEffect = false;
10952 PrevTSK, POI, HasNoEffect))
10953 return true;
10954
10955 if (!HasNoEffect) {
10956 // Instantiate static data member or variable template.
10958 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10959 VTSD->setExternKeywordLoc(ExternLoc);
10960 VTSD->setTemplateKeywordLoc(TemplateLoc);
10961 }
10962
10963 // Merge attributes.
10965 if (PrevTemplate)
10966 ProcessAPINotes(Prev);
10967
10970 }
10971
10972 // Check the new variable specialization against the parsed input.
10973 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10974 Diag(T->getTypeLoc().getBeginLoc(),
10975 diag::err_invalid_var_template_spec_type)
10976 << 0 << PrevTemplate << R << Prev->getType();
10977 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10978 << 2 << PrevTemplate->getDeclName();
10979 return true;
10980 }
10981
10983 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10984 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10985 D.getIdentifierLoc(), T, TSK);
10986 return (Decl *)nullptr;
10987 }
10988
10989 // If the declarator is a template-id, translate the parser's template
10990 // argument list into our AST format.
10991 bool HasExplicitTemplateArgs = false;
10992 TemplateArgumentListInfo TemplateArgs;
10994 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10995 HasExplicitTemplateArgs = true;
10996 }
10997
10998 // C++ [temp.explicit]p1:
10999 // A [...] function [...] can be explicitly instantiated from its template.
11000 // A member function [...] of a class template can be explicitly
11001 // instantiated from the member definition associated with its class
11002 // template.
11003 UnresolvedSet<8> TemplateMatches;
11004 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
11006 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
11007 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11008 P != PEnd; ++P) {
11009 NamedDecl *Prev = *P;
11010 if (!HasExplicitTemplateArgs) {
11011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11012 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11013 /*AdjustExceptionSpec*/true);
11014 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11015 if (Method->getPrimaryTemplate()) {
11016 TemplateMatches.addDecl(Method, P.getAccess());
11017 } else {
11018 OverloadCandidate &C = NonTemplateMatches.addCandidate();
11019 C.FoundDecl = P.getPair();
11020 C.Function = Method;
11021 C.Viable = true;
11023 if (Method->getTrailingRequiresClause() &&
11025 /*ForOverloadResolution=*/true) ||
11026 !S.IsSatisfied)) {
11027 C.Viable = false;
11029 }
11030 }
11031 }
11032 }
11033 }
11034
11035 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11036 if (!FunTmpl)
11037 continue;
11038
11039 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11040 FunctionDecl *Specialization = nullptr;
11042 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11043 Specialization, Info);
11045 // Keep track of almost-matches.
11046 FailedTemplateCandidates.addCandidate().set(
11047 P.getPair(), FunTmpl->getTemplatedDecl(),
11048 MakeDeductionFailureInfo(Context, TDK, Info));
11049 (void)TDK;
11050 continue;
11051 }
11052
11053 // Target attributes are part of the cuda function signature, so
11054 // the cuda target of the instantiated function must match that of its
11055 // template. Given that C++ template deduction does not take
11056 // target attributes into account, we reject candidates here that
11057 // have a different target.
11058 if (LangOpts.CUDA &&
11059 CUDA().IdentifyTarget(Specialization,
11060 /* IgnoreImplicitHDAttr = */ true) !=
11061 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11062 FailedTemplateCandidates.addCandidate().set(
11063 P.getPair(), FunTmpl->getTemplatedDecl(),
11066 continue;
11067 }
11068
11069 TemplateMatches.addDecl(Specialization, P.getAccess());
11070 }
11071
11072 FunctionDecl *Specialization = nullptr;
11073 if (!NonTemplateMatches.empty()) {
11074 unsigned Msg = 0;
11075 OverloadCandidateDisplayKind DisplayKind;
11077 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11078 Best)) {
11079 case OR_Success:
11080 case OR_Deleted:
11081 Specialization = cast<FunctionDecl>(Best->Function);
11082 break;
11083 case OR_Ambiguous:
11084 Msg = diag::err_explicit_instantiation_ambiguous;
11085 DisplayKind = OCD_AmbiguousCandidates;
11086 break;
11088 Msg = diag::err_explicit_instantiation_no_candidate;
11089 DisplayKind = OCD_AllCandidates;
11090 break;
11091 }
11092 if (Msg) {
11093 PartialDiagnostic Diag = PDiag(Msg) << Name;
11094 NonTemplateMatches.NoteCandidates(
11095 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11096 {});
11097 return true;
11098 }
11099 }
11100
11101 if (!Specialization) {
11102 // Find the most specialized function template specialization.
11104 TemplateMatches.begin(), TemplateMatches.end(),
11105 FailedTemplateCandidates, D.getIdentifierLoc(),
11106 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11107 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11108 PDiag(diag::note_explicit_instantiation_candidate));
11109
11110 if (Result == TemplateMatches.end())
11111 return true;
11112
11113 // Ignore access control bits, we don't need them for redeclaration checking.
11115 }
11116
11117 // C++11 [except.spec]p4
11118 // In an explicit instantiation an exception-specification may be specified,
11119 // but is not required.
11120 // If an exception-specification is specified in an explicit instantiation
11121 // directive, it shall be compatible with the exception-specifications of
11122 // other declarations of that function.
11123 if (auto *FPT = R->getAs<FunctionProtoType>())
11124 if (FPT->hasExceptionSpec()) {
11125 unsigned DiagID =
11126 diag::err_mismatched_exception_spec_explicit_instantiation;
11127 if (getLangOpts().MicrosoftExt)
11128 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11130 PDiag(DiagID) << Specialization->getType(),
11131 PDiag(diag::note_explicit_instantiation_here),
11132 Specialization->getType()->getAs<FunctionProtoType>(),
11133 Specialization->getLocation(), FPT, D.getBeginLoc());
11134 // In Microsoft mode, mismatching exception specifications just cause a
11135 // warning.
11136 if (!getLangOpts().MicrosoftExt && Result)
11137 return true;
11138 }
11139
11140 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11142 diag::err_explicit_instantiation_member_function_not_instantiated)
11144 << (Specialization->getTemplateSpecializationKind() ==
11146 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11147 return true;
11148 }
11149
11150 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11151 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11152 PrevDecl = Specialization;
11153
11154 if (PrevDecl) {
11155 bool HasNoEffect = false;
11157 PrevDecl,
11159 PrevDecl->getPointOfInstantiation(),
11160 HasNoEffect))
11161 return true;
11162
11163 if (HasNoEffect) {
11164 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11165 if (HasExplicitTemplateArgs)
11166 ArgsAsWritten =
11169 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11170 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11171 D.getIdentifierLoc(), T, TSK);
11172 return (Decl *)nullptr;
11173 }
11174 }
11175
11176 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11177 // functions
11178 // valarray<size_t>::valarray(size_t) and
11179 // valarray<size_t>::~valarray()
11180 // that it declared to have internal linkage with the internal_linkage
11181 // attribute. Ignore the explicit instantiation declaration in this case.
11182 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11184 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11185 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11186 RD->isInStdNamespace())
11187 return (Decl*) nullptr;
11188 }
11189
11192
11193 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11194 // instantiation declarations.
11196 Specialization->hasAttr<DLLImportAttr>() &&
11197 Context.getTargetInfo().getCXXABI().isMicrosoft())
11199
11200 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11201 if (Specialization->isDefined()) {
11202 // Let the ASTConsumer know that this function has been explicitly
11203 // instantiated now, and its linkage might have changed.
11204 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11205 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11206 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11207 // be explicitly instantiated.
11208 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11209 RD && RD->isLambda()) {
11210 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11211 << /*instantiation*/ 1;
11212 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11213 return (Decl *)nullptr;
11214 }
11216 }
11217
11218 // C++0x [temp.explicit]p2:
11219 // If the explicit instantiation is for a member function, a member class
11220 // or a static data member of a class template specialization, the name of
11221 // the class template specialization in the qualified-id for the member
11222 // name shall be a simple-template-id.
11223 //
11224 // C++98 has the same restriction, just worded differently.
11225 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11226 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11227 D.getCXXScopeSpec().isSet() &&
11230 diag::ext_explicit_instantiation_without_qualified_id)
11232
11234 *this,
11235 FunTmpl ? (NamedDecl *)FunTmpl
11236 : Specialization->getInstantiatedFromMemberFunction(),
11237 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11238
11239 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11240 if (HasExplicitTemplateArgs)
11241 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11243 TemplateLoc,
11245 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11246 return (Decl *)nullptr;
11247}
11248
11250 const CXXScopeSpec &SS,
11251 const IdentifierInfo *Name,
11252 SourceLocation TagLoc,
11253 SourceLocation NameLoc) {
11254 // This has to hold, because SS is expected to be defined.
11255 assert(Name && "Expected a name in a dependent tag");
11256
11258 if (!NNS)
11259 return true;
11260
11261 if (TUK == TagUseKind::Friend &&
11263 return true;
11264
11266
11267 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11268 Diag(NameLoc, diag::err_dependent_tag_decl)
11269 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11270 return true;
11271 }
11272
11273 // Create the resulting type.
11275 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11276
11277 // Create type-source location information for this type.
11278 TypeLocBuilder TLB;
11280 TL.setElaboratedKeywordLoc(TagLoc);
11282 TL.setNameLoc(NameLoc);
11284}
11285
11287 const CXXScopeSpec &SS,
11288 const IdentifierInfo &II,
11289 SourceLocation IdLoc,
11290 ImplicitTypenameContext IsImplicitTypename) {
11291 if (SS.isInvalid())
11292 return true;
11293
11294 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11295 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11296 << FixItHint::CreateRemoval(TypenameLoc);
11297
11299 TypeSourceInfo *TSI = nullptr;
11300 QualType T =
11303 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11304 /*DeducedTSTContext=*/true);
11305 if (T.isNull())
11306 return true;
11307 return CreateParsedType(T, TSI);
11308}
11309
11312 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11313 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11314 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11315 ASTTemplateArgsPtr TemplateArgsIn,
11316 SourceLocation RAngleLoc) {
11317 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11318 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11319 ? diag::compat_cxx11_typename_outside_of_template
11320 : diag::compat_pre_cxx11_typename_outside_of_template)
11321 << FixItHint::CreateRemoval(TypenameLoc);
11322
11323 // Strangely, non-type results are not ignored by this lookup, so the
11324 // program is ill-formed if it finds an injected-class-name.
11325 if (TypenameLoc.isValid()) {
11326 auto *LookupRD =
11327 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11328 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11329 Diag(TemplateIILoc,
11330 diag::ext_out_of_line_qualified_id_type_names_constructor)
11331 << TemplateII << 0 /*injected-class-name used as template name*/
11332 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11333 }
11334 }
11335
11336 // Translate the parser's template argument list in our AST format.
11337 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11338 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11339
11343 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11344 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11345 if (T.isNull())
11346 return true;
11347
11348 // Provide source-location information for the template specialization type.
11349 TypeLocBuilder Builder;
11351 = Builder.push<TemplateSpecializationTypeLoc>(T);
11352 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11353 TemplateIILoc, TemplateArgs);
11354 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11355 return CreateParsedType(T, TSI);
11356}
11357
11358/// Determine whether this failed name lookup should be treated as being
11359/// disabled by a usage of std::enable_if.
11361 SourceRange &CondRange, Expr *&Cond) {
11362 // We must be looking for a ::type...
11363 if (!II.isStr("type"))
11364 return false;
11365
11366 // ... within an explicitly-written template specialization...
11368 return false;
11369
11370 // FIXME: Look through sugar.
11371 auto EnableIfTSTLoc =
11373 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11374 return false;
11375 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11376
11377 // ... which names a complete class template declaration...
11378 const TemplateDecl *EnableIfDecl =
11379 EnableIfTST->getTemplateName().getAsTemplateDecl();
11380 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11381 return false;
11382
11383 // ... called "enable_if".
11384 const IdentifierInfo *EnableIfII =
11385 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11386 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11387 return false;
11388
11389 // Assume the first template argument is the condition.
11390 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11391
11392 // Dig out the condition.
11393 Cond = nullptr;
11394 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11396 return true;
11397
11398 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11399
11400 // Ignore Boolean literals; they add no value.
11402 Cond = nullptr;
11403
11404 return true;
11405}
11406
11409 SourceLocation KeywordLoc,
11410 NestedNameSpecifierLoc QualifierLoc,
11411 const IdentifierInfo &II,
11412 SourceLocation IILoc,
11413 TypeSourceInfo **TSI,
11414 bool DeducedTSTContext) {
11415 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11416 DeducedTSTContext);
11417 if (T.isNull())
11418 return QualType();
11419
11420 TypeLocBuilder TLB;
11422 auto TL = TLB.push<DependentNameTypeLoc>(T);
11423 TL.setElaboratedKeywordLoc(KeywordLoc);
11424 TL.setQualifierLoc(QualifierLoc);
11425 TL.setNameLoc(IILoc);
11428 TL.setElaboratedKeywordLoc(KeywordLoc);
11429 TL.setQualifierLoc(QualifierLoc);
11430 TL.setNameLoc(IILoc);
11431 } else if (isa<TemplateTypeParmType>(T)) {
11432 // FIXME: There might be a 'typename' keyword here, but we just drop it
11433 // as it can't be represented.
11434 assert(!QualifierLoc);
11435 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11436 } else if (isa<TagType>(T)) {
11437 auto TL = TLB.push<TagTypeLoc>(T);
11438 TL.setElaboratedKeywordLoc(KeywordLoc);
11439 TL.setQualifierLoc(QualifierLoc);
11440 TL.setNameLoc(IILoc);
11441 } else if (isa<TypedefType>(T)) {
11442 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11443 } else {
11444 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11445 }
11446 *TSI = TLB.getTypeSourceInfo(Context, T);
11447 return T;
11448}
11449
11450/// Build the type that describes a C++ typename specifier,
11451/// e.g., "typename T::type".
11454 SourceLocation KeywordLoc,
11455 NestedNameSpecifierLoc QualifierLoc,
11456 const IdentifierInfo &II,
11457 SourceLocation IILoc, bool DeducedTSTContext) {
11458 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11459
11460 CXXScopeSpec SS;
11461 SS.Adopt(QualifierLoc);
11462
11463 DeclContext *Ctx = nullptr;
11464 if (QualifierLoc) {
11465 Ctx = computeDeclContext(SS);
11466 if (!Ctx) {
11467 // If the nested-name-specifier is dependent and couldn't be
11468 // resolved to a type, build a typename type.
11469 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11470 return Context.getDependentNameType(Keyword,
11471 QualifierLoc.getNestedNameSpecifier(),
11472 &II);
11473 }
11474
11475 // If the nested-name-specifier refers to the current instantiation,
11476 // the "typename" keyword itself is superfluous. In C++03, the
11477 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11478 // allows such extraneous "typename" keywords, and we retroactively
11479 // apply this DR to C++03 code with only a warning. In any case we continue.
11480
11481 if (RequireCompleteDeclContext(SS, Ctx))
11482 return QualType();
11483 }
11484
11485 DeclarationName Name(&II);
11486 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11487 if (Ctx)
11488 LookupQualifiedName(Result, Ctx, SS);
11489 else
11490 LookupName(Result, CurScope);
11491 unsigned DiagID = 0;
11492 Decl *Referenced = nullptr;
11493 switch (Result.getResultKind()) {
11495 // If we're looking up 'type' within a template named 'enable_if', produce
11496 // a more specific diagnostic.
11497 SourceRange CondRange;
11498 Expr *Cond = nullptr;
11499 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11500 // If we have a condition, narrow it down to the specific failed
11501 // condition.
11502 if (Cond) {
11503 Expr *FailedCond;
11504 std::string FailedDescription;
11505 std::tie(FailedCond, FailedDescription) =
11507
11508 Diag(FailedCond->getExprLoc(),
11509 diag::err_typename_nested_not_found_requirement)
11510 << FailedDescription
11511 << FailedCond->getSourceRange();
11512 return QualType();
11513 }
11514
11515 Diag(CondRange.getBegin(),
11516 diag::err_typename_nested_not_found_enable_if)
11517 << Ctx << CondRange;
11518 return QualType();
11519 }
11520
11521 DiagID = Ctx ? diag::err_typename_nested_not_found
11522 : diag::err_unknown_typename;
11523 break;
11524 }
11525
11527 // We found a using declaration that is a value. Most likely, the using
11528 // declaration itself is meant to have the 'typename' keyword.
11529 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11530 IILoc);
11531 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11532 << Name << Ctx << FullRange;
11533 if (UnresolvedUsingValueDecl *Using
11534 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11535 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11536 Diag(Loc, diag::note_using_value_decl_missing_typename)
11537 << FixItHint::CreateInsertion(Loc, "typename ");
11538 }
11539 }
11540 // Fall through to create a dependent typename type, from which we can
11541 // recover better.
11542 [[fallthrough]];
11543
11545 // Okay, it's a member of an unknown instantiation.
11546 return Context.getDependentNameType(Keyword,
11547 QualifierLoc.getNestedNameSpecifier(),
11548 &II);
11549
11551 // FXIME: Missing support for UsingShadowDecl on this path?
11552 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11553 // C++ [class.qual]p2:
11554 // In a lookup in which function names are not ignored and the
11555 // nested-name-specifier nominates a class C, if the name specified
11556 // after the nested-name-specifier, when looked up in C, is the
11557 // injected-class-name of C [...] then the name is instead considered
11558 // to name the constructor of class C.
11559 //
11560 // Unlike in an elaborated-type-specifier, function names are not ignored
11561 // in typename-specifier lookup. However, they are ignored in all the
11562 // contexts where we form a typename type with no keyword (that is, in
11563 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11564 //
11565 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11566 // ignore functions, but that appears to be an oversight.
11571 Type, IILoc);
11572 // FIXME: This appears to be the only case where a template type parameter
11573 // can have an elaborated keyword. We should preserve it somehow.
11576 assert(!QualifierLoc);
11578 }
11579 return Context.getTypeDeclType(
11580 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11581 }
11582
11583 // C++ [dcl.type.simple]p2:
11584 // A type-specifier of the form
11585 // typename[opt] nested-name-specifier[opt] template-name
11586 // is a placeholder for a deduced class type [...].
11587 if (getLangOpts().CPlusPlus17) {
11588 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11589 if (!DeducedTSTContext) {
11590 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11591 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11592 Diag(IILoc, diag::err_dependent_deduced_tst)
11594 << QualType(Qualifier.getAsType(), 0);
11595 else
11596 Diag(IILoc, diag::err_deduced_tst)
11599 return QualType();
11600 }
11601 TemplateName Name = Context.getQualifiedTemplateName(
11602 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11603 TemplateName(TD));
11604 return Context.getDeducedTemplateSpecializationType(
11605 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11606 Name);
11607 }
11608 }
11609
11610 DiagID = Ctx ? diag::err_typename_nested_not_type
11611 : diag::err_typename_not_type;
11612 Referenced = Result.getFoundDecl();
11613 break;
11614
11616 DiagID = Ctx ? diag::err_typename_nested_not_type
11617 : diag::err_typename_not_type;
11618 Referenced = *Result.begin();
11619 break;
11620
11622 return QualType();
11623 }
11624
11625 // If we get here, it's because name lookup did not find a
11626 // type. Emit an appropriate diagnostic and return an error.
11627 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11628 IILoc);
11629 if (Ctx)
11630 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11631 else
11632 Diag(IILoc, DiagID) << FullRange << Name;
11633 if (Referenced)
11634 Diag(Referenced->getLocation(),
11635 Ctx ? diag::note_typename_member_refers_here
11636 : diag::note_typename_refers_here)
11637 << Name;
11638 return QualType();
11639}
11640
11641namespace {
11642 // See Sema::RebuildTypeInCurrentInstantiation
11643 class CurrentInstantiationRebuilder
11644 : public TreeTransform<CurrentInstantiationRebuilder> {
11645 SourceLocation Loc;
11646 DeclarationName Entity;
11647
11648 public:
11650
11651 CurrentInstantiationRebuilder(Sema &SemaRef,
11652 SourceLocation Loc,
11653 DeclarationName Entity)
11654 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11655 Loc(Loc), Entity(Entity) { }
11656
11657 /// Determine whether the given type \p T has already been
11658 /// transformed.
11659 ///
11660 /// For the purposes of type reconstruction, a type has already been
11661 /// transformed if it is NULL or if it is not dependent.
11662 bool AlreadyTransformed(QualType T) {
11663 return T.isNull() || !T->isInstantiationDependentType();
11664 }
11665
11666 /// Returns the location of the entity whose type is being
11667 /// rebuilt.
11668 SourceLocation getBaseLocation() { return Loc; }
11669
11670 /// Returns the name of the entity whose type is being rebuilt.
11671 DeclarationName getBaseEntity() { return Entity; }
11672
11673 /// Sets the "base" location and entity when that
11674 /// information is known based on another transformation.
11675 void setBase(SourceLocation Loc, DeclarationName Entity) {
11676 this->Loc = Loc;
11677 this->Entity = Entity;
11678 }
11679
11680 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11681 // Lambdas never need to be transformed.
11682 return E;
11683 }
11684 };
11685} // end anonymous namespace
11686
11688 SourceLocation Loc,
11689 DeclarationName Name) {
11690 if (!T || !T->getType()->isInstantiationDependentType())
11691 return T;
11692
11693 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11694 return Rebuilder.TransformType(T);
11695}
11696
11698 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11699 DeclarationName());
11700 return Rebuilder.TransformExpr(E);
11701}
11702
11704 if (SS.isInvalid())
11705 return true;
11706
11708 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11709 DeclarationName());
11711 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11712 if (!Rebuilt)
11713 return true;
11714
11715 SS.Adopt(Rebuilt);
11716 return false;
11717}
11718
11720 TemplateParameterList *Params) {
11721 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11722 Decl *Param = Params->getParam(I);
11723
11724 // There is nothing to rebuild in a type parameter.
11725 if (isa<TemplateTypeParmDecl>(Param))
11726 continue;
11727
11728 // Rebuild the template parameter list of a template template parameter.
11730 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11732 TTP->getTemplateParameters()))
11733 return true;
11734
11735 continue;
11736 }
11737
11738 // Rebuild the type of a non-type template parameter.
11740 TypeSourceInfo *NewTSI
11742 NTTP->getLocation(),
11743 NTTP->getDeclName());
11744 if (!NewTSI)
11745 return true;
11746
11747 if (NewTSI->getType()->isUndeducedType()) {
11748 // C++17 [temp.dep.expr]p3:
11749 // An id-expression is type-dependent if it contains
11750 // - an identifier associated by name lookup with a non-type
11751 // template-parameter declared with a type that contains a
11752 // placeholder type (7.1.7.4),
11753 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11754 }
11755
11756 if (NewTSI != NTTP->getTypeSourceInfo()) {
11757 NTTP->setTypeSourceInfo(NewTSI);
11758 NTTP->setType(NewTSI->getType());
11759 }
11760 }
11761
11762 return false;
11763}
11764
11765std::string
11767 const TemplateArgumentList &Args) {
11768 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11769}
11770
11771std::string
11773 const TemplateArgument *Args,
11774 unsigned NumArgs) {
11775 SmallString<128> Str;
11776 llvm::raw_svector_ostream Out(Str);
11777
11778 if (!Params || Params->size() == 0 || NumArgs == 0)
11779 return std::string();
11780
11781 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11782 if (I >= NumArgs)
11783 break;
11784
11785 if (I == 0)
11786 Out << "[with ";
11787 else
11788 Out << ", ";
11789
11790 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11791 Out << Id->getName();
11792 } else {
11793 Out << '$' << I;
11794 }
11795
11796 Out << " = ";
11797 Args[I].print(getPrintingPolicy(), Out,
11799 getPrintingPolicy(), Params, I));
11800 }
11801
11802 Out << ']';
11803 return std::string(Out.str());
11804}
11805
11807 CachedTokens &Toks) {
11808 if (!FD)
11809 return;
11810
11811 auto LPT = std::make_unique<LateParsedTemplate>();
11812
11813 // Take tokens to avoid allocations
11814 LPT->Toks.swap(Toks);
11815 LPT->D = FnD;
11816 LPT->FPO = getCurFPFeatures();
11817 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11818
11819 FD->setLateTemplateParsed(true);
11820}
11821
11823 if (!FD)
11824 return;
11825 FD->setLateTemplateParsed(false);
11826}
11827
11829 DeclContext *DC = CurContext;
11830
11831 while (DC) {
11832 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11833 const FunctionDecl *FD = RD->isLocalClass();
11834 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11835 } else if (DC->isTranslationUnit() || DC->isNamespace())
11836 return false;
11837
11838 DC = DC->getParent();
11839 }
11840 return false;
11841}
11842
11843namespace {
11844/// Walk the path from which a declaration was instantiated, and check
11845/// that every explicit specialization along that path is visible. This enforces
11846/// C++ [temp.expl.spec]/6:
11847///
11848/// If a template, a member template or a member of a class template is
11849/// explicitly specialized then that specialization shall be declared before
11850/// the first use of that specialization that would cause an implicit
11851/// instantiation to take place, in every translation unit in which such a
11852/// use occurs; no diagnostic is required.
11853///
11854/// and also C++ [temp.class.spec]/1:
11855///
11856/// A partial specialization shall be declared before the first use of a
11857/// class template specialization that would make use of the partial
11858/// specialization as the result of an implicit or explicit instantiation
11859/// in every translation unit in which such a use occurs; no diagnostic is
11860/// required.
11861class ExplicitSpecializationVisibilityChecker {
11862 Sema &S;
11863 SourceLocation Loc;
11866
11867public:
11868 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11870 : S(S), Loc(Loc), Kind(Kind) {}
11871
11872 void check(NamedDecl *ND) {
11873 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11874 return checkImpl(FD);
11875 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11876 return checkImpl(RD);
11877 if (auto *VD = dyn_cast<VarDecl>(ND))
11878 return checkImpl(VD);
11879 if (auto *ED = dyn_cast<EnumDecl>(ND))
11880 return checkImpl(ED);
11881 }
11882
11883private:
11884 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11885 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11886 : Sema::MissingImportKind::ExplicitSpecialization;
11887 const bool Recover = true;
11888
11889 // If we got a custom set of modules (because only a subset of the
11890 // declarations are interesting), use them, otherwise let
11891 // diagnoseMissingImport intelligently pick some.
11892 if (Modules.empty())
11893 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11894 else
11895 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11896 }
11897
11898 bool CheckMemberSpecialization(const NamedDecl *D) {
11899 return Kind == Sema::AcceptableKind::Visible
11902 }
11903
11904 bool CheckExplicitSpecialization(const NamedDecl *D) {
11905 return Kind == Sema::AcceptableKind::Visible
11908 }
11909
11910 bool CheckDeclaration(const NamedDecl *D) {
11911 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11913 }
11914
11915 // Check a specific declaration. There are three problematic cases:
11916 //
11917 // 1) The declaration is an explicit specialization of a template
11918 // specialization.
11919 // 2) The declaration is an explicit specialization of a member of an
11920 // templated class.
11921 // 3) The declaration is an instantiation of a template, and that template
11922 // is an explicit specialization of a member of a templated class.
11923 //
11924 // We don't need to go any deeper than that, as the instantiation of the
11925 // surrounding class / etc is not triggered by whatever triggered this
11926 // instantiation, and thus should be checked elsewhere.
11927 template<typename SpecDecl>
11928 void checkImpl(SpecDecl *Spec) {
11929 bool IsHiddenExplicitSpecialization = false;
11930 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11931 // Some invalid friend declarations are written as specializations but are
11932 // instantiated implicitly.
11933 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11934 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11935 if (SpecKind == TSK_ExplicitSpecialization) {
11936 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11937 ? !CheckMemberSpecialization(Spec)
11938 : !CheckExplicitSpecialization(Spec);
11939 } else {
11940 checkInstantiated(Spec);
11941 }
11942
11943 if (IsHiddenExplicitSpecialization)
11944 diagnose(Spec->getMostRecentDecl(), false);
11945 }
11946
11947 void checkInstantiated(FunctionDecl *FD) {
11948 if (auto *TD = FD->getPrimaryTemplate())
11949 checkTemplate(TD);
11950 }
11951
11952 void checkInstantiated(CXXRecordDecl *RD) {
11953 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11954 if (!SD)
11955 return;
11956
11957 auto From = SD->getSpecializedTemplateOrPartial();
11958 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11959 checkTemplate(TD);
11960 else if (auto *TD =
11961 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11962 if (!CheckDeclaration(TD))
11963 diagnose(TD, true);
11964 checkTemplate(TD);
11965 }
11966 }
11967
11968 void checkInstantiated(VarDecl *RD) {
11969 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11970 if (!SD)
11971 return;
11972
11973 auto From = SD->getSpecializedTemplateOrPartial();
11974 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11975 checkTemplate(TD);
11976 else if (auto *TD =
11977 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11978 if (!CheckDeclaration(TD))
11979 diagnose(TD, true);
11980 checkTemplate(TD);
11981 }
11982 }
11983
11984 void checkInstantiated(EnumDecl *FD) {}
11985
11986 template<typename TemplDecl>
11987 void checkTemplate(TemplDecl *TD) {
11988 if (TD->isMemberSpecialization()) {
11989 if (!CheckMemberSpecialization(TD))
11990 diagnose(TD->getMostRecentDecl(), false);
11991 }
11992 }
11993};
11994} // end anonymous namespace
11995
11997 if (!getLangOpts().Modules)
11998 return;
11999
12000 ExplicitSpecializationVisibilityChecker(*this, Loc,
12002 .check(Spec);
12003}
12004
12006 NamedDecl *Spec) {
12007 if (!getLangOpts().CPlusPlusModules)
12008 return checkSpecializationVisibility(Loc, Spec);
12009
12010 ExplicitSpecializationVisibilityChecker(*this, Loc,
12012 .check(Spec);
12013}
12014
12017 return N->getLocation();
12018 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12020 return FD->getLocation();
12023 return N->getLocation();
12024 }
12025 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12026 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12027 continue;
12028 return CSC.PointOfInstantiation;
12029 }
12030 return N->getLocation();
12031}
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 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 diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:157
const LValueBase getLValueBase() const
Definition APValue.cpp:1065
const void * getReflectionOpaqueOperand() const
Definition APValue.h:780
APSInt & getInt()
Definition APValue.h:566
APSInt & getComplexIntImag()
Definition APValue.h:604
ValueKind getKind() const
Definition APValue.h:536
APFixedPoint & getFixedPoint()
Definition APValue.h:588
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1148
APValue & getVectorElt(unsigned I)
Definition APValue.h:640
unsigned getVectorLength() const
Definition APValue.h:648
bool isLValue() const
Definition APValue.h:547
bool isMemberPointer() const
Definition APValue.h:553
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1038
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:166
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:164
bool isNullPointer() const
Definition APValue.cpp:1101
APSInt & getComplexIntReal()
Definition APValue.h:596
APFloat & getComplexFloatImag()
Definition APValue.h:620
APFloat & getComplexFloatReal()
Definition APValue.h:612
APFloat & getFloat()
Definition APValue.h:580
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
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:46
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:8304
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:2138
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:2150
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:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h: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:4490
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2279
bool isFileContext() const
Definition DeclBase.h:2217
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:2239
bool isTranslationUnit() const
Definition DeclBase.h:2222
bool isRecord() const
Definition DeclBase.h:2226
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:2181
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:1290
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1391
ValueDecl * getDecl()
Definition Expr.h:1358
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:658
void ClearStorageClassSpecs()
Definition DeclSpec.h:503
bool isNoreturnSpecified() const
Definition DeclSpec.h:671
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:498
SCS getStorageClassSpec() const
Definition DeclSpec.h:489
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:563
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:562
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:672
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:664
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:490
ParsedAttributes & getAttributes()
Definition DeclSpec.h:883
bool isInlineSpecified() const
Definition DeclSpec.h:647
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:499
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:659
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:846
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:650
bool hasExplicitSpecifier() const
Definition DeclSpec.h:661
bool hasConstexprSpecifier() const
Definition DeclSpec.h:847
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1078
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:824
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2843
bool isInvalidDecl() const
Definition DeclBase.h:596
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:815
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:838
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1955
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2102
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2391
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2781
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2138
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2121
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2117
bool hasEllipsis() const
Definition DeclSpec.h:2780
bool isInvalidType() const
Definition DeclSpec.h:2769
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2137
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2109
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2385
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:4582
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:4325
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:4146
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4418
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5230
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:113
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3131
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3126
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:847
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:3106
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:4107
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:145
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
Represents a member of a struct/union/class.
Definition Decl.h:3295
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:2059
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4249
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4578
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4357
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4216
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3794
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4188
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:4422
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2489
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4461
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4209
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4994
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
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:4952
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:3897
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:5352
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:3045
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:4451
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:241
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1682
NamedDecl * getMostRecentDecl()
Definition Decl.h:502
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1944
Represent a C++ namespace.
Definition Decl.h:593
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:8031
Represents a pointer to an Objective C object.
Definition TypeBase.h:8087
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:1198
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
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
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:8275
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:8535
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3827
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:8446
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:8631
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3820
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:4460
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5468
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:13834
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8549
A RAII object to temporarily push a declaration context.
Definition Sema.h:3584
Whether and why a template name is required in this lookup.
Definition Sema.h:11565
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11573
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12623
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12657
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7819
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13781
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13232
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2702
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9440
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9444
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9452
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9447
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:9756
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:1499
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:4267
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:2107
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:11536
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12134
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12137
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12141
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:1332
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:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:935
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:778
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:1236
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:12313
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12331
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12321
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12341
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:11586
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11593
@ None
This is not assumed to be a template name.
Definition Sema.h:11588
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11590
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:11522
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:930
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:14628
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14616
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14625
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14619
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14643
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1331
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:1330
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:648
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:1472
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:13872
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:15679
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:1333
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:4772
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:6822
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6801
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:14139
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11563
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:524
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:11746
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11756
@ TPC_FriendFunctionTemplate
Definition Sema.h:11754
@ TPC_ClassTemplateMember
Definition Sema.h:11752
@ TPC_FunctionTemplate
Definition Sema.h:11751
@ TPC_FriendClassTemplate
Definition Sema.h:11753
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11755
friend class InitializationSequence
Definition Sema.h:1614
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:6425
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:6509
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1324
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:3577
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11528
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:148
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:9765
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13075
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:8762
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13869
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:3852
StringRef getKindName() const
Definition Decl.h:4048
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4982
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5118
TagKind getTagKind() const
Definition Decl.h:4052
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:3823
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3648
const Type * getTypeForDecl() const
Definition Decl.h:3673
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3682
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:893
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:6326
A container of type source information.
Definition TypeBase.h:8417
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:8428
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:9209
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:8715
bool isVoidPointerType() const
Definition Type.cpp:845
bool isArrayType() const
Definition TypeBase.h:8782
bool isPointerType() const
Definition TypeBase.h:8683
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
bool isEnumeralType() const
Definition TypeBase.h:8814
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:9194
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8870
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:8711
bool isBitIntType() const
Definition TypeBase.h:8958
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8806
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:8764
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:9215
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:5207
bool isPointerOrReferenceType() const
Definition TypeBase.h:8687
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:8679
bool isVectorType() const
Definition TypeBase.h:8822
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:9299
bool isNullPtrType() const
Definition TypeBase.h:9109
bool isRecordType() const
Definition TypeBase.h:8810
QualType getUnderlyingType() const
Definition Decl.h:3752
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4377
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:2288
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1042
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1074
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1254
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1251
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1070
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1124
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1094
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:6131
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3970
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
TLSKind getTLSKind() const
Definition Decl.cpp:2148
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2747
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:2882
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:2775
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:2754
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2873
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:4273
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:1938
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h: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:598
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1034
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1026
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1020
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1022
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:445
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6039
@ Enum
The "enum" keyword.
Definition TypeBase.h:6053
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:556
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:374
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
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:1259
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
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:6014
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6028
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6032
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:1623
#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:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:625
Extra information about a function prototype.
Definition TypeBase.h:5501
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3520
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3537
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3502
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:12172
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12168
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12161
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12158
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12158
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13283
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13387
A stack object to be created when performing template instantiation.
Definition Sema.h:13477
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13630
NamedDecl * Previous
Definition Sema.h:361
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:1053