clang 23.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
15#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/Template.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
146 return D;
147
148 return nullptr;
149}
150
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
242 if (isa<FunctionTemplateDecl>(FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
280 R.suppressDiagnostics();
281 } else {
282 if (!D) {
283 D = getAsTemplateNameDecl(*R.begin());
284 assert(D && "unambiguous result is not a template name");
285 }
286
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
300 Template);
301 }
302
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
307 R.suppressDiagnostics();
308 } else {
312 TemplateKind =
314 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
318 }
319 }
320
322 S->getTemplateParamParent() == nullptr)
323 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(Template);
328 return TemplateKind;
329}
330
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
345 R.suppressDiagnostics();
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
351 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
352 if (!TD || !getAsTypeTemplateDecl(TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
358 *Template = TemplateTy::make(Name);
359 }
360 return true;
361}
362
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
379 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(IILoc, diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(IILoc, "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
391 bool AllowTypoCorrection) {
392 if (ATK)
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
412 "Caller should have completed object type");
413
414 // Template names cannot appear inside an Objective-C class or object type
415 // or a vector type.
416 //
417 // FIXME: This is wrong. For example:
418 //
419 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
420 // Vec<int> vi;
421 // vi.Vec<int>::~Vec<int>();
422 //
423 // ... should be accepted but we will not treat 'Vec' as a template name
424 // here. The right thing to do would be to check if the name is a valid
425 // vector component name, and look up a template name if not. And similarly
426 // for lookups into Objective-C class and object types, where the same
427 // problem can arise.
428 if (ObjectType->isObjCObjectOrInterfaceType() ||
429 ObjectType->isVectorType()) {
430 Found.clear();
431 return false;
432 }
433 } else if (SS.isNotEmpty()) {
434 // This nested-name-specifier occurs after another nested-name-specifier,
435 // so long into the context associated with the prior nested-name-specifier.
436 LookupCtx = computeDeclContext(SS, EnteringContext);
437 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
438
439 // The declaration context must be complete.
440 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
441 return true;
442 }
443
444 bool ObjectTypeSearchedInScope = false;
445 bool AllowFunctionTemplatesInLookup = true;
446 if (LookupCtx) {
447 // Perform "qualified" name lookup into the declaration context we
448 // computed, which is either the type of the base of a member access
449 // expression or the declaration context associated with a prior
450 // nested-name-specifier.
451 LookupQualifiedName(Found, LookupCtx);
452
453 // FIXME: The C++ standard does not clearly specify what happens in the
454 // case where the object type is dependent, and implementations vary. In
455 // Clang, we treat a name after a . or -> as a template-name if lookup
456 // finds a non-dependent member or member of the current instantiation that
457 // is a type template, or finds no such members and lookup in the context
458 // of the postfix-expression finds a type template. In the latter case, the
459 // name is nonetheless dependent, and we may resolve it to a member of an
460 // unknown specialization when we come to instantiate the template.
461 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
462 }
463
464 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
465 // C++ [basic.lookup.classref]p1:
466 // In a class member access expression (5.2.5), if the . or -> token is
467 // immediately followed by an identifier followed by a <, the
468 // identifier must be looked up to determine whether the < is the
469 // beginning of a template argument list (14.2) or a less-than operator.
470 // The identifier is first looked up in the class of the object
471 // expression. If the identifier is not found, it is then looked up in
472 // the context of the entire postfix-expression and shall name a class
473 // template.
474 if (S)
475 LookupName(Found, S);
476
477 if (!ObjectType.isNull()) {
478 // FIXME: We should filter out all non-type templates here, particularly
479 // variable templates and concepts. But the exclusion of alias templates
480 // and template template parameters is a wording defect.
481 AllowFunctionTemplatesInLookup = false;
482 ObjectTypeSearchedInScope = true;
483 }
484
485 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
486 }
487
488 if (Found.isAmbiguous())
489 return false;
490
491 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
492 !RequiredTemplate.hasTemplateKeyword()) {
493 // C++2a [temp.names]p2:
494 // A name is also considered to refer to a template if it is an
495 // unqualified-id followed by a < and name lookup finds either one or more
496 // functions or finds nothing.
497 //
498 // To keep our behavior consistent, we apply the "finds nothing" part in
499 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
500 // successfully form a call to an undeclared template-id.
501 bool AllFunctions =
502 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
504 });
505 if (AllFunctions || (Found.empty() && !IsDependent)) {
506 // If lookup found any functions, or if this is a name that can only be
507 // used for a function, then strongly assume this is a function
508 // template-id.
509 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
512 Found.clear();
513 return false;
514 }
515 }
516
517 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
518 // If we did not find any names, and this is not a disambiguation, attempt
519 // to correct any typos.
520 DeclarationName Name = Found.getLookupName();
521 Found.clear();
522 QualifiedLookupValidatorCCC FilterCCC(!SS.isEmpty());
523 FilterCCC.WantTypeSpecifiers = false;
524 FilterCCC.WantExpressionKeywords = false;
525 FilterCCC.WantRemainingKeywords = false;
526 FilterCCC.WantCXXNamedCasts = true;
527 if (TypoCorrection Corrected = CorrectTypo(
528 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
529 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
530 if (auto *ND = Corrected.getFoundDecl())
531 Found.addDecl(ND);
533 if (Found.isAmbiguous()) {
534 Found.clear();
535 } else if (!Found.empty()) {
536 // Do not erase the typo-corrected result to avoid duplicated
537 // diagnostics.
538 AllowFunctionTemplatesInLookup = true;
539 Found.setLookupName(Corrected.getCorrection());
540 if (LookupCtx) {
541 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
542 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543 Name.getAsString() == CorrectedStr;
544 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
545 << Name << LookupCtx << DroppedSpecifier
546 << SS.getRange());
547 } else {
548 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
549 }
550 }
551 }
552 }
553
554 NamedDecl *ExampleLookupResult =
555 Found.empty() ? nullptr : Found.getRepresentativeDecl();
556 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
557 if (Found.empty()) {
558 if (IsDependent) {
559 Found.setNotFoundInCurrentInstantiation();
560 return false;
561 }
562
563 // If a 'template' keyword was used, a lookup that finds only non-template
564 // names is an error.
565 if (ExampleLookupResult && RequiredTemplate) {
566 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
567 << Found.getLookupName() << SS.getRange()
568 << RequiredTemplate.hasTemplateKeyword()
569 << RequiredTemplate.getTemplateKeywordLoc();
570 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
571 diag::note_template_kw_refers_to_non_template)
572 << Found.getLookupName();
573 return true;
574 }
575
576 return false;
577 }
578
579 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
581 // C++03 [basic.lookup.classref]p1:
582 // [...] If the lookup in the class of the object expression finds a
583 // template, the name is also looked up in the context of the entire
584 // postfix-expression and [...]
585 //
586 // Note: C++11 does not perform this second lookup.
587 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
589 FoundOuter.setTemplateNameLookup(true);
590 LookupName(FoundOuter, S);
591 // FIXME: We silently accept an ambiguous lookup here, in violation of
592 // [basic.lookup]/1.
593 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
594
595 NamedDecl *OuterTemplate;
596 if (FoundOuter.empty()) {
597 // - if the name is not found, the name found in the class of the
598 // object expression is used, otherwise
599 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
600 !(OuterTemplate =
601 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
602 // - if the name is found in the context of the entire
603 // postfix-expression and does not name a class template, the name
604 // found in the class of the object expression is used, otherwise
605 FoundOuter.clear();
606 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
607 // - if the name found is a class template, it must refer to the same
608 // entity as the one found in the class of the object expression,
609 // otherwise the program is ill-formed.
610 if (!Found.isSingleResult() ||
611 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
612 OuterTemplate->getCanonicalDecl()) {
613 Diag(Found.getNameLoc(),
614 diag::ext_nested_name_member_ref_lookup_ambiguous)
615 << Found.getLookupName()
616 << ObjectType;
617 Diag(Found.getRepresentativeDecl()->getLocation(),
618 diag::note_ambig_member_ref_object_type)
619 << ObjectType;
620 Diag(FoundOuter.getFoundDecl()->getLocation(),
621 diag::note_ambig_member_ref_scope);
622
623 // Recover by taking the template that we found in the object
624 // expression's type.
625 }
626 }
627 }
628
629 return false;
630}
631
635 if (TemplateName.isInvalid())
636 return;
637
638 DeclarationNameInfo NameInfo;
639 CXXScopeSpec SS;
640 LookupNameKind LookupKind;
641
642 DeclContext *LookupCtx = nullptr;
643 NamedDecl *Found = nullptr;
644 bool MissingTemplateKeyword = false;
645
646 // Figure out what name we looked up.
647 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
648 NameInfo = DRE->getNameInfo();
649 SS.Adopt(DRE->getQualifierLoc());
650 LookupKind = LookupOrdinaryName;
651 Found = DRE->getFoundDecl();
652 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
653 NameInfo = ME->getMemberNameInfo();
654 SS.Adopt(ME->getQualifierLoc());
655 LookupKind = LookupMemberName;
656 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
657 Found = ME->getMemberDecl();
658 } else if (auto *DSDRE =
659 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
660 NameInfo = DSDRE->getNameInfo();
661 SS.Adopt(DSDRE->getQualifierLoc());
662 MissingTemplateKeyword = true;
663 } else if (auto *DSME =
664 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
665 NameInfo = DSME->getMemberNameInfo();
666 SS.Adopt(DSME->getQualifierLoc());
667 MissingTemplateKeyword = true;
668 } else {
669 llvm_unreachable("unexpected kind of potential template name");
670 }
671
672 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
673 // was missing.
674 if (MissingTemplateKeyword) {
675 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
676 << NameInfo.getName() << SourceRange(Less, Greater);
677 return;
678 }
679
680 // Try to correct the name by looking for templates and C++ named casts.
681 struct TemplateCandidateFilter : CorrectionCandidateCallback {
682 Sema &S;
683 TemplateCandidateFilter(Sema &S) : S(S) {
684 WantTypeSpecifiers = false;
685 WantExpressionKeywords = false;
686 WantRemainingKeywords = false;
687 WantCXXNamedCasts = true;
688 };
689 bool ValidateCandidate(const TypoCorrection &Candidate) override {
690 if (auto *ND = Candidate.getCorrectionDecl())
691 return S.getAsTemplateNameDecl(ND);
692 return Candidate.isKeyword();
693 }
694
695 std::unique_ptr<CorrectionCandidateCallback> clone() override {
696 return std::make_unique<TemplateCandidateFilter>(*this);
697 }
698 };
699
700 DeclarationName Name = NameInfo.getName();
701 TemplateCandidateFilter CCC(*this);
702 if (TypoCorrection Corrected =
703 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
704 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
705 auto *ND = Corrected.getFoundDecl();
706 if (ND)
707 ND = getAsTemplateNameDecl(ND);
708 if (ND || Corrected.isKeyword()) {
709 if (LookupCtx) {
710 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
711 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
712 Name.getAsString() == CorrectedStr;
713 diagnoseTypo(Corrected,
714 PDiag(diag::err_non_template_in_member_template_id_suggest)
715 << Name << LookupCtx << DroppedSpecifier
716 << SS.getRange(), false);
717 } else {
718 diagnoseTypo(Corrected,
719 PDiag(diag::err_non_template_in_template_id_suggest)
720 << Name, false);
721 }
722 if (Found)
723 Diag(Found->getLocation(),
724 diag::note_non_template_in_template_id_found);
725 return;
726 }
727 }
728
729 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
730 << Name << SourceRange(Less, Greater);
731 if (Found)
732 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
733}
734
737 SourceLocation TemplateKWLoc,
738 const DeclarationNameInfo &NameInfo,
739 bool isAddressOfOperand,
740 const TemplateArgumentListInfo *TemplateArgs) {
741 if (SS.isEmpty()) {
742 // FIXME: This codepath is only used by dependent unqualified names
743 // (e.g. a dependent conversion-function-id, or operator= once we support
744 // it). It doesn't quite do the right thing, and it will silently fail if
745 // getCurrentThisType() returns null.
746 QualType ThisType = getCurrentThisType();
747 if (ThisType.isNull())
748 return ExprError();
749
751 Context, /*Base=*/nullptr, ThisType,
752 /*IsArrow=*/!Context.getLangOpts().HLSL,
753 /*OperatorLoc=*/SourceLocation(),
754 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
755 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
756 }
757 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
758}
759
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 const TemplateArgumentListInfo *TemplateArgs) {
765 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
766 if (!SS.isValid())
767 return CreateRecoveryExpr(
768 SS.getBeginLoc(),
769 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
770
772 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
773 TemplateArgs);
774}
775
777 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
779 bool Final) {
780 // The template argument itself might be an expression, in which case we just
781 // return that expression. This happens when substituting into an alias
782 // template.
783 Expr *Replacement;
784 bool refParam = true;
786 Replacement = Arg.getAsExpr();
787 refParam = Replacement->isLValue();
788 if (refParam && Replacement->getType()->isRecordType()) {
789 QualType ParamType =
791 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)
792 : NTTP->getType();
793 if (const auto *PET = dyn_cast<PackExpansionType>(ParamType))
794 ParamType = PET->getPattern();
795 refParam = ParamType->isReferenceType();
796 }
797 } else {
798 ExprResult result =
799 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
800 if (result.isInvalid())
801 return ExprError();
802 Replacement = result.get();
804 }
805 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
806 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
807 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
808}
809
811 NamedDecl *Instantiation,
812 bool InstantiatedFromMember,
813 const NamedDecl *Pattern,
814 const NamedDecl *PatternDef,
816 bool Complain, bool *Unreachable) {
817 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
818 isa<VarDecl>(Instantiation));
819
820 bool IsEntityBeingDefined = false;
821 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
822 IsEntityBeingDefined = TD->isBeingDefined();
823
824 if (PatternDef && !IsEntityBeingDefined) {
825 NamedDecl *SuggestedDef = nullptr;
826 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
827 &SuggestedDef,
828 /*OnlyNeedComplete*/ false)) {
829 if (Unreachable)
830 *Unreachable = true;
831 // If we're allowed to diagnose this and recover, do so.
832 bool Recover = Complain && !isSFINAEContext();
833 if (Complain)
834 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
836 return !Recover;
837 }
838 return false;
839 }
840
841 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
842 return true;
843
844 CanQualType InstantiationTy;
845 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
846 InstantiationTy = Context.getCanonicalTagType(TD);
847 if (PatternDef) {
848 Diag(PointOfInstantiation,
849 diag::err_template_instantiate_within_definition)
850 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
851 << InstantiationTy;
852 // Not much point in noting the template declaration here, since
853 // we're lexically inside it.
854 Instantiation->setInvalidDecl();
855 } else if (InstantiatedFromMember) {
856 if (isa<FunctionDecl>(Instantiation)) {
857 Diag(PointOfInstantiation,
858 diag::err_explicit_instantiation_undefined_member)
859 << /*member function*/ 1 << Instantiation->getDeclName()
860 << Instantiation->getDeclContext();
861 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
862 } else {
863 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
864 Diag(PointOfInstantiation,
865 diag::err_implicit_instantiate_member_undefined)
866 << InstantiationTy;
867 Diag(Pattern->getLocation(), diag::note_member_declared_at);
868 }
869 } else {
870 if (isa<FunctionDecl>(Instantiation)) {
871 Diag(PointOfInstantiation,
872 diag::err_explicit_instantiation_undefined_func_template)
873 << Pattern;
874 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
875 } else if (isa<TagDecl>(Instantiation)) {
876 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
877 << (TSK != TSK_ImplicitInstantiation)
878 << InstantiationTy;
879 NoteTemplateLocation(*Pattern);
880 } else {
881 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
882 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
883 Diag(PointOfInstantiation,
884 diag::err_explicit_instantiation_undefined_var_template)
885 << Instantiation;
886 Instantiation->setInvalidDecl();
887 } else
888 Diag(PointOfInstantiation,
889 diag::err_explicit_instantiation_undefined_member)
890 << /*static data member*/ 2 << Instantiation->getDeclName()
891 << Instantiation->getDeclContext();
892 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
893 }
894 }
895
896 // In general, Instantiation isn't marked invalid to get more than one
897 // error for multiple undefined instantiations. But the code that does
898 // explicit declaration -> explicit definition conversion can't handle
899 // invalid declarations, so mark as invalid in that case.
901 Instantiation->setInvalidDecl();
902 return true;
903}
904
906 bool SupportedForCompatibility) {
907 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
908
909 // C++23 [temp.local]p6:
910 // The name of a template-parameter shall not be bound to any following.
911 // declaration whose locus is contained by the scope to which the
912 // template-parameter belongs.
913 //
914 // When MSVC compatibility is enabled, the diagnostic is always a warning
915 // by default. Otherwise, it an error unless SupportedForCompatibility is
916 // true, in which case it is a default-to-error warning.
917 unsigned DiagId =
918 getLangOpts().MSVCCompat
919 ? diag::ext_template_param_shadow
920 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
921 : diag::err_template_param_shadow);
922 const auto *ND = cast<NamedDecl>(PrevDecl);
923 Diag(Loc, DiagId) << ND->getDeclName();
925}
926
928 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
929 D = Temp->getTemplatedDecl();
930 return Temp;
931 }
932 return nullptr;
933}
934
936 SourceLocation EllipsisLoc) const {
937 assert(Kind == Template &&
938 "Only template template arguments can be pack expansions here");
939 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
940 "Template template argument pack expansion without packs");
942 Result.EllipsisLoc = EllipsisLoc;
943 return Result;
944}
945
947 const ParsedTemplateArgument &Arg) {
948
949 switch (Arg.getKind()) {
951 TypeSourceInfo *TSI;
952 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
953 if (!TSI)
954 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
956 }
957
959 Expr *E = Arg.getAsExpr();
960 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
961 }
962
965 TemplateArgument TArg;
966 if (Arg.getEllipsisLoc().isValid())
967 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
968 else
969 TArg = Template;
970 return TemplateArgumentLoc(
971 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
973 Arg.getNameLoc(), Arg.getEllipsisLoc());
974 }
975 }
976
977 llvm_unreachable("Unhandled parsed template argument");
978}
979
981 TemplateArgumentListInfo &TemplateArgs) {
982 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
983 TemplateArgs.addArgument(translateTemplateArgument(*this,
984 TemplateArgsIn[I]));
985}
986
988 SourceLocation Loc,
989 const IdentifierInfo *Name) {
990 NamedDecl *PrevDecl =
991 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
993 if (PrevDecl && PrevDecl->isTemplateParameter())
994 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
995}
996
998 TypeSourceInfo *TInfo;
999 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1000 if (T.isNull())
1001 return ParsedTemplateArgument();
1002 assert(TInfo && "template argument with no location");
1003
1004 // If we might have formed a deduced template specialization type, convert
1005 // it to a template template argument.
1006 if (getLangOpts().CPlusPlus17) {
1007 TypeLoc TL = TInfo->getTypeLoc();
1008 SourceLocation EllipsisLoc;
1009 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1010 EllipsisLoc = PET.getEllipsisLoc();
1011 TL = PET.getPatternLoc();
1012 }
1013
1014 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1015 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1016 CXXScopeSpec SS;
1017 SS.Adopt(DTST.getQualifierLoc());
1018 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1019 TemplateTy::make(Name),
1020 DTST.getTemplateNameLoc());
1021 if (EllipsisLoc.isValid())
1022 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1023 return Result;
1024 }
1025 }
1026
1027 // This is a normal type template argument. Note, if the type template
1028 // argument is an injected-class-name for a template, it has a dual nature
1029 // and can be used as either a type or a template. We handle that in
1030 // convertTypeTemplateArgumentToTemplate.
1032 ParsedType.get().getAsOpaquePtr(),
1033 TInfo->getTypeLoc().getBeginLoc());
1034}
1035
1037 SourceLocation EllipsisLoc,
1038 SourceLocation KeyLoc,
1039 IdentifierInfo *ParamName,
1040 SourceLocation ParamNameLoc,
1041 unsigned Depth, unsigned Position,
1042 SourceLocation EqualLoc,
1043 ParsedType DefaultArg,
1044 bool HasTypeConstraint) {
1045 assert(S->isTemplateParamScope() &&
1046 "Template type parameter not in template parameter scope!");
1047
1048 bool IsParameterPack = EllipsisLoc.isValid();
1050 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1051 KeyLoc, ParamNameLoc, Depth, Position,
1052 ParamName, Typename, IsParameterPack,
1053 HasTypeConstraint);
1054 Param->setAccess(AS_public);
1055
1056 if (Param->isParameterPack())
1057 if (auto *CSI = getEnclosingLambdaOrBlock())
1058 CSI->LocalPacks.push_back(Param);
1059
1060 if (ParamName) {
1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062
1063 // Add the template parameter into the current scope.
1064 S->AddDecl(Param);
1065 IdResolver.AddDecl(Param);
1066 }
1067
1068 // C++0x [temp.param]p9:
1069 // A default template-argument may be specified for any kind of
1070 // template-parameter that is not a template parameter pack.
1071 if (DefaultArg && IsParameterPack) {
1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073 DefaultArg = nullptr;
1074 }
1075
1076 // Handle the default argument, if provided.
1077 if (DefaultArg) {
1078 TypeSourceInfo *DefaultTInfo;
1079 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080
1081 assert(DefaultTInfo && "expected source information for type");
1082
1083 // Check for unexpanded parameter packs.
1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1086 return Param;
1087
1088 // Check the template argument itself.
1089 if (CheckTemplateArgument(DefaultTInfo)) {
1090 Param->setInvalidDecl();
1091 return Param;
1092 }
1093
1094 Param->setDefaultArgument(
1095 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1096 }
1097
1098 return Param;
1099}
1100
1101/// Convert the parser's template argument list representation into our form.
1104 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1105 TemplateId.RAngleLoc);
1106 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1107 TemplateId.NumArgs);
1108 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1109 return TemplateArgs;
1110}
1111
1113
1114 TemplateName TN = TypeConstr->Template.get();
1115 NamedDecl *CD = nullptr;
1116 bool IsTypeConcept = false;
1117 bool RequiresArguments = false;
1118 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1119 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1120 RequiresArguments =
1121 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1122 CD = TTP;
1123 } else {
1124 CD = TN.getAsTemplateDecl();
1125 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1126 RequiresArguments = cast<ConceptDecl>(CD)
1127 ->getTemplateParameters()
1128 ->getMinRequiredArguments() > 1;
1129 }
1130
1131 // C++2a [temp.param]p4:
1132 // [...] The concept designated by a type-constraint shall be a type
1133 // concept ([temp.concept]).
1134 if (!IsTypeConcept) {
1135 Diag(TypeConstr->TemplateNameLoc,
1136 diag::err_type_constraint_non_type_concept);
1137 return true;
1138 }
1139
1140 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1141 return true;
1142
1143 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1144
1145 if (!WereArgsSpecified && RequiresArguments) {
1146 Diag(TypeConstr->TemplateNameLoc,
1147 diag::err_type_constraint_missing_arguments)
1148 << CD;
1149 return true;
1150 }
1151 return false;
1152}
1153
1155 TemplateIdAnnotation *TypeConstr,
1156 TemplateTypeParmDecl *ConstrainedParameter,
1157 SourceLocation EllipsisLoc) {
1158 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1159 false);
1160}
1161
1163 TemplateIdAnnotation *TypeConstr,
1164 TemplateTypeParmDecl *ConstrainedParameter,
1165 SourceLocation EllipsisLoc,
1166 bool AllowUnexpandedPack) {
1167
1168 if (CheckTypeConstraint(TypeConstr))
1169 return true;
1170
1171 TemplateName TN = TypeConstr->Template.get();
1174
1175 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1176 TypeConstr->TemplateNameLoc);
1177
1178 TemplateArgumentListInfo TemplateArgs;
1179 if (TypeConstr->LAngleLoc.isValid()) {
1180 TemplateArgs =
1181 makeTemplateArgumentListInfo(*this, *TypeConstr);
1182
1183 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1184 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1186 return true;
1187 }
1188 }
1189 }
1190 return AttachTypeConstraint(
1192 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1193 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1194 ConstrainedParameter, EllipsisLoc);
1195}
1196
1197template <typename ArgumentLocAppender>
1200 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1201 SourceLocation RAngleLoc, QualType ConstrainedType,
1202 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1203 SourceLocation EllipsisLoc) {
1204
1205 TemplateArgumentListInfo ConstraintArgs;
1206 ConstraintArgs.addArgument(
1208 /*NTTPType=*/QualType(), ParamNameLoc));
1209
1210 ConstraintArgs.setRAngleLoc(RAngleLoc);
1211 ConstraintArgs.setLAngleLoc(LAngleLoc);
1212 Appender(ConstraintArgs);
1213
1214 // C++2a [temp.param]p4:
1215 // [...] This constraint-expression E is called the immediately-declared
1216 // constraint of T. [...]
1217 CXXScopeSpec SS;
1218 SS.Adopt(NS);
1219 ExprResult ImmediatelyDeclaredConstraint;
1220 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1221 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1222 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1223 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1224 /*DoCheckConstraintSatisfaction=*/
1226 }
1227 // We have a template template parameter
1228 else {
1229 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1230 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1231 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1232 }
1233 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1234 return ImmediatelyDeclaredConstraint;
1235
1236 // C++2a [temp.param]p4:
1237 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1238 //
1239 // We have the following case:
1240 //
1241 // template<typename T> concept C1 = true;
1242 // template<C1... T> struct s1;
1243 //
1244 // The constraint: (C1<T> && ...)
1245 //
1246 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1247 // any unqualified lookups for 'operator&&' here.
1248 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1249 /*LParenLoc=*/SourceLocation(),
1250 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1251 EllipsisLoc, /*RHS=*/nullptr,
1252 /*RParenLoc=*/SourceLocation(),
1253 /*NumExpansions=*/std::nullopt);
1254}
1255
1257 DeclarationNameInfo NameInfo,
1258 TemplateDecl *NamedConcept,
1259 NamedDecl *FoundDecl,
1260 const TemplateArgumentListInfo *TemplateArgs,
1261 TemplateTypeParmDecl *ConstrainedParameter,
1262 SourceLocation EllipsisLoc) {
1263 // C++2a [temp.param]p4:
1264 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1265 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1266 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1268 *TemplateArgs) : nullptr;
1269
1270 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1271
1272 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1273 *this, NS, NameInfo, NamedConcept, FoundDecl,
1274 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1275 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1276 ParamAsArgument, ConstrainedParameter->getLocation(),
1277 [&](TemplateArgumentListInfo &ConstraintArgs) {
1278 if (TemplateArgs)
1279 for (const auto &ArgLoc : TemplateArgs->arguments())
1280 ConstraintArgs.addArgument(ArgLoc);
1281 },
1282 EllipsisLoc);
1283 if (ImmediatelyDeclaredConstraint.isInvalid())
1284 return true;
1285
1286 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1287 /*TemplateKWLoc=*/SourceLocation{},
1288 /*ConceptNameInfo=*/NameInfo,
1289 /*FoundDecl=*/FoundDecl,
1290 /*NamedConcept=*/NamedConcept,
1291 /*ArgsWritten=*/ArgsAsWritten);
1292 ConstrainedParameter->setTypeConstraint(
1293 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1294 return false;
1295}
1296
1298 NonTypeTemplateParmDecl *NewConstrainedParm,
1299 NonTypeTemplateParmDecl *OrigConstrainedParm,
1300 SourceLocation EllipsisLoc) {
1301 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1303 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1304 diag::err_unsupported_placeholder_constraint)
1305 << NewConstrainedParm->getTypeSourceInfo()
1306 ->getTypeLoc()
1307 .getSourceRange();
1308 return true;
1309 }
1310 // FIXME: Concepts: This should be the type of the placeholder, but this is
1311 // unclear in the wording right now.
1312 DeclRefExpr *Ref =
1313 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1314 VK_PRValue, OrigConstrainedParm->getLocation());
1315 if (!Ref)
1316 return true;
1317 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1319 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1321 OrigConstrainedParm->getLocation(),
1322 [&](TemplateArgumentListInfo &ConstraintArgs) {
1323 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1324 ConstraintArgs.addArgument(TL.getArgLoc(I));
1325 },
1326 EllipsisLoc);
1327 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1328 !ImmediatelyDeclaredConstraint.isUsable())
1329 return true;
1330
1331 NewConstrainedParm->setPlaceholderTypeConstraint(
1332 ImmediatelyDeclaredConstraint.get());
1333 return false;
1334}
1335
1337 SourceLocation Loc) {
1338 if (TSI->getType()->isUndeducedType()) {
1339 // C++17 [temp.dep.expr]p3:
1340 // An id-expression is type-dependent if it contains
1341 // - an identifier associated by name lookup with a non-type
1342 // template-parameter declared with a type that contains a
1343 // placeholder type (7.1.7.4),
1345 if (!NewTSI)
1346 return QualType();
1347 TSI = NewTSI;
1348 }
1349
1350 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1351}
1352
1354 if (T->isDependentType())
1355 return false;
1356
1357 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1358 return true;
1359
1360 if (T->isStructuralType())
1361 return false;
1362
1363 // Structural types are required to be object types or lvalue references.
1364 if (T->isRValueReferenceType()) {
1365 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1366 return true;
1367 }
1368
1369 // Don't mention structural types in our diagnostic prior to C++20. Also,
1370 // there's not much more we can say about non-scalar non-class types --
1371 // because we can't see functions or arrays here, those can only be language
1372 // extensions.
1373 if (!getLangOpts().CPlusPlus20 ||
1374 (!T->isScalarType() && !T->isRecordType())) {
1375 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1376 return true;
1377 }
1378
1379 // Structural types are required to be literal types.
1380 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1381 return true;
1382
1383 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1384
1385 // Drill down into the reason why the class is non-structural.
1386 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1387 // All members are required to be public and non-mutable, and can't be of
1388 // rvalue reference type. Check these conditions first to prefer a "local"
1389 // reason over a more distant one.
1390 for (const FieldDecl *FD : RD->fields()) {
1391 if (FD->getAccess() != AS_public) {
1392 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1393 return true;
1394 }
1395 if (FD->isMutable()) {
1396 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1397 return true;
1398 }
1399 if (FD->getType()->isRValueReferenceType()) {
1400 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1401 << T;
1402 return true;
1403 }
1404 }
1405
1406 // All bases are required to be public.
1407 for (const auto &BaseSpec : RD->bases()) {
1408 if (BaseSpec.getAccessSpecifier() != AS_public) {
1409 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1410 << T << 1;
1411 return true;
1412 }
1413 }
1414
1415 // All subobjects are required to be of structural types.
1416 SourceLocation SubLoc;
1417 QualType SubType;
1418 int Kind = -1;
1419
1420 for (const FieldDecl *FD : RD->fields()) {
1421 QualType T = Context.getBaseElementType(FD->getType());
1422 if (!T->isStructuralType()) {
1423 SubLoc = FD->getLocation();
1424 SubType = T;
1425 Kind = 0;
1426 break;
1427 }
1428 }
1429
1430 if (Kind == -1) {
1431 for (const auto &BaseSpec : RD->bases()) {
1432 QualType T = BaseSpec.getType();
1433 if (!T->isStructuralType()) {
1434 SubLoc = BaseSpec.getBaseTypeLoc();
1435 SubType = T;
1436 Kind = 1;
1437 break;
1438 }
1439 }
1440 }
1441
1442 assert(Kind != -1 && "couldn't find reason why type is not structural");
1443 Diag(SubLoc, diag::note_not_structural_subobject)
1444 << T << Kind << SubType;
1445 T = SubType;
1446 RD = T->getAsCXXRecordDecl();
1447 }
1448
1449 return true;
1450}
1451
1453 SourceLocation Loc) {
1454 // We don't allow variably-modified types as the type of non-type template
1455 // parameters.
1456 if (T->isVariablyModifiedType()) {
1457 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1458 << T;
1459 return QualType();
1460 }
1461
1462 if (T->isBlockPointerType()) {
1463 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1464 return QualType();
1465 }
1466
1467 // C++ [temp.param]p4:
1468 //
1469 // A non-type template-parameter shall have one of the following
1470 // (optionally cv-qualified) types:
1471 //
1472 // -- integral or enumeration type,
1473 if (T->isIntegralOrEnumerationType() ||
1474 // -- pointer to object or pointer to function,
1475 T->isPointerType() ||
1476 // -- lvalue reference to object or lvalue reference to function,
1477 T->isLValueReferenceType() ||
1478 // -- pointer to member,
1479 T->isMemberPointerType() ||
1480 // -- std::nullptr_t, or
1481 T->isNullPtrType() ||
1482 // -- a type that contains a placeholder type.
1483 T->isUndeducedType()) {
1484 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1485 // are ignored when determining its type.
1486 return T.getUnqualifiedType();
1487 }
1488
1489 // C++ [temp.param]p8:
1490 //
1491 // A non-type template-parameter of type "array of T" or
1492 // "function returning T" is adjusted to be of type "pointer to
1493 // T" or "pointer to function returning T", respectively.
1494 if (T->isArrayType() || T->isFunctionType())
1495 return Context.getDecayedType(T);
1496
1497 // If T is a dependent type, we can't do the check now, so we
1498 // assume that it is well-formed. Note that stripping off the
1499 // qualifiers here is not really correct if T turns out to be
1500 // an array type, but we'll recompute the type everywhere it's
1501 // used during instantiation, so that should be OK. (Using the
1502 // qualified type is equally wrong.)
1503 if (T->isDependentType())
1504 return T.getUnqualifiedType();
1505
1506 // C++20 [temp.param]p6:
1507 // -- a structural type
1508 if (RequireStructuralType(T, Loc))
1509 return QualType();
1510
1511 if (!getLangOpts().CPlusPlus20) {
1512 // FIXME: Consider allowing structural types as an extension in C++17. (In
1513 // earlier language modes, the template argument evaluation rules are too
1514 // inflexible.)
1515 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1516 return QualType();
1517 }
1518
1519 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1520 return T.getUnqualifiedType();
1521}
1522
1524 unsigned Depth,
1525 unsigned Position,
1526 SourceLocation EqualLoc,
1527 Expr *Default) {
1529
1530 // Check that we have valid decl-specifiers specified.
1531 auto CheckValidDeclSpecifiers = [this, &D] {
1532 // C++ [temp.param]
1533 // p1
1534 // template-parameter:
1535 // ...
1536 // parameter-declaration
1537 // p2
1538 // ... A storage class shall not be specified in a template-parameter
1539 // declaration.
1540 // [dcl.typedef]p1:
1541 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1542 // of a parameter-declaration
1543 const DeclSpec &DS = D.getDeclSpec();
1544 auto EmitDiag = [this](SourceLocation Loc) {
1545 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1547 };
1549 EmitDiag(DS.getStorageClassSpecLoc());
1550
1552 EmitDiag(DS.getThreadStorageClassSpecLoc());
1553
1554 // [dcl.inline]p1:
1555 // The inline specifier can be applied only to the declaration or
1556 // definition of a variable or function.
1557
1558 if (DS.isInlineSpecified())
1559 EmitDiag(DS.getInlineSpecLoc());
1560
1561 // [dcl.constexpr]p1:
1562 // The constexpr specifier shall be applied only to the definition of a
1563 // variable or variable template or the declaration of a function or
1564 // function template.
1565
1566 if (DS.hasConstexprSpecifier())
1567 EmitDiag(DS.getConstexprSpecLoc());
1568
1569 // [dcl.fct.spec]p1:
1570 // Function-specifiers can be used only in function declarations.
1571
1572 if (DS.isVirtualSpecified())
1573 EmitDiag(DS.getVirtualSpecLoc());
1574
1575 if (DS.hasExplicitSpecifier())
1576 EmitDiag(DS.getExplicitSpecLoc());
1577
1578 if (DS.isNoreturnSpecified())
1579 EmitDiag(DS.getNoreturnSpecLoc());
1580 };
1581
1582 CheckValidDeclSpecifiers();
1583
1584 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1585 if (isa<AutoType>(T))
1587 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1588 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1589
1590 assert(S->isTemplateParamScope() &&
1591 "Non-type template parameter not in template parameter scope!");
1592 bool Invalid = false;
1593
1595 if (T.isNull()) {
1596 T = Context.IntTy; // Recover with an 'int' type.
1597 Invalid = true;
1598 }
1599
1601
1602 const IdentifierInfo *ParamName = D.getIdentifier();
1603 bool IsParameterPack = D.hasEllipsis();
1605 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1606 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1607 TInfo);
1608 Param->setAccess(AS_public);
1609
1611 if (TL.isConstrained()) {
1612 if (D.getEllipsisLoc().isInvalid() &&
1613 T->containsUnexpandedParameterPack()) {
1614 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1615 for (auto &Loc :
1616 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1619 }
1620 if (!Invalid &&
1621 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1622 Invalid = true;
1623 }
1624
1625 if (Invalid)
1626 Param->setInvalidDecl();
1627
1628 if (Param->isParameterPack())
1629 if (auto *CSI = getEnclosingLambdaOrBlock())
1630 CSI->LocalPacks.push_back(Param);
1631
1632 if (ParamName) {
1634 ParamName);
1635
1636 // Add the template parameter into the current scope.
1637 S->AddDecl(Param);
1638 IdResolver.AddDecl(Param);
1639 }
1640
1641 // C++0x [temp.param]p9:
1642 // A default template-argument may be specified for any kind of
1643 // template-parameter that is not a template parameter pack.
1644 if (Default && IsParameterPack) {
1645 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1646 Default = nullptr;
1647 }
1648
1649 // Check the well-formedness of the default template argument, if provided.
1650 if (Default) {
1651 // Check for unexpanded parameter packs.
1653 return Param;
1654
1655 Param->setDefaultArgument(
1657 TemplateArgument(Default, /*IsCanonical=*/false),
1658 QualType(), SourceLocation()));
1659 }
1660
1661 return Param;
1662}
1663
1664/// ActOnTemplateTemplateParameter - Called when a C++ template template
1665/// parameter (e.g. T in template <template <typename> class T> class array)
1666/// has been parsed. S is the current scope.
1668 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1669 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1670 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1671 unsigned Position, SourceLocation EqualLoc,
1673 assert(S->isTemplateParamScope() &&
1674 "Template template parameter not in template parameter scope!");
1675
1676 bool IsParameterPack = EllipsisLoc.isValid();
1677
1678 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1679 if (Params->size() == 0) {
1680 Diag(Loc, diag::err_template_template_parm_no_parms)
1681 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1682
1683 // Recover as if there was a type template parameter pack.
1684 SmallVector<NamedDecl *, 4> ParamDecls;
1685 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1686 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1687 Depth + 1, 0, /*Id=*/nullptr,
1688 /*Typename=*/false, /*ParameterPack=*/true));
1690 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1691 Params->getRAngleLoc(), Params->getRequiresClause());
1692 }
1693
1694 bool Invalid = false;
1696 Params,
1697 /*OldParams=*/nullptr,
1698 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1699 Invalid = true;
1700
1701 // Construct the parameter object.
1703 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1704 IsParameterPack, Name, Kind, Typename, Params);
1705 Param->setAccess(AS_public);
1706
1707 if (Param->isParameterPack())
1708 if (auto *LSI = getEnclosingLambdaOrBlock())
1709 LSI->LocalPacks.push_back(Param);
1710
1711 // If the template template parameter has a name, then link the identifier
1712 // into the scope and lookup mechanisms.
1713 if (Name) {
1714 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1715
1716 S->AddDecl(Param);
1717 IdResolver.AddDecl(Param);
1718 }
1719
1720 if (Invalid)
1721 Param->setInvalidDecl();
1722
1723 // C++0x [temp.param]p9:
1724 // A default template-argument may be specified for any kind of
1725 // template-parameter that is not a template parameter pack.
1726 if (IsParameterPack && !Default.isInvalid()) {
1727 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1729 }
1730
1731 if (!Default.isInvalid()) {
1732 // Check only that we have a template template argument. We don't want to
1733 // try to check well-formedness now, because our template template parameter
1734 // might have dependent types in its template parameters, which we wouldn't
1735 // be able to match now.
1736 //
1737 // If none of the template template parameter's template arguments mention
1738 // other template parameters, we could actually perform more checking here.
1739 // However, it isn't worth doing.
1741 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1742 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1743 << DefaultArg.getSourceRange();
1744 return Param;
1745 }
1746
1747 TemplateName Name =
1750 if (Template &&
1752 return Param;
1753 }
1754
1755 // Check for unexpanded parameter packs.
1757 DefaultArg.getArgument().getAsTemplate(),
1759 return Param;
1760
1761 Param->setDefaultArgument(Context, DefaultArg);
1762 }
1763
1764 return Param;
1765}
1766
1767namespace {
1768class ConstraintRefersToContainingTemplateChecker
1770 using inherited = ConstDynamicRecursiveASTVisitor;
1771 bool Result = false;
1772 const FunctionDecl *Friend = nullptr;
1773 unsigned TemplateDepth = 0;
1774
1775 // Check a record-decl that we've seen to see if it is a lexical parent of the
1776 // Friend, likely because it was referred to without its template arguments.
1777 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1778 CheckingRD = CheckingRD->getMostRecentDecl();
1779 if (!CheckingRD->isTemplated())
1780 return true;
1781
1782 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1783 DC && !DC->isFileContext(); DC = DC->getParent())
1784 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1785 if (CheckingRD == RD->getMostRecentDecl()) {
1786 Result = true;
1787 return false;
1788 }
1789
1790 return true;
1791 }
1792
1793 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1794 if (D->getDepth() < TemplateDepth)
1795 Result = true;
1796
1797 // Necessary because the type of the NTTP might be what refers to the parent
1798 // constriant.
1799 return TraverseType(D->getType());
1800 }
1801
1802public:
1803 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1804 unsigned TemplateDepth)
1805 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1806
1807 bool getResult() const { return Result; }
1808
1809 // This should be the only template parm type that we have to deal with.
1810 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1811 // FunctionParmPackExpr are all partially substituted, which cannot happen
1812 // with concepts at this point in translation.
1813 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1814 if (Type->getDecl()->getDepth() < TemplateDepth) {
1815 Result = true;
1816 return false;
1817 }
1818 return true;
1819 }
1820
1821 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1822 return TraverseDecl(E->getDecl());
1823 }
1824
1825 bool TraverseTypedefType(const TypedefType *TT,
1826 bool /*TraverseQualifier*/) override {
1827 return TraverseType(TT->desugar());
1828 }
1829
1830 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1831 // We don't care about TypeLocs. So traverse Types instead.
1832 return TraverseType(TL.getType(), TraverseQualifier);
1833 }
1834
1835 bool VisitTagType(const TagType *T) override {
1836 return TraverseDecl(T->getDecl());
1837 }
1838
1839 bool TraverseDecl(const Decl *D) override {
1840 assert(D);
1841 // FIXME : This is possibly an incomplete list, but it is unclear what other
1842 // Decl kinds could be used to refer to the template parameters. This is a
1843 // best guess so far based on examples currently available, but the
1844 // unreachable should catch future instances/cases.
1845 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1846 return TraverseType(TD->getUnderlyingType());
1847 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1848 return CheckNonTypeTemplateParmDecl(NTTPD);
1849 if (auto *VD = dyn_cast<ValueDecl>(D))
1850 return TraverseType(VD->getType());
1851 if (isa<TemplateDecl>(D))
1852 return true;
1853 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1854 return CheckIfContainingRecord(RD);
1855
1857 // No direct types to visit here I believe.
1858 } else
1859 llvm_unreachable("Don't know how to handle this declaration type yet");
1860 return true;
1861 }
1862};
1863} // namespace
1864
1866 const FunctionDecl *Friend, unsigned TemplateDepth,
1867 const Expr *Constraint) {
1868 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1869 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1870 Checker.TraverseStmt(Constraint);
1871 return Checker.getResult();
1872}
1873
1876 SourceLocation ExportLoc,
1877 SourceLocation TemplateLoc,
1878 SourceLocation LAngleLoc,
1879 ArrayRef<NamedDecl *> Params,
1880 SourceLocation RAngleLoc,
1881 Expr *RequiresClause) {
1882 if (ExportLoc.isValid())
1883 Diag(ExportLoc, diag::warn_template_export_unsupported);
1884
1885 for (NamedDecl *P : Params)
1887
1888 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1889 llvm::ArrayRef(Params), RAngleLoc,
1890 RequiresClause);
1891}
1892
1894 const CXXScopeSpec &SS) {
1895 if (SS.isSet())
1896 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1897}
1898
1899// Returns the template parameter list with all default template argument
1900// information.
1902 // Make sure we get the template parameter list from the most
1903 // recent declaration, since that is the only one that is guaranteed to
1904 // have all the default template argument information.
1905 Decl *D = TD->getMostRecentDecl();
1906 // C++11 N3337 [temp.param]p12:
1907 // A default template argument shall not be specified in a friend class
1908 // template declaration.
1909 //
1910 // Skip past friend *declarations* because they are not supposed to contain
1911 // default template arguments. Moreover, these declarations may introduce
1912 // template parameters living in different template depths than the
1913 // corresponding template parameters in TD, causing unmatched constraint
1914 // substitution.
1915 //
1916 // FIXME: Diagnose such cases within a class template:
1917 // template <class T>
1918 // struct S {
1919 // template <class = void> friend struct C;
1920 // };
1921 // template struct S<int>;
1923 D->getPreviousDecl())
1924 D = D->getPreviousDecl();
1925 return cast<TemplateDecl>(D)->getTemplateParameters();
1926}
1927
1929 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1930 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1931 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1932 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1933 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1934 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1935 assert(TemplateParams && TemplateParams->size() > 0 &&
1936 "No template parameters");
1937 assert(TUK != TagUseKind::Reference &&
1938 "Can only declare or define class templates");
1939 bool Invalid = false;
1940
1941 // Check that we can declare a template here.
1942 if (CheckTemplateDeclScope(S, TemplateParams))
1943 return true;
1944
1946 assert(Kind != TagTypeKind::Enum &&
1947 "can't build template of enumerated type");
1948
1949 // There is no such thing as an unnamed class template.
1950 if (!Name) {
1951 Diag(KWLoc, diag::err_template_unnamed_class);
1952 return true;
1953 }
1954
1955 // Find any previous declaration with this name. For a friend with no
1956 // scope explicitly specified, we only look for tag declarations (per
1957 // C++11 [basic.lookup.elab]p2).
1958 DeclContext *SemanticContext;
1959 LookupResult Previous(*this, Name, NameLoc,
1960 (SS.isEmpty() && TUK == TagUseKind::Friend)
1964 if (SS.isNotEmpty() && !SS.isInvalid()) {
1965 SemanticContext = computeDeclContext(SS, true);
1966 if (!SemanticContext) {
1967 // FIXME: Horrible, horrible hack! We can't currently represent this
1968 // in the AST, and historically we have just ignored such friend
1969 // class templates, so don't complain here.
1970 Diag(NameLoc, TUK == TagUseKind::Friend
1971 ? diag::warn_template_qualified_friend_ignored
1972 : diag::err_template_qualified_declarator_no_match)
1973 << SS.getScopeRep() << SS.getRange();
1974 return TUK != TagUseKind::Friend;
1975 }
1976
1977 if (RequireCompleteDeclContext(SS, SemanticContext))
1978 return true;
1979
1980 // If we're adding a template to a dependent context, we may need to
1981 // rebuilding some of the types used within the template parameter list,
1982 // now that we know what the current instantiation is.
1983 if (SemanticContext->isDependentContext()) {
1984 ContextRAII SavedContext(*this, SemanticContext);
1986 Invalid = true;
1987 }
1988
1989 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1990 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1991 /*TemplateId-*/ nullptr,
1992 /*IsMemberSpecialization*/ false);
1993
1994 LookupQualifiedName(Previous, SemanticContext);
1995 } else {
1996 SemanticContext = CurContext;
1997
1998 // C++14 [class.mem]p14:
1999 // If T is the name of a class, then each of the following shall have a
2000 // name different from T:
2001 // -- every member template of class T
2002 if (TUK != TagUseKind::Friend &&
2003 DiagnoseClassNameShadow(SemanticContext,
2004 DeclarationNameInfo(Name, NameLoc)))
2005 return true;
2006
2007 LookupName(Previous, S);
2008 }
2009
2010 if (Previous.isAmbiguous())
2011 return true;
2012
2013 // Let the template parameter scope enter the lookup chain of the current
2014 // class template. For example, given
2015 //
2016 // namespace ns {
2017 // template <class> bool Param = false;
2018 // template <class T> struct N;
2019 // }
2020 //
2021 // template <class Param> struct ns::N { void foo(Param); };
2022 //
2023 // When we reference Param inside the function parameter list, our name lookup
2024 // chain for it should be like:
2025 // FunctionScope foo
2026 // -> RecordScope N
2027 // -> TemplateParamScope (where we will find Param)
2028 // -> NamespaceScope ns
2029 //
2030 // See also CppLookupName().
2031 if (S->isTemplateParamScope())
2032 EnterTemplatedContext(S, SemanticContext);
2033
2034 NamedDecl *PrevDecl = nullptr;
2035 if (Previous.begin() != Previous.end())
2036 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2037
2038 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2039 // Maybe we will complain about the shadowed template parameter.
2040 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2041 // Just pretend that we didn't see the previous declaration.
2042 PrevDecl = nullptr;
2043 }
2044
2045 // If there is a previous declaration with the same name, check
2046 // whether this is a valid redeclaration.
2047 ClassTemplateDecl *PrevClassTemplate =
2048 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2049
2050 // We may have found the injected-class-name of a class template,
2051 // class template partial specialization, or class template specialization.
2052 // In these cases, grab the template that is being defined or specialized.
2053 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2054 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2055 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2056 PrevClassTemplate
2057 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2058 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2059 PrevClassTemplate
2061 ->getSpecializedTemplate();
2062 }
2063 }
2064
2065 if (TUK == TagUseKind::Friend) {
2066 // C++ [namespace.memdef]p3:
2067 // [...] When looking for a prior declaration of a class or a function
2068 // declared as a friend, and when the name of the friend class or
2069 // function is neither a qualified name nor a template-id, scopes outside
2070 // the innermost enclosing namespace scope are not considered.
2071 if (!SS.isSet()) {
2072 DeclContext *OutermostContext = CurContext;
2073 while (!OutermostContext->isFileContext())
2074 OutermostContext = OutermostContext->getLookupParent();
2075
2076 if (PrevDecl &&
2077 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2078 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2079 SemanticContext = PrevDecl->getDeclContext();
2080 } else {
2081 // Declarations in outer scopes don't matter. However, the outermost
2082 // context we computed is the semantic context for our new
2083 // declaration.
2084 PrevDecl = PrevClassTemplate = nullptr;
2085 SemanticContext = OutermostContext;
2086
2087 // Check that the chosen semantic context doesn't already contain a
2088 // declaration of this name as a non-tag type.
2090 DeclContext *LookupContext = SemanticContext;
2091 while (LookupContext->isTransparentContext())
2092 LookupContext = LookupContext->getLookupParent();
2093 LookupQualifiedName(Previous, LookupContext);
2094
2095 if (Previous.isAmbiguous())
2096 return true;
2097
2098 if (Previous.begin() != Previous.end())
2099 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2100 }
2101 }
2102 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2103 SemanticContext, S, SS.isValid()))
2104 PrevDecl = PrevClassTemplate = nullptr;
2105
2106 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2107 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2108 if (SS.isEmpty() &&
2109 !(PrevClassTemplate &&
2110 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2111 SemanticContext->getRedeclContext()))) {
2112 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2113 Diag(Shadow->getTargetDecl()->getLocation(),
2114 diag::note_using_decl_target);
2115 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2116 // Recover by ignoring the old declaration.
2117 PrevDecl = PrevClassTemplate = nullptr;
2118 }
2119 }
2120
2121 if (PrevClassTemplate) {
2122 // Ensure that the template parameter lists are compatible. Skip this check
2123 // for a friend in a dependent context: the template parameter list itself
2124 // could be dependent.
2125 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2127 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2128 : CurContext,
2129 CurContext, KWLoc),
2130 TemplateParams, PrevClassTemplate,
2131 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2133 return true;
2134
2135 // C++ [temp.class]p4:
2136 // In a redeclaration, partial specialization, explicit
2137 // specialization or explicit instantiation of a class template,
2138 // the class-key shall agree in kind with the original class
2139 // template declaration (7.1.5.3).
2140 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2142 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2143 Diag(KWLoc, diag::err_use_with_wrong_tag)
2144 << Name
2145 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2146 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2147 Kind = PrevRecordDecl->getTagKind();
2148 }
2149
2150 // Check for redefinition of this class template.
2151 if (TUK == TagUseKind::Definition) {
2152 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2153 // If we have a prior definition that is not visible, treat this as
2154 // simply making that previous definition visible.
2155 NamedDecl *Hidden = nullptr;
2156 bool HiddenDefVisible = false;
2157 if (SkipBody &&
2158 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2159 SkipBody->ShouldSkip = true;
2160 SkipBody->Previous = Def;
2161 if (!HiddenDefVisible && Hidden) {
2162 auto *Tmpl =
2163 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2164 assert(Tmpl && "original definition of a class template is not a "
2165 "class template?");
2168 }
2169 } else {
2170 Diag(NameLoc, diag::err_redefinition) << Name;
2171 Diag(Def->getLocation(), diag::note_previous_definition);
2172 // FIXME: Would it make sense to try to "forget" the previous
2173 // definition, as part of error recovery?
2174 return true;
2175 }
2176 }
2177 }
2178 } else if (PrevDecl) {
2179 // C++ [temp]p5:
2180 // A class template shall not have the same name as any other
2181 // template, class, function, object, enumeration, enumerator,
2182 // namespace, or type in the same scope (3.3), except as specified
2183 // in (14.5.4).
2184 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2185 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2186 return true;
2187 }
2188
2189 // Check the template parameter list of this declaration, possibly
2190 // merging in the template parameter list from the previous class
2191 // template declaration. Skip this check for a friend in a dependent
2192 // context, because the template parameter list might be dependent.
2193 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2195 TemplateParams,
2196 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2197 : nullptr,
2198 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2199 SemanticContext->isDependentContext())
2202 : TPC_Other,
2203 SkipBody))
2204 Invalid = true;
2205
2206 if (SS.isSet()) {
2207 // If the name of the template was qualified, we must be defining the
2208 // template out-of-line.
2209 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2210 Diag(NameLoc, TUK == TagUseKind::Friend
2211 ? diag::err_friend_decl_does_not_match
2212 : diag::err_member_decl_does_not_match)
2213 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2214 Invalid = true;
2215 }
2216 }
2217
2218 // If this is a templated friend in a dependent context we should not put it
2219 // on the redecl chain. In some cases, the templated friend can be the most
2220 // recent declaration tricking the template instantiator to make substitutions
2221 // there.
2222 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2223 bool ShouldAddRedecl =
2224 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2225
2227 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2228 PrevClassTemplate && ShouldAddRedecl
2229 ? PrevClassTemplate->getTemplatedDecl()
2230 : nullptr);
2231 SetNestedNameSpecifier(*this, NewClass, SS);
2232 if (NumOuterTemplateParamLists > 0)
2234 Context,
2235 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2236
2237 // Add alignment attributes if necessary; these attributes are checked when
2238 // the ASTContext lays out the structure.
2239 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2240 if (LangOpts.HLSL)
2241 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2244 }
2245
2246 ClassTemplateDecl *NewTemplate
2247 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2248 DeclarationName(Name), TemplateParams,
2249 NewClass);
2250
2251 if (ShouldAddRedecl)
2252 NewTemplate->setPreviousDecl(PrevClassTemplate);
2253
2254 NewClass->setDescribedClassTemplate(NewTemplate);
2255
2256 if (ModulePrivateLoc.isValid())
2257 NewTemplate->setModulePrivate();
2258
2259 // If we are providing an explicit specialization of a member that is a
2260 // class template, make a note of that.
2261 if (PrevClassTemplate &&
2262 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2263 PrevClassTemplate->setMemberSpecialization();
2264
2265 // Set the access specifier.
2266 if (!Invalid && TUK != TagUseKind::Friend &&
2267 NewTemplate->getDeclContext()->isRecord())
2268 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2269
2270 // Set the lexical context of these templates
2272 NewTemplate->setLexicalDeclContext(CurContext);
2273
2274 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2275 NewClass->startDefinition();
2276
2277 ProcessDeclAttributeList(S, NewClass, Attr);
2278
2279 if (PrevClassTemplate)
2280 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2281
2285
2286 if (TUK != TagUseKind::Friend) {
2287 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2288 Scope *Outer = S;
2289 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2290 Outer = Outer->getParent();
2291 PushOnScopeChains(NewTemplate, Outer);
2292 } else {
2293 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2294 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2295 NewClass->setAccess(PrevClassTemplate->getAccess());
2296 }
2297
2298 NewTemplate->setObjectOfFriendDecl();
2299
2300 // Friend templates are visible in fairly strange ways.
2301 if (!CurContext->isDependentContext()) {
2302 DeclContext *DC = SemanticContext->getRedeclContext();
2303 DC->makeDeclVisibleInContext(NewTemplate);
2304 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2305 PushOnScopeChains(NewTemplate, EnclosingScope,
2306 /* AddToContext = */ false);
2307 }
2308
2310 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2311 Friend->setAccess(AS_public);
2312 CurContext->addDecl(Friend);
2313 }
2314
2315 if (PrevClassTemplate)
2316 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2317
2318 if (Invalid) {
2319 NewTemplate->setInvalidDecl();
2320 NewClass->setInvalidDecl();
2321 }
2322
2323 ActOnDocumentableDecl(NewTemplate);
2324
2325 if (SkipBody && SkipBody->ShouldSkip)
2326 return SkipBody->Previous;
2327
2328 return NewTemplate;
2329}
2330
2331/// Diagnose the presence of a default template argument on a
2332/// template parameter, which is ill-formed in certain contexts.
2333///
2334/// \returns true if the default template argument should be dropped.
2337 SourceLocation ParamLoc,
2338 SourceRange DefArgRange) {
2339 switch (TPC) {
2340 case Sema::TPC_Other:
2342 return false;
2343
2346 // C++ [temp.param]p9:
2347 // A default template-argument shall not be specified in a
2348 // function template declaration or a function template
2349 // definition [...]
2350 // If a friend function template declaration specifies a default
2351 // template-argument, that declaration shall be a definition and shall be
2352 // the only declaration of the function template in the translation unit.
2353 // (C++98/03 doesn't have this wording; see DR226).
2354 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2355 << DefArgRange;
2356 return false;
2357
2359 // C++0x [temp.param]p9:
2360 // A default template-argument shall not be specified in the
2361 // template-parameter-lists of the definition of a member of a
2362 // class template that appears outside of the member's class.
2363 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2364 << DefArgRange;
2365 return true;
2366
2369 // C++ [temp.param]p9:
2370 // A default template-argument shall not be specified in a
2371 // friend template declaration.
2372 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2373 << DefArgRange;
2374 return true;
2375
2376 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2377 // for friend function templates if there is only a single
2378 // declaration (and it is a definition). Strange!
2379 }
2380
2381 llvm_unreachable("Invalid TemplateParamListContext!");
2382}
2383
2384/// Check for unexpanded parameter packs within the template parameters
2385/// of a template template parameter, recursively.
2388 // A template template parameter which is a parameter pack is also a pack
2389 // expansion.
2390 if (TTP->isParameterPack())
2391 return false;
2392
2394 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2395 NamedDecl *P = Params->getParam(I);
2396 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2397 if (!TTP->isParameterPack())
2398 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2399 if (TC->hasExplicitTemplateArgs())
2400 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2403 return true;
2404 continue;
2405 }
2406
2407 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2408 if (!NTTP->isParameterPack() &&
2409 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2410 NTTP->getTypeSourceInfo(),
2412 return true;
2413
2414 continue;
2415 }
2416
2417 if (TemplateTemplateParmDecl *InnerTTP
2418 = dyn_cast<TemplateTemplateParmDecl>(P))
2419 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2420 return true;
2421 }
2422
2423 return false;
2424}
2425
2427 TemplateParameterList *OldParams,
2429 SkipBodyInfo *SkipBody) {
2430 bool Invalid = false;
2431
2432 // C++ [temp.param]p10:
2433 // The set of default template-arguments available for use with a
2434 // template declaration or definition is obtained by merging the
2435 // default arguments from the definition (if in scope) and all
2436 // declarations in scope in the same way default function
2437 // arguments are (8.3.6).
2438 bool SawDefaultArgument = false;
2439 SourceLocation PreviousDefaultArgLoc;
2440
2441 // Dummy initialization to avoid warnings.
2442 TemplateParameterList::iterator OldParam = NewParams->end();
2443 if (OldParams)
2444 OldParam = OldParams->begin();
2445
2446 bool RemoveDefaultArguments = false;
2447 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2448 NewParamEnd = NewParams->end();
2449 NewParam != NewParamEnd; ++NewParam) {
2450 // Whether we've seen a duplicate default argument in the same translation
2451 // unit.
2452 bool RedundantDefaultArg = false;
2453 // Whether we've found inconsis inconsitent default arguments in different
2454 // translation unit.
2455 bool InconsistentDefaultArg = false;
2456 // The name of the module which contains the inconsistent default argument.
2457 std::string PrevModuleName;
2458
2459 SourceLocation OldDefaultLoc;
2460 SourceLocation NewDefaultLoc;
2461
2462 // Variable used to diagnose missing default arguments
2463 bool MissingDefaultArg = false;
2464
2465 // Variable used to diagnose non-final parameter packs
2466 bool SawParameterPack = false;
2467
2468 if (TemplateTypeParmDecl *NewTypeParm
2469 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2470 // Check the presence of a default argument here.
2471 if (NewTypeParm->hasDefaultArgument() &&
2473 *this, TPC, NewTypeParm->getLocation(),
2474 NewTypeParm->getDefaultArgument().getSourceRange()))
2475 NewTypeParm->removeDefaultArgument();
2476
2477 // Merge default arguments for template type parameters.
2478 TemplateTypeParmDecl *OldTypeParm
2479 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2480 if (NewTypeParm->isParameterPack()) {
2481 assert(!NewTypeParm->hasDefaultArgument() &&
2482 "Parameter packs can't have a default argument!");
2483 SawParameterPack = true;
2484 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2485 NewTypeParm->hasDefaultArgument() &&
2486 (!SkipBody || !SkipBody->ShouldSkip)) {
2487 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2488 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2489 SawDefaultArgument = true;
2490
2491 if (!OldTypeParm->getOwningModule())
2492 RedundantDefaultArg = true;
2493 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2494 NewTypeParm)) {
2495 InconsistentDefaultArg = true;
2496 PrevModuleName =
2498 }
2499 PreviousDefaultArgLoc = NewDefaultLoc;
2500 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2501 // Merge the default argument from the old declaration to the
2502 // new declaration.
2503 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2504 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2505 } else if (NewTypeParm->hasDefaultArgument()) {
2506 SawDefaultArgument = true;
2507 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2508 } else if (SawDefaultArgument)
2509 MissingDefaultArg = true;
2510 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2511 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2512 // Check for unexpanded parameter packs, except in a template template
2513 // parameter pack, as in those any unexpanded packs should be expanded
2514 // along with the parameter itself.
2516 !NewNonTypeParm->isParameterPack() &&
2517 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2518 NewNonTypeParm->getTypeSourceInfo(),
2520 Invalid = true;
2521 continue;
2522 }
2523
2524 // Check the presence of a default argument here.
2525 if (NewNonTypeParm->hasDefaultArgument() &&
2527 *this, TPC, NewNonTypeParm->getLocation(),
2528 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2529 NewNonTypeParm->removeDefaultArgument();
2530 }
2531
2532 // Merge default arguments for non-type template parameters
2533 NonTypeTemplateParmDecl *OldNonTypeParm
2534 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2535 if (NewNonTypeParm->isParameterPack()) {
2536 assert(!NewNonTypeParm->hasDefaultArgument() &&
2537 "Parameter packs can't have a default argument!");
2538 if (!NewNonTypeParm->isPackExpansion())
2539 SawParameterPack = true;
2540 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2541 NewNonTypeParm->hasDefaultArgument() &&
2542 (!SkipBody || !SkipBody->ShouldSkip)) {
2543 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2544 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2545 SawDefaultArgument = true;
2546 if (!OldNonTypeParm->getOwningModule())
2547 RedundantDefaultArg = true;
2548 else if (!getASTContext().isSameDefaultTemplateArgument(
2549 OldNonTypeParm, NewNonTypeParm)) {
2550 InconsistentDefaultArg = true;
2551 PrevModuleName =
2552 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2553 }
2554 PreviousDefaultArgLoc = NewDefaultLoc;
2555 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2556 // Merge the default argument from the old declaration to the
2557 // new declaration.
2558 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2559 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2560 } else if (NewNonTypeParm->hasDefaultArgument()) {
2561 SawDefaultArgument = true;
2562 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2563 } else if (SawDefaultArgument)
2564 MissingDefaultArg = true;
2565 } else {
2566 TemplateTemplateParmDecl *NewTemplateParm
2567 = cast<TemplateTemplateParmDecl>(*NewParam);
2568
2569 // Check for unexpanded parameter packs, recursively.
2570 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2571 Invalid = true;
2572 continue;
2573 }
2574
2575 // Check the presence of a default argument here.
2576 if (NewTemplateParm->hasDefaultArgument() &&
2578 NewTemplateParm->getLocation(),
2579 NewTemplateParm->getDefaultArgument().getSourceRange()))
2580 NewTemplateParm->removeDefaultArgument();
2581
2582 // Merge default arguments for template template parameters
2583 TemplateTemplateParmDecl *OldTemplateParm
2584 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2585 if (NewTemplateParm->isParameterPack()) {
2586 assert(!NewTemplateParm->hasDefaultArgument() &&
2587 "Parameter packs can't have a default argument!");
2588 if (!NewTemplateParm->isPackExpansion())
2589 SawParameterPack = true;
2590 } else if (OldTemplateParm &&
2591 hasVisibleDefaultArgument(OldTemplateParm) &&
2592 NewTemplateParm->hasDefaultArgument() &&
2593 (!SkipBody || !SkipBody->ShouldSkip)) {
2594 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2595 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2596 SawDefaultArgument = true;
2597 if (!OldTemplateParm->getOwningModule())
2598 RedundantDefaultArg = true;
2599 else if (!getASTContext().isSameDefaultTemplateArgument(
2600 OldTemplateParm, NewTemplateParm)) {
2601 InconsistentDefaultArg = true;
2602 PrevModuleName =
2603 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2604 }
2605 PreviousDefaultArgLoc = NewDefaultLoc;
2606 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2607 // Merge the default argument from the old declaration to the
2608 // new declaration.
2609 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2610 PreviousDefaultArgLoc
2611 = OldTemplateParm->getDefaultArgument().getLocation();
2612 } else if (NewTemplateParm->hasDefaultArgument()) {
2613 SawDefaultArgument = true;
2614 PreviousDefaultArgLoc
2615 = NewTemplateParm->getDefaultArgument().getLocation();
2616 } else if (SawDefaultArgument)
2617 MissingDefaultArg = true;
2618 }
2619
2620 // C++11 [temp.param]p11:
2621 // If a template parameter of a primary class template or alias template
2622 // is a template parameter pack, it shall be the last template parameter.
2623 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2624 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2625 Diag((*NewParam)->getLocation(),
2626 diag::err_template_param_pack_must_be_last_template_parameter);
2627 Invalid = true;
2628 }
2629
2630 // [basic.def.odr]/13:
2631 // There can be more than one definition of a
2632 // ...
2633 // default template argument
2634 // ...
2635 // in a program provided that each definition appears in a different
2636 // translation unit and the definitions satisfy the [same-meaning
2637 // criteria of the ODR].
2638 //
2639 // Simply, the design of modules allows the definition of template default
2640 // argument to be repeated across translation unit. Note that the ODR is
2641 // checked elsewhere. But it is still not allowed to repeat template default
2642 // argument in the same translation unit.
2643 if (RedundantDefaultArg) {
2644 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2645 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2646 Invalid = true;
2647 } else if (InconsistentDefaultArg) {
2648 // We could only diagnose about the case that the OldParam is imported.
2649 // The case NewParam is imported should be handled in ASTReader.
2650 Diag(NewDefaultLoc,
2651 diag::err_template_param_default_arg_inconsistent_redefinition);
2652 Diag(OldDefaultLoc,
2653 diag::note_template_param_prev_default_arg_in_other_module)
2654 << PrevModuleName;
2655 Invalid = true;
2656 } else if (MissingDefaultArg &&
2657 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2658 TPC == TPC_FriendClassTemplate)) {
2659 // C++ 23[temp.param]p14:
2660 // If a template-parameter of a class template, variable template, or
2661 // alias template has a default template argument, each subsequent
2662 // template-parameter shall either have a default template argument
2663 // supplied or be a template parameter pack.
2664 Diag((*NewParam)->getLocation(),
2665 diag::err_template_param_default_arg_missing);
2666 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2667 Invalid = true;
2668 RemoveDefaultArguments = true;
2669 }
2670
2671 // If we have an old template parameter list that we're merging
2672 // in, move on to the next parameter.
2673 if (OldParams)
2674 ++OldParam;
2675 }
2676
2677 // We were missing some default arguments at the end of the list, so remove
2678 // all of the default arguments.
2679 if (RemoveDefaultArguments) {
2680 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2681 NewParamEnd = NewParams->end();
2682 NewParam != NewParamEnd; ++NewParam) {
2683 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2684 TTP->removeDefaultArgument();
2685 else if (NonTypeTemplateParmDecl *NTTP
2686 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2687 NTTP->removeDefaultArgument();
2688 else
2689 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2690 }
2691 }
2692
2693 return Invalid;
2694}
2695
2696namespace {
2697
2698/// A class which looks for a use of a certain level of template
2699/// parameter.
2700struct DependencyChecker : DynamicRecursiveASTVisitor {
2701 unsigned Depth;
2702
2703 // Whether we're looking for a use of a template parameter that makes the
2704 // overall construct type-dependent / a dependent type. This is strictly
2705 // best-effort for now; we may fail to match at all for a dependent type
2706 // in some cases if this is set.
2707 bool IgnoreNonTypeDependent;
2708
2709 bool Match;
2710 SourceLocation MatchLoc;
2711
2712 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2713 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2714 Match(false) {}
2715
2716 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2717 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2718 NamedDecl *ND = Params->getParam(0);
2719 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2720 Depth = PD->getDepth();
2721 } else if (NonTypeTemplateParmDecl *PD =
2722 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2723 Depth = PD->getDepth();
2724 } else {
2725 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2726 }
2727 }
2728
2729 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2730 if (ParmDepth >= Depth) {
2731 Match = true;
2732 MatchLoc = Loc;
2733 return true;
2734 }
2735 return false;
2736 }
2737
2738 bool TraverseStmt(Stmt *S) override {
2739 // Prune out non-type-dependent expressions if requested. This can
2740 // sometimes result in us failing to find a template parameter reference
2741 // (if a value-dependent expression creates a dependent type), but this
2742 // mode is best-effort only.
2743 if (auto *E = dyn_cast_or_null<Expr>(S))
2744 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2745 return true;
2747 }
2748
2749 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2750 if (IgnoreNonTypeDependent && !TL.isNull() &&
2751 !TL.getType()->isDependentType())
2752 return true;
2753 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2754 }
2755
2756 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2757 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2758 }
2759
2760 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2761 // For a best-effort search, keep looking until we find a location.
2762 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2763 }
2764
2765 bool TraverseTemplateName(TemplateName N) override {
2766 if (TemplateTemplateParmDecl *PD =
2767 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2768 if (Matches(PD->getDepth()))
2769 return false;
2771 }
2772
2773 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2774 if (NonTypeTemplateParmDecl *PD =
2775 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2776 if (Matches(PD->getDepth(), E->getExprLoc()))
2777 return false;
2778 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2779 }
2780
2781 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2782 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2783 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2784 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2785 return false;
2786 }
2787 for (auto &TLoc : ULE->template_arguments())
2789 }
2790 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2791 }
2792
2793 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2794 return TraverseType(T->getReplacementType());
2795 }
2796
2797 bool VisitSubstTemplateTypeParmPackType(
2798 SubstTemplateTypeParmPackType *T) override {
2799 return TraverseTemplateArgument(T->getArgumentPack());
2800 }
2801
2802 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2803 bool TraverseQualifier) override {
2804 // An InjectedClassNameType will never have a dependent template name,
2805 // so no need to traverse it.
2806 return TraverseTemplateArguments(
2807 T->getTemplateArgs(T->getDecl()->getASTContext()));
2808 }
2809};
2810} // end anonymous namespace
2811
2812/// Determines whether a given type depends on the given parameter
2813/// list.
2814static bool
2816 if (!Params->size())
2817 return false;
2818
2819 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2820 Checker.TraverseType(T);
2821 return Checker.Match;
2822}
2823
2824// Find the source range corresponding to the named type in the given
2825// nested-name-specifier, if any.
2827 QualType T,
2828 const CXXScopeSpec &SS) {
2830 for (;;) {
2833 break;
2834 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2835 return NNSLoc.castAsTypeLoc().getSourceRange();
2836 // FIXME: This will always be empty.
2837 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2838 }
2839
2840 return SourceRange();
2841}
2842
2844 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2845 TemplateIdAnnotation *TemplateId,
2846 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2847 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2848 IsMemberSpecialization = false;
2849 Invalid = false;
2850
2851 // The sequence of nested types to which we will match up the template
2852 // parameter lists. We first build this list by starting with the type named
2853 // by the nested-name-specifier and walking out until we run out of types.
2854 SmallVector<QualType, 4> NestedTypes;
2855 QualType T;
2856 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2857 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2858 if (CXXRecordDecl *Record =
2859 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2860 T = Context.getCanonicalTagType(Record);
2861 else
2862 T = QualType(Qualifier.getAsType(), 0);
2863 }
2864
2865 // If we found an explicit specialization that prevents us from needing
2866 // 'template<>' headers, this will be set to the location of that
2867 // explicit specialization.
2868 SourceLocation ExplicitSpecLoc;
2869
2870 while (!T.isNull()) {
2871 NestedTypes.push_back(T);
2872
2873 // Retrieve the parent of a record type.
2874 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2875 // If this type is an explicit specialization, we're done.
2877 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2879 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2880 ExplicitSpecLoc = Spec->getLocation();
2881 break;
2882 }
2883 } else if (Record->getTemplateSpecializationKind()
2885 ExplicitSpecLoc = Record->getLocation();
2886 break;
2887 }
2888
2889 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2890 T = Context.getTypeDeclType(Parent);
2891 else
2892 T = QualType();
2893 continue;
2894 }
2895
2896 if (const TemplateSpecializationType *TST
2897 = T->getAs<TemplateSpecializationType>()) {
2898 TemplateName Name = TST->getTemplateName();
2899 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2900 // Look one step prior in a dependent template specialization type.
2901 if (NestedNameSpecifier NNS = DTS->getQualifier();
2903 T = QualType(NNS.getAsType(), 0);
2904 else
2905 T = QualType();
2906 continue;
2907 }
2908 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2909 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2910 T = Context.getTypeDeclType(Parent);
2911 else
2912 T = QualType();
2913 continue;
2914 }
2915 }
2916
2917 // Look one step prior in a dependent name type.
2918 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2919 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2921 T = QualType(NNS.getAsType(), 0);
2922 else
2923 T = QualType();
2924 continue;
2925 }
2926
2927 // Retrieve the parent of an enumeration type.
2928 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2929 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2930 // check here.
2931 EnumDecl *Enum = EnumT->getDecl();
2932
2933 // Get to the parent type.
2934 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2935 T = Context.getCanonicalTypeDeclType(Parent);
2936 else
2937 T = QualType();
2938 continue;
2939 }
2940
2941 T = QualType();
2942 }
2943 // Reverse the nested types list, since we want to traverse from the outermost
2944 // to the innermost while checking template-parameter-lists.
2945 std::reverse(NestedTypes.begin(), NestedTypes.end());
2946
2947 // C++0x [temp.expl.spec]p17:
2948 // A member or a member template may be nested within many
2949 // enclosing class templates. In an explicit specialization for
2950 // such a member, the member declaration shall be preceded by a
2951 // template<> for each enclosing class template that is
2952 // explicitly specialized.
2953 bool SawNonEmptyTemplateParameterList = false;
2954
2955 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2956 if (SawNonEmptyTemplateParameterList) {
2957 if (!SuppressDiagnostic)
2958 Diag(DeclLoc, diag::err_specialize_member_of_template)
2959 << !Recovery << Range;
2960 Invalid = true;
2961 IsMemberSpecialization = false;
2962 return true;
2963 }
2964
2965 return false;
2966 };
2967
2968 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2969 // Check that we can have an explicit specialization here.
2970 if (CheckExplicitSpecialization(Range, true))
2971 return true;
2972
2973 // We don't have a template header, but we should.
2974 SourceLocation ExpectedTemplateLoc;
2975 if (!ParamLists.empty())
2976 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2977 else
2978 ExpectedTemplateLoc = DeclStartLoc;
2979
2980 if (!SuppressDiagnostic)
2981 Diag(DeclLoc, diag::err_template_spec_needs_header)
2982 << Range
2983 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2984 return false;
2985 };
2986
2987 unsigned ParamIdx = 0;
2988 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2989 ++TypeIdx) {
2990 T = NestedTypes[TypeIdx];
2991
2992 // Whether we expect a 'template<>' header.
2993 bool NeedEmptyTemplateHeader = false;
2994
2995 // Whether we expect a template header with parameters.
2996 bool NeedNonemptyTemplateHeader = false;
2997
2998 // For a dependent type, the set of template parameters that we
2999 // expect to see.
3000 TemplateParameterList *ExpectedTemplateParams = nullptr;
3001
3002 // C++0x [temp.expl.spec]p15:
3003 // A member or a member template may be nested within many enclosing
3004 // class templates. In an explicit specialization for such a member, the
3005 // member declaration shall be preceded by a template<> for each
3006 // enclosing class template that is explicitly specialized.
3007 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3009 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3010 ExpectedTemplateParams = Partial->getTemplateParameters();
3011 NeedNonemptyTemplateHeader = true;
3012 } else if (Record->isDependentType()) {
3013 if (Record->getDescribedClassTemplate()) {
3014 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3015 ->getTemplateParameters();
3016 NeedNonemptyTemplateHeader = true;
3017 }
3018 } else if (ClassTemplateSpecializationDecl *Spec
3019 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3020 // C++0x [temp.expl.spec]p4:
3021 // Members of an explicitly specialized class template are defined
3022 // in the same manner as members of normal classes, and not using
3023 // the template<> syntax.
3024 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3025 NeedEmptyTemplateHeader = true;
3026 else
3027 continue;
3028 } else if (Record->getTemplateSpecializationKind()) {
3029 if (Record->getTemplateSpecializationKind()
3031 TypeIdx == NumTypes - 1)
3032 IsMemberSpecialization = true;
3033
3034 continue;
3035 }
3036 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3037 TemplateName Name = TST->getTemplateName();
3038 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3039 ExpectedTemplateParams = Template->getTemplateParameters();
3040 NeedNonemptyTemplateHeader = true;
3041 } else if (Name.getAsDeducedTemplateName()) {
3042 // FIXME: We actually could/should check the template arguments here
3043 // against the corresponding template parameter list.
3044 NeedNonemptyTemplateHeader = false;
3045 }
3046 }
3047
3048 // C++ [temp.expl.spec]p16:
3049 // In an explicit specialization declaration for a member of a class
3050 // template or a member template that appears in namespace scope, the
3051 // member template and some of its enclosing class templates may remain
3052 // unspecialized, except that the declaration shall not explicitly
3053 // specialize a class member template if its enclosing class templates
3054 // are not explicitly specialized as well.
3055 if (ParamIdx < ParamLists.size()) {
3056 if (ParamLists[ParamIdx]->size() == 0) {
3057 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3058 false))
3059 return nullptr;
3060 } else
3061 SawNonEmptyTemplateParameterList = true;
3062 }
3063
3064 if (NeedEmptyTemplateHeader) {
3065 // If we're on the last of the types, and we need a 'template<>' header
3066 // here, then it's a member specialization.
3067 if (TypeIdx == NumTypes - 1)
3068 IsMemberSpecialization = true;
3069
3070 if (ParamIdx < ParamLists.size()) {
3071 if (ParamLists[ParamIdx]->size() > 0) {
3072 // The header has template parameters when it shouldn't. Complain.
3073 if (!SuppressDiagnostic)
3074 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3075 diag::err_template_param_list_matches_nontemplate)
3076 << T
3077 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3078 ParamLists[ParamIdx]->getRAngleLoc())
3080 Invalid = true;
3081 return nullptr;
3082 }
3083
3084 // Consume this template header.
3085 ++ParamIdx;
3086 continue;
3087 }
3088
3089 if (!IsFriend)
3090 if (DiagnoseMissingExplicitSpecialization(
3092 return nullptr;
3093
3094 continue;
3095 }
3096
3097 if (NeedNonemptyTemplateHeader) {
3098 // In friend declarations we can have template-ids which don't
3099 // depend on the corresponding template parameter lists. But
3100 // assume that empty parameter lists are supposed to match this
3101 // template-id.
3102 if (IsFriend && T->isDependentType()) {
3103 if (ParamIdx < ParamLists.size() &&
3104 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3105 ExpectedTemplateParams = nullptr;
3106 else
3107 continue;
3108 }
3109
3110 if (ParamIdx < ParamLists.size()) {
3111 // Check the template parameter list, if we can.
3112 if (ExpectedTemplateParams &&
3114 ExpectedTemplateParams,
3115 !SuppressDiagnostic, TPL_TemplateMatch))
3116 Invalid = true;
3117
3118 if (!Invalid &&
3119 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3121 Invalid = true;
3122
3123 ++ParamIdx;
3124 continue;
3125 }
3126
3127 if (!SuppressDiagnostic)
3128 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3129 << T
3131 Invalid = true;
3132 continue;
3133 }
3134 }
3135
3136 // If there were at least as many template-ids as there were template
3137 // parameter lists, then there are no template parameter lists remaining for
3138 // the declaration itself.
3139 if (ParamIdx >= ParamLists.size()) {
3140 if (TemplateId && !IsFriend) {
3141 // We don't have a template header for the declaration itself, but we
3142 // should.
3143 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3144 TemplateId->RAngleLoc));
3145
3146 // Fabricate an empty template parameter list for the invented header.
3148 SourceLocation(), {},
3149 SourceLocation(), nullptr);
3150 }
3151
3152 return nullptr;
3153 }
3154
3155 // If there were too many template parameter lists, complain about that now.
3156 if (ParamIdx < ParamLists.size() - 1) {
3157 bool HasAnyExplicitSpecHeader = false;
3158 bool AllExplicitSpecHeaders = true;
3159 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3160 if (ParamLists[I]->size() == 0)
3161 HasAnyExplicitSpecHeader = true;
3162 else
3163 AllExplicitSpecHeaders = false;
3164 }
3165
3166 if (!SuppressDiagnostic)
3167 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3168 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3169 : diag::err_template_spec_extra_headers)
3170 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3171 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3172
3173 // If there was a specialization somewhere, such that 'template<>' is
3174 // not required, and there were any 'template<>' headers, note where the
3175 // specialization occurred.
3176 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3177 !SuppressDiagnostic)
3178 Diag(ExplicitSpecLoc,
3179 diag::note_explicit_template_spec_does_not_need_header)
3180 << NestedTypes.back();
3181
3182 // We have a template parameter list with no corresponding scope, which
3183 // means that the resulting template declaration can't be instantiated
3184 // properly (we'll end up with dependent nodes when we shouldn't).
3185 if (!AllExplicitSpecHeaders)
3186 Invalid = true;
3187 }
3188
3189 // C++ [temp.expl.spec]p16:
3190 // In an explicit specialization declaration for a member of a class
3191 // template or a member template that ap- pears in namespace scope, the
3192 // member template and some of its enclosing class templates may remain
3193 // unspecialized, except that the declaration shall not explicitly
3194 // specialize a class member template if its en- closing class templates
3195 // are not explicitly specialized as well.
3196 if (ParamLists.back()->size() == 0 &&
3197 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3198 false))
3199 return nullptr;
3200
3201 // Return the last template parameter list, which corresponds to the
3202 // entity being declared.
3203 return ParamLists.back();
3204}
3205
3207 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3208 Diag(Template->getLocation(), diag::note_template_declared_here)
3210 ? 0
3212 ? 1
3214 ? 2
3216 << Template->getDeclName();
3217 return;
3218 }
3219
3221 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3222 IEnd = OST->end();
3223 I != IEnd; ++I)
3224 Diag((*I)->getLocation(), diag::note_template_declared_here)
3225 << 0 << (*I)->getDeclName();
3226
3227 return;
3228 }
3229}
3230
3232 TemplateName BaseTemplate,
3233 SourceLocation TemplateLoc,
3235 auto lookUpCommonType = [&](TemplateArgument T1,
3236 TemplateArgument T2) -> QualType {
3237 // Don't bother looking for other specializations if both types are
3238 // builtins - users aren't allowed to specialize for them
3239 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3240 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3241 {T1, T2});
3242
3246 Args.addArgument(TemplateArgumentLoc(
3247 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3248
3249 EnterExpressionEvaluationContext UnevaluatedContext(
3251 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3253
3254 QualType BaseTemplateInst = S.CheckTemplateIdType(
3255 Keyword, BaseTemplate, TemplateLoc, Args,
3256 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3257
3258 if (SFINAE.hasErrorOccurred())
3259 return QualType();
3260
3261 return BaseTemplateInst;
3262 };
3263
3264 // Note A: For the common_type trait applied to a template parameter pack T of
3265 // types, the member type shall be either defined or not present as follows:
3266 switch (Ts.size()) {
3267
3268 // If sizeof...(T) is zero, there shall be no member type.
3269 case 0:
3270 return QualType();
3271
3272 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3273 // pack T. The member typedef-name type shall denote the same type, if any, as
3274 // common_type_t<T0, T0>; otherwise there shall be no member type.
3275 case 1:
3276 return lookUpCommonType(Ts[0], Ts[0]);
3277
3278 // If sizeof...(T) is two, let the first and second types constituting T be
3279 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3280 // as decay_t<T1> and decay_t<T2>, respectively.
3281 case 2: {
3282 QualType T1 = Ts[0].getAsType();
3283 QualType T2 = Ts[1].getAsType();
3284 QualType D1 = S.BuiltinDecay(T1, {});
3285 QualType D2 = S.BuiltinDecay(T2, {});
3286
3287 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3288 // the same type, if any, as common_type_t<D1, D2>.
3289 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3290 return lookUpCommonType(D1, D2);
3291
3292 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3293 // denotes a valid type, let C denote that type.
3294 {
3295 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3296 EnterExpressionEvaluationContext UnevaluatedContext(
3298 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3300
3301 // false
3303 VK_PRValue);
3304 ExprResult Cond = &CondExpr;
3305
3306 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3307 if (ConstRefQual) {
3308 D1.addConst();
3309 D2.addConst();
3310 }
3311
3312 // declval<D1>()
3313 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3314 ExprResult LHS = &LHSExpr;
3315
3316 // declval<D2>()
3317 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3318 ExprResult RHS = &RHSExpr;
3319
3322
3323 // decltype(false ? declval<D1>() : declval<D2>())
3325 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3326
3327 if (Result.isNull() || SFINAE.hasErrorOccurred())
3328 return QualType();
3329
3330 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3331 return S.BuiltinDecay(Result, TemplateLoc);
3332 };
3333
3334 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3335 return Res;
3336
3337 // Let:
3338 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3339 // COND-RES(X, Y) be
3340 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3341
3342 // C++20 only
3343 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3344 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3345 if (!S.Context.getLangOpts().CPlusPlus20)
3346 return QualType();
3347 return CheckConditionalOperands(true);
3348 }
3349 }
3350
3351 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3352 // denote the first, second, and (pack of) remaining types constituting T. Let
3353 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3354 // a type C, the member typedef-name type shall denote the same type, if any,
3355 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3356 default: {
3357 QualType Result = Ts.front().getAsType();
3358 for (auto T : llvm::drop_begin(Ts)) {
3359 Result = lookUpCommonType(Result, T.getAsType());
3360 if (Result.isNull())
3361 return QualType();
3362 }
3363 return Result;
3364 }
3365 }
3366}
3367
3368static bool isInVkNamespace(const RecordType *RT) {
3369 DeclContext *DC = RT->getDecl()->getDeclContext();
3370 if (!DC)
3371 return false;
3372
3373 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3374 if (!ND)
3375 return false;
3376
3377 return ND->getQualifiedNameAsString() == "hlsl::vk";
3378}
3379
3380static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3381 QualType OperandArg,
3382 SourceLocation Loc) {
3383 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3384 bool Literal = false;
3385 SourceLocation LiteralLoc;
3386 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3387 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3388 assert(SpecDecl);
3389
3390 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3391 QualType ConstantType = LiteralArgs[0].getAsType();
3392 RT = ConstantType->getAsCanonical<RecordType>();
3393 Literal = true;
3394 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3395 }
3396
3397 if (RT && isInVkNamespace(RT) &&
3398 RT->getDecl()->getName() == "integral_constant") {
3399 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3400 assert(SpecDecl);
3401
3402 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3403
3404 QualType ConstantType = ConstantArgs[0].getAsType();
3405 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3406
3407 if (Literal)
3408 return SpirvOperand::createLiteral(Value);
3409 return SpirvOperand::createConstant(ConstantType, Value);
3410 } else if (Literal) {
3411 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3412 return SpirvOperand();
3413 }
3414 }
3415 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3416 diag::err_call_incomplete_argument))
3417 return SpirvOperand();
3418 return SpirvOperand::createType(OperandArg);
3419}
3420
3423 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3424 TemplateArgumentListInfo &TemplateArgs) {
3425 ASTContext &Context = SemaRef.getASTContext();
3426
3427 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3428 "Builtin template arguments do not match its parameters");
3429
3430 switch (BTD->getBuiltinTemplateKind()) {
3431 case BTK__make_integer_seq: {
3432 // Specializations of __make_integer_seq<S, T, N> are treated like
3433 // S<T, 0, ..., N-1>.
3434
3435 QualType OrigType = Converted[1].getAsType();
3436 // C++14 [inteseq.intseq]p1:
3437 // T shall be an integer type.
3438 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3439 SemaRef.Diag(TemplateArgs[1].getLocation(),
3440 diag::err_integer_sequence_integral_element_type);
3441 return QualType();
3442 }
3443
3444 TemplateArgument NumArgsArg = Converted[2];
3445 if (NumArgsArg.isDependent())
3446 return QualType();
3447
3448 TemplateArgumentListInfo SyntheticTemplateArgs;
3449 // The type argument, wrapped in substitution sugar, gets reused as the
3450 // first template argument in the synthetic template argument list.
3451 SyntheticTemplateArgs.addArgument(
3454 OrigType, TemplateArgs[1].getLocation())));
3455
3456 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3457 // Expand N into 0 ... N-1.
3458 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3459 I < NumArgs; ++I) {
3460 TemplateArgument TA(Context, I, OrigType);
3461 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3462 TA, OrigType, TemplateArgs[2].getLocation()));
3463 }
3464 } else {
3465 // C++14 [inteseq.make]p1:
3466 // If N is negative the program is ill-formed.
3467 SemaRef.Diag(TemplateArgs[2].getLocation(),
3468 diag::err_integer_sequence_negative_length);
3469 return QualType();
3470 }
3471
3472 // The first template argument will be reused as the template decl that
3473 // our synthetic template arguments will be applied to.
3474 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3475 TemplateLoc, SyntheticTemplateArgs,
3476 /*Scope=*/nullptr,
3477 /*ForNestedNameSpecifier=*/false);
3478 }
3479
3480 case BTK__type_pack_element: {
3481 // Specializations of
3482 // __type_pack_element<Index, T_1, ..., T_N>
3483 // are treated like T_Index.
3484 assert(Converted.size() == 2 &&
3485 "__type_pack_element should be given an index and a parameter pack");
3486
3487 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3488 if (IndexArg.isDependent() || Ts.isDependent())
3489 return QualType();
3490
3491 llvm::APSInt Index = IndexArg.getAsIntegral();
3492 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3493 "type std::size_t, and hence be non-negative");
3494 // If the Index is out of bounds, the program is ill-formed.
3495 if (Index >= Ts.pack_size()) {
3496 SemaRef.Diag(TemplateArgs[0].getLocation(),
3497 diag::err_type_pack_element_out_of_bounds);
3498 return QualType();
3499 }
3500
3501 // We simply return the type at index `Index`.
3502 int64_t N = Index.getExtValue();
3503 return Ts.getPackAsArray()[N].getAsType();
3504 }
3505
3506 case BTK__builtin_common_type: {
3507 assert(Converted.size() == 4);
3508 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3509 return QualType();
3510
3511 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3512 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3513 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3514 TemplateLoc, Ts);
3515 !CT.isNull()) {
3519 CT, TemplateArgs[1].getLocation())));
3520 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3521 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3522 TAs, /*Scope=*/nullptr,
3523 /*ForNestedNameSpecifier=*/false);
3524 }
3525 QualType HasNoTypeMember = Converted[2].getAsType();
3526 return HasNoTypeMember;
3527 }
3528
3529 case BTK__hlsl_spirv_type: {
3530 assert(Converted.size() == 4);
3531
3532 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3533 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3534 }
3535
3536 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3537 return QualType();
3538
3539 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3540 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3541 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3542
3543 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3544
3546
3547 for (auto &OperandTA : OperandArgs) {
3548 QualType OperandArg = OperandTA.getAsType();
3549 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3550 TemplateArgs[3].getLocation());
3551 if (!Operand.isValid())
3552 return QualType();
3553 Operands.push_back(Operand);
3554 }
3555
3556 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3557 }
3558 case BTK__builtin_dedup_pack: {
3559 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3560 "a parameter pack");
3561 TemplateArgument Ts = Converted[0];
3562 // Delay the computation until we can compute the final result. We choose
3563 // not to remove the duplicates upfront before substitution to keep the code
3564 // simple.
3565 if (Ts.isDependent())
3566 return QualType();
3567 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3569 llvm::SmallDenseSet<QualType> Seen;
3570 // Synthesize a new template argument list, removing duplicates.
3571 for (auto T : Ts.getPackAsArray()) {
3572 assert(T.getKind() == clang::TemplateArgument::Type);
3573 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3574 continue;
3575 OutArgs.push_back(T);
3576 }
3577 return Context.getSubstBuiltinTemplatePack(
3578 TemplateArgument::CreatePackCopy(Context, OutArgs));
3579 }
3580 }
3581 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3582}
3583
3584/// Determine whether this alias template is "enable_if_t".
3585/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3587 return AliasTemplate->getName() == "enable_if_t" ||
3588 AliasTemplate->getName() == "__enable_if_t";
3589}
3590
3591/// Collect all of the separable terms in the given condition, which
3592/// might be a conjunction.
3593///
3594/// FIXME: The right answer is to convert the logical expression into
3595/// disjunctive normal form, so we can find the first failed term
3596/// within each possible clause.
3597static void collectConjunctionTerms(Expr *Clause,
3598 SmallVectorImpl<Expr *> &Terms) {
3599 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3600 if (BinOp->getOpcode() == BO_LAnd) {
3601 collectConjunctionTerms(BinOp->getLHS(), Terms);
3602 collectConjunctionTerms(BinOp->getRHS(), Terms);
3603 return;
3604 }
3605 }
3606
3607 Terms.push_back(Clause);
3608}
3609
3610// The ranges-v3 library uses an odd pattern of a top-level "||" with
3611// a left-hand side that is value-dependent but never true. Identify
3612// the idiom and ignore that term.
3614 // Top-level '||'.
3615 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3616 if (!BinOp) return Cond;
3617
3618 if (BinOp->getOpcode() != BO_LOr) return Cond;
3619
3620 // With an inner '==' that has a literal on the right-hand side.
3621 Expr *LHS = BinOp->getLHS();
3622 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3623 if (!InnerBinOp) return Cond;
3624
3625 if (InnerBinOp->getOpcode() != BO_EQ ||
3626 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3627 return Cond;
3628
3629 // If the inner binary operation came from a macro expansion named
3630 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3631 // of the '||', which is the real, user-provided condition.
3632 SourceLocation Loc = InnerBinOp->getExprLoc();
3633 if (!Loc.isMacroID()) return Cond;
3634
3635 StringRef MacroName = PP.getImmediateMacroName(Loc);
3636 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3637 return BinOp->getRHS();
3638
3639 return Cond;
3640}
3641
3642namespace {
3643
3644// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3645// within failing boolean expression, such as substituting template parameters
3646// for actual types.
3647class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3648public:
3649 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3650 : Policy(P) {}
3651
3652 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3653 const auto *DR = dyn_cast<DeclRefExpr>(E);
3654 if (DR && DR->getQualifier()) {
3655 // If this is a qualified name, expand the template arguments in nested
3656 // qualifiers.
3657 DR->getQualifier().print(OS, Policy, true);
3658 // Then print the decl itself.
3659 const ValueDecl *VD = DR->getDecl();
3660 OS << VD->getName();
3661 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3662 // This is a template variable, print the expanded template arguments.
3663 printTemplateArgumentList(
3664 OS, IV->getTemplateArgs().asArray(), Policy,
3665 IV->getSpecializedTemplate()->getTemplateParameters());
3666 }
3667 return true;
3668 }
3669 return false;
3670 }
3671
3672private:
3673 const PrintingPolicy Policy;
3674};
3675
3676} // end anonymous namespace
3677
3678std::pair<Expr *, std::string>
3681
3682 // Separate out all of the terms in a conjunction.
3685
3686 // Determine which term failed.
3687 Expr *FailedCond = nullptr;
3688 for (Expr *Term : Terms) {
3689 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3690
3691 // Literals are uninteresting.
3692 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3693 isa<IntegerLiteral>(TermAsWritten))
3694 continue;
3695
3696 // The initialization of the parameter from the argument is
3697 // a constant-evaluated context.
3700
3701 bool Succeeded;
3702 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3703 !Succeeded) {
3704 FailedCond = TermAsWritten;
3705 break;
3706 }
3707 }
3708 if (!FailedCond)
3709 FailedCond = Cond->IgnoreParenImpCasts();
3710
3711 std::string Description;
3712 {
3713 llvm::raw_string_ostream Out(Description);
3715 Policy.PrintAsCanonical = true;
3716 FailedBooleanConditionPrinterHelper Helper(Policy);
3717 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3718 }
3719 return { FailedCond, Description };
3720}
3721
3722static TemplateName
3724 const AssumedTemplateStorage *ATN,
3725 SourceLocation NameLoc) {
3726 // We assumed this undeclared identifier to be an (ADL-only) function
3727 // template name, but it was used in a context where a type was required.
3728 // Try to typo-correct it now.
3729 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3730 struct CandidateCallback : CorrectionCandidateCallback {
3731 bool ValidateCandidate(const TypoCorrection &TC) override {
3732 return TC.getCorrectionDecl() &&
3734 }
3735 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3736 return std::make_unique<CandidateCallback>(*this);
3737 }
3738 } FilterCCC;
3739
3740 TypoCorrection Corrected =
3741 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3742 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3743 if (Corrected && Corrected.getFoundDecl()) {
3744 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3745 << ATN->getDeclName());
3747 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3749 }
3750
3751 return TemplateName();
3752}
3753
3755 TemplateName Name,
3756 SourceLocation TemplateLoc,
3757 TemplateArgumentListInfo &TemplateArgs,
3758 Scope *Scope, bool ForNestedNameSpecifier) {
3759 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3760
3761 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3762 if (!Template) {
3763 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3764 Template = S->getParameterPack();
3765 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3766 if (DTN->getName().getIdentifier())
3767 // When building a template-id where the template-name is dependent,
3768 // assume the template is a type template. Either our assumption is
3769 // correct, or the code is ill-formed and will be diagnosed when the
3770 // dependent name is substituted.
3771 return Context.getTemplateSpecializationType(Keyword, Name,
3772 TemplateArgs.arguments(),
3773 /*CanonicalArgs=*/{});
3774 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3776 *this, Scope, ATN, TemplateLoc);
3777 CorrectedName.isNull()) {
3778 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3779 return QualType();
3780 } else {
3781 Name = CorrectedName;
3782 Template = Name.getAsTemplateDecl();
3783 }
3784 }
3785 }
3786 if (!Template ||
3788 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3789 if (ForNestedNameSpecifier)
3790 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3791 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3792 else
3793 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3795 return QualType();
3796 }
3797
3798 // Check that the template argument list is well-formed for this
3799 // template.
3801 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3802 DefaultArgs, /*PartialTemplateArgs=*/false,
3803 CTAI,
3804 /*UpdateArgsWithConversions=*/true))
3805 return QualType();
3806
3807 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3808 // and there are no diagnsotics currently implemented for TemplateDecls,
3809 // so avoid doing it for now.
3810 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3811
3812 QualType CanonType;
3813
3815 // We might have a substituted template template parameter pack. If so,
3816 // build a template specialization type for it.
3818 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3819
3820 // C++0x [dcl.type.elab]p2:
3821 // If the identifier resolves to a typedef-name or the simple-template-id
3822 // resolves to an alias template specialization, the
3823 // elaborated-type-specifier is ill-formed.
3826 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3829 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3830 }
3831
3832 // Find the canonical type for this type alias template specialization.
3833 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3834
3835 // Diagnose uses of the pattern of this template.
3836 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3837 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3838
3839 if (Pattern->isInvalidDecl())
3840 return QualType();
3841
3842 // Only substitute for the innermost template argument list.
3843 MultiLevelTemplateArgumentList TemplateArgLists;
3845 /*Final=*/true);
3846 TemplateArgLists.addOuterRetainedLevels(
3847 AliasTemplate->getTemplateParameters()->getDepth());
3848
3850
3851 // FIXME: The TemplateArgs passed here are not used for the context note,
3852 // nor they should, because this note will be pointing to the specialization
3853 // anyway. These arguments are needed for a hack for instantiating lambdas
3854 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3855 // arguments will be used for collating the template arguments needed to
3856 // instantiate the lambda.
3857 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3858 /*Entity=*/AliasTemplate,
3859 /*TemplateArgs=*/CTAI.SugaredConverted);
3860 if (Inst.isInvalid())
3861 return QualType();
3862
3863 std::optional<ContextRAII> SavedContext;
3864 if (!AliasTemplate->getDeclContext()->isFileContext())
3865 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3866
3867 CanonType =
3868 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3869 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3870 if (CanonType.isNull()) {
3871 // If this was enable_if and we failed to find the nested type
3872 // within enable_if in a SFINAE context, dig out the specific
3873 // enable_if condition that failed and present that instead.
3875 if (SFINAETrap *Trap = getSFINAEContext();
3876 TemplateDeductionInfo *DeductionInfo =
3877 Trap ? Trap->getDeductionInfo() : nullptr) {
3878 if (DeductionInfo->hasSFINAEDiagnostic() &&
3879 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3880 diag::err_typename_nested_not_found_enable_if &&
3881 TemplateArgs[0].getArgument().getKind() ==
3883 Expr *FailedCond;
3884 std::string FailedDescription;
3885 std::tie(FailedCond, FailedDescription) =
3886 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3887
3888 // Remove the old SFINAE diagnostic.
3889 PartialDiagnosticAt OldDiag =
3891 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3892
3893 // Add a new SFINAE diagnostic specifying which condition
3894 // failed.
3895 DeductionInfo->addSFINAEDiagnostic(
3896 OldDiag.first,
3897 PDiag(diag::err_typename_nested_not_found_requirement)
3898 << FailedDescription << FailedCond->getSourceRange());
3899 }
3900 }
3901 }
3902
3903 return QualType();
3904 }
3905 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3906 CanonType = checkBuiltinTemplateIdType(
3907 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3908 } else if (Name.isDependent() ||
3909 TemplateSpecializationType::anyDependentTemplateArguments(
3910 TemplateArgs, CTAI.CanonicalConverted)) {
3911 // This class template specialization is a dependent
3912 // type. Therefore, its canonical type is another class template
3913 // specialization type that contains all of the converted
3914 // arguments in canonical form. This ensures that, e.g., A<T> and
3915 // A<T, T> have identical types when A is declared as:
3916 //
3917 // template<typename T, typename U = T> struct A;
3918 CanonType = Context.getCanonicalTemplateSpecializationType(
3920 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3921 CTAI.CanonicalConverted);
3922 assert(CanonType->isCanonicalUnqualified());
3923
3924 // This might work out to be a current instantiation, in which
3925 // case the canonical type needs to be the InjectedClassNameType.
3926 //
3927 // TODO: in theory this could be a simple hashtable lookup; most
3928 // changes to CurContext don't change the set of current
3929 // instantiations.
3931 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3932 // If we get out to a namespace, we're done.
3933 if (Ctx->isFileContext()) break;
3934
3935 // If this isn't a record, keep looking.
3936 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3937 if (!Record) continue;
3938
3939 // Look for one of the two cases with InjectedClassNameTypes
3940 // and check whether it's the same template.
3942 !Record->getDescribedClassTemplate())
3943 continue;
3944
3945 // Fetch the injected class name type and check whether its
3946 // injected type is equal to the type we just built.
3947 CanQualType ICNT = Context.getCanonicalTagType(Record);
3948 CanQualType Injected =
3949 Record->getCanonicalTemplateSpecializationType(Context);
3950
3951 if (CanonType != Injected)
3952 continue;
3953
3954 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3955 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3956
3957 // If so, the canonical type of this TST is the injected
3958 // class name type of the record we just found.
3959 CanonType = ICNT;
3960 break;
3961 }
3962 }
3963 } else if (ClassTemplateDecl *ClassTemplate =
3964 dyn_cast<ClassTemplateDecl>(Template)) {
3965 // Find the class template specialization declaration that
3966 // corresponds to these arguments.
3967 void *InsertPos = nullptr;
3969 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3970 if (!Decl) {
3971 // This is the first time we have referenced this class template
3972 // specialization. Create the canonical declaration and add it to
3973 // the set of specializations.
3975 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3976 ClassTemplate->getDeclContext(),
3977 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3978 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3979 CTAI.StrictPackMatch, nullptr);
3980 ClassTemplate->AddSpecialization(Decl, InsertPos);
3981 if (ClassTemplate->isOutOfLine())
3982 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3983 }
3984
3985 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3986 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3987 NonSFINAEContext _(*this);
3988 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3989 if (!Inst.isInvalid()) {
3991 CTAI.CanonicalConverted,
3992 /*Final=*/false);
3993 InstantiateAttrsForDecl(TemplateArgLists,
3994 ClassTemplate->getTemplatedDecl(), Decl);
3995 }
3996 }
3997
3998 // Diagnose uses of this specialization.
3999 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4000 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4001
4002 CanonType = Context.getCanonicalTagType(Decl);
4003 assert(isa<RecordType>(CanonType) &&
4004 "type of non-dependent specialization is not a RecordType");
4005 } else {
4006 llvm_unreachable("Unhandled template kind");
4007 }
4008
4009 // Build the fully-sugared type for this class template
4010 // specialization, which refers back to the class template
4011 // specialization we created or found.
4012 return Context.getTemplateSpecializationType(
4013 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4014 CanonType);
4015}
4016
4018 TemplateNameKind &TNK,
4019 SourceLocation NameLoc,
4020 IdentifierInfo *&II) {
4021 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4022
4023 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4024 assert(ATN && "not an assumed template name");
4025 II = ATN->getDeclName().getAsIdentifierInfo();
4026
4027 if (TemplateName Name =
4028 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4029 !Name.isNull()) {
4030 // Resolved to a type template name.
4031 ParsedName = TemplateTy::make(Name);
4032 TNK = TNK_Type_template;
4033 }
4034}
4035
4037 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4038 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4039 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4040 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4041 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4042 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4043 ImplicitTypenameContext AllowImplicitTypename) {
4044 if (SS.isInvalid())
4045 return true;
4046
4047 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4048 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4049
4050 // C++ [temp.res]p3:
4051 // A qualified-id that refers to a type and in which the
4052 // nested-name-specifier depends on a template-parameter (14.6.2)
4053 // shall be prefixed by the keyword typename to indicate that the
4054 // qualified-id denotes a type, forming an
4055 // elaborated-type-specifier (7.1.5.3).
4056 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4057 // C++2a relaxes some of those restrictions in [temp.res]p5.
4058 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4059 SS.getScopeRep(), TemplateII);
4061 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4062 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4063 << NNS;
4064 if (!getLangOpts().CPlusPlus20)
4065 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4066 } else
4067 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4068
4069 // FIXME: This is not quite correct recovery as we don't transform SS
4070 // into the corresponding dependent form (and we don't diagnose missing
4071 // 'template' keywords within SS as a result).
4072 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4073 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4074 TemplateArgsIn, RAngleLoc);
4075 }
4076
4077 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4078 // it's not actually allowed to be used as a type in most cases. Because
4079 // we annotate it before we know whether it's valid, we have to check for
4080 // this case here.
4081 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4082 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4083 Diag(TemplateIILoc,
4084 TemplateKWLoc.isInvalid()
4085 ? diag::err_out_of_line_qualified_id_type_names_constructor
4086 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4087 << TemplateII << 0 /*injected-class-name used as template name*/
4088 << 1 /*if any keyword was present, it was 'template'*/;
4089 }
4090 }
4091
4092 // Translate the parser's template argument list in our AST format.
4093 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4094 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4095
4097 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4098 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4099 if (SpecTy.isNull())
4100 return true;
4101
4102 // Build type-source information.
4103 TypeLocBuilder TLB;
4104 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4105 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4106 TemplateIILoc, TemplateArgs);
4107 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4108}
4109
4111 TypeSpecifierType TagSpec,
4112 SourceLocation TagLoc,
4113 CXXScopeSpec &SS,
4114 SourceLocation TemplateKWLoc,
4115 TemplateTy TemplateD,
4116 SourceLocation TemplateLoc,
4117 SourceLocation LAngleLoc,
4118 ASTTemplateArgsPtr TemplateArgsIn,
4119 SourceLocation RAngleLoc) {
4120 if (SS.isInvalid())
4121 return TypeResult(true);
4122
4123 // Translate the parser's template argument list in our AST format.
4124 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4125 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4126
4127 // Determine the tag kind
4131
4133 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4134 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4135 if (Result.isNull())
4136 return TypeResult(true);
4137
4138 // Check the tag kind
4139 if (const RecordType *RT = Result->getAs<RecordType>()) {
4140 RecordDecl *D = RT->getDecl();
4141
4142 IdentifierInfo *Id = D->getIdentifier();
4143 assert(Id && "templated class must have an identifier");
4144
4146 TagLoc, Id)) {
4147 Diag(TagLoc, diag::err_use_with_wrong_tag)
4148 << Result
4150 Diag(D->getLocation(), diag::note_previous_use);
4151 }
4152 }
4153
4154 // Provide source-location information for the template specialization.
4155 TypeLocBuilder TLB;
4157 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4158 TemplateArgs);
4160}
4161
4162static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4163 NamedDecl *PrevDecl,
4164 SourceLocation Loc,
4166
4168
4170 unsigned Depth,
4171 unsigned Index) {
4172 switch (Arg.getKind()) {
4180 return false;
4181
4183 QualType Type = Arg.getAsType();
4184 const TemplateTypeParmType *TPT =
4185 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4186 return TPT && !Type.hasQualifiers() &&
4187 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4188 }
4189
4191 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4192 if (!DRE || !DRE->getDecl())
4193 return false;
4194 const NonTypeTemplateParmDecl *NTTP =
4195 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4196 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4197 }
4198
4200 const TemplateTemplateParmDecl *TTP =
4201 dyn_cast_or_null<TemplateTemplateParmDecl>(
4203 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4204 }
4205 llvm_unreachable("unexpected kind of template argument");
4206}
4207
4209 TemplateParameterList *SpecParams,
4211 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4212 return false;
4213
4214 unsigned Depth = Params->getDepth();
4215
4216 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4217 TemplateArgument Arg = Args[I];
4218
4219 // If the parameter is a pack expansion, the argument must be a pack
4220 // whose only element is a pack expansion.
4221 if (Params->getParam(I)->isParameterPack()) {
4222 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4223 !Arg.pack_begin()->isPackExpansion())
4224 return false;
4225 Arg = Arg.pack_begin()->getPackExpansionPattern();
4226 }
4227
4228 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4229 return false;
4230
4231 // For NTTPs further specialization is allowed via deduced types, so
4232 // we need to make sure to only reject here if primary template and
4233 // specialization use the same type for the NTTP.
4234 if (auto *SpecNTTP =
4235 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4236 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4237 if (!NTTP || NTTP->getType().getCanonicalType() !=
4238 SpecNTTP->getType().getCanonicalType())
4239 return false;
4240 }
4241 }
4242
4243 return true;
4244}
4245
4246template<typename PartialSpecDecl>
4247static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4248 if (Partial->getDeclContext()->isDependentContext())
4249 return;
4250
4251 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4252 // for non-substitution-failure issues?
4253 TemplateDeductionInfo Info(Partial->getLocation());
4254 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4255 return;
4256
4257 auto *Template = Partial->getSpecializedTemplate();
4258 S.Diag(Partial->getLocation(),
4259 diag::ext_partial_spec_not_more_specialized_than_primary)
4261
4262 if (Info.hasSFINAEDiagnostic()) {
4266 SmallString<128> SFINAEArgString;
4267 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4268 S.Diag(Diag.first,
4269 diag::note_partial_spec_not_more_specialized_than_primary)
4270 << SFINAEArgString;
4271 }
4272
4274 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4275 Template->getAssociatedConstraints(TemplateAC);
4276 Partial->getAssociatedConstraints(PartialAC);
4278 TemplateAC);
4279}
4280
4281static void
4283 const llvm::SmallBitVector &DeducibleParams) {
4284 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4285 if (!DeducibleParams[I]) {
4286 NamedDecl *Param = TemplateParams->getParam(I);
4287 if (Param->getDeclName())
4288 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4289 << Param->getDeclName();
4290 else
4291 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4292 << "(anonymous)";
4293 }
4294 }
4295}
4296
4297
4298template<typename PartialSpecDecl>
4300 PartialSpecDecl *Partial) {
4301 // C++1z [temp.class.spec]p8: (DR1495)
4302 // - The specialization shall be more specialized than the primary
4303 // template (14.5.5.2).
4305
4306 // C++ [temp.class.spec]p8: (DR1315)
4307 // - Each template-parameter shall appear at least once in the
4308 // template-id outside a non-deduced context.
4309 // C++1z [temp.class.spec.match]p3 (P0127R2)
4310 // If the template arguments of a partial specialization cannot be
4311 // deduced because of the structure of its template-parameter-list
4312 // and the template-id, the program is ill-formed.
4313 auto *TemplateParams = Partial->getTemplateParameters();
4314 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4315 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4316 TemplateParams->getDepth(), DeducibleParams);
4317
4318 if (!DeducibleParams.all()) {
4319 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4320 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4322 << (NumNonDeducible > 1)
4323 << SourceRange(Partial->getLocation(),
4324 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4325 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4326 }
4327}
4328
4333
4338
4340 // C++1z [temp.param]p11:
4341 // A template parameter of a deduction guide template that does not have a
4342 // default-argument shall be deducible from the parameter-type-list of the
4343 // deduction guide template.
4344 auto *TemplateParams = TD->getTemplateParameters();
4345 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4346 MarkDeducedTemplateParameters(TD, DeducibleParams);
4347 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4348 // A parameter pack is deducible (to an empty pack).
4349 auto *Param = TemplateParams->getParam(I);
4350 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4351 DeducibleParams[I] = true;
4352 }
4353
4354 if (!DeducibleParams.all()) {
4355 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4356 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4357 << (NumNonDeducible > 1);
4358 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4359 }
4360}
4361
4364 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4366 // D must be variable template id.
4368 "Variable template specialization is declared with a template id.");
4369
4370 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4371 TemplateArgumentListInfo TemplateArgs =
4372 makeTemplateArgumentListInfo(*this, *TemplateId);
4373 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4374 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4375 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4376
4377 TemplateName Name = TemplateId->Template.get();
4378
4379 // The template-id must name a variable template.
4381 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4382 if (!VarTemplate) {
4383 NamedDecl *FnTemplate;
4384 if (auto *OTS = Name.getAsOverloadedTemplate())
4385 FnTemplate = *OTS->begin();
4386 else
4387 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4388 if (FnTemplate)
4389 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4390 << FnTemplate->getDeclName();
4391 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4393 }
4394
4395 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4396 auto Message = DSA->getMessage();
4397 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4398 << VarTemplate << !Message.empty() << Message;
4399 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4400 }
4401
4402 // Check for unexpanded parameter packs in any of the template arguments.
4403 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4404 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4408 return true;
4409
4410 // Check that the template argument list is well-formed for this
4411 // template.
4413 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4414 /*DefaultArgs=*/{},
4415 /*PartialTemplateArgs=*/false, CTAI,
4416 /*UpdateArgsWithConversions=*/true))
4417 return true;
4418
4419 // Find the variable template (partial) specialization declaration that
4420 // corresponds to these arguments.
4423 TemplateArgs.size(),
4424 CTAI.CanonicalConverted))
4425 return true;
4426
4427 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4428 // we also do them during instantiation.
4429 if (!Name.isDependent() &&
4430 !TemplateSpecializationType::anyDependentTemplateArguments(
4431 TemplateArgs, CTAI.CanonicalConverted)) {
4432 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4433 << VarTemplate->getDeclName();
4435 }
4436
4437 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4438 TemplateParams, CTAI.CanonicalConverted) &&
4439 (!Context.getLangOpts().CPlusPlus20 ||
4440 !TemplateParams->hasAssociatedConstraints())) {
4441 // C++ [temp.class.spec]p9b3:
4442 //
4443 // -- The argument list of the specialization shall not be identical
4444 // to the implicit argument list of the primary template.
4445 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4446 << /*variable template*/ 1
4447 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4448 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4449 // FIXME: Recover from this by treating the declaration as a
4450 // redeclaration of the primary template.
4451 return true;
4452 }
4453 }
4454
4455 void *InsertPos = nullptr;
4456 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4457
4459 PrevDecl = VarTemplate->findPartialSpecialization(
4460 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4461 else
4462 PrevDecl =
4463 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4464
4466
4467 // Check whether we can declare a variable template specialization in
4468 // the current scope.
4469 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4470 TemplateNameLoc,
4472 return true;
4473
4474 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4475 // Since the only prior variable template specialization with these
4476 // arguments was referenced but not declared, reuse that
4477 // declaration node as our own, updating its source location and
4478 // the list of outer template parameters to reflect our new declaration.
4479 Specialization = PrevDecl;
4480 Specialization->setLocation(TemplateNameLoc);
4481 PrevDecl = nullptr;
4482 } else if (IsPartialSpecialization) {
4483 // Create a new class template partial specialization declaration node.
4485 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4488 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4489 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4490 SC, CTAI.CanonicalConverted);
4491 Partial->setTemplateArgsAsWritten(TemplateArgs);
4492
4493 if (!PrevPartial)
4494 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4495 Specialization = Partial;
4496
4497 // If we are providing an explicit specialization of a member variable
4498 // template specialization, make a note of that.
4499 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4500 PrevPartial->setMemberSpecialization();
4501
4503 } else {
4504 // Create a new class template specialization declaration node for
4505 // this explicit specialization or friend declaration.
4507 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4508 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4509 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4510
4511 if (!PrevDecl)
4512 VarTemplate->AddSpecialization(Specialization, InsertPos);
4513 }
4514
4515 // C++ [temp.expl.spec]p6:
4516 // If a template, a member template or the member of a class template is
4517 // explicitly specialized then that specialization shall be declared
4518 // before the first use of that specialization that would cause an implicit
4519 // instantiation to take place, in every translation unit in which such a
4520 // use occurs; no diagnostic is required.
4521 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4522 bool Okay = false;
4523 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4524 // Is there any previous explicit specialization declaration?
4526 Okay = true;
4527 break;
4528 }
4529 }
4530
4531 if (!Okay) {
4532 SourceRange Range(TemplateNameLoc, RAngleLoc);
4533 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4534 << Name << Range;
4535
4536 Diag(PrevDecl->getPointOfInstantiation(),
4537 diag::note_instantiation_required_here)
4538 << (PrevDecl->getTemplateSpecializationKind() !=
4540 return true;
4541 }
4542 }
4543
4544 Specialization->setLexicalDeclContext(CurContext);
4545
4546 // Add the specialization into its lexical context, so that it can
4547 // be seen when iterating through the list of declarations in that
4548 // context. However, specializations are not found by name lookup.
4549 CurContext->addDecl(Specialization);
4550
4551 // Note that this is an explicit specialization.
4552 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4553
4554 Previous.clear();
4555 if (PrevDecl)
4556 Previous.addDecl(PrevDecl);
4557 else if (Specialization->isStaticDataMember() &&
4558 Specialization->isOutOfLine())
4559 Specialization->setAccess(VarTemplate->getAccess());
4560
4561 return Specialization;
4562}
4563
4564namespace {
4565/// A partial specialization whose template arguments have matched
4566/// a given template-id.
4567struct PartialSpecMatchResult {
4570};
4571
4572// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4573// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4574static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4575 if (Var->getName() != "format_kind" ||
4576 !Var->getDeclContext()->isStdNamespace())
4577 return false;
4578
4579 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4580 // release in which users can access std::format_kind.
4581 // We can use 20250520 as the final date, see the following commits.
4582 // GCC releases/gcc-15 branch:
4583 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4584 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4585 // GCC master branch:
4586 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4587 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4588 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4589}
4590} // end anonymous namespace
4591
4594 SourceLocation TemplateNameLoc,
4595 const TemplateArgumentListInfo &TemplateArgs,
4596 bool SetWrittenArgs) {
4597 assert(Template && "A variable template id without template?");
4598
4599 // Check that the template argument list is well-formed for this template.
4602 Template, TemplateNameLoc,
4603 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4604 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4605 /*UpdateArgsWithConversions=*/true))
4606 return true;
4607
4608 // Produce a placeholder value if the specialization is dependent.
4609 if (Template->getDeclContext()->isDependentContext() ||
4610 TemplateSpecializationType::anyDependentTemplateArguments(
4611 TemplateArgs, CTAI.CanonicalConverted)) {
4612 if (ParsingInitForAutoVars.empty())
4613 return DeclResult();
4614
4615 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4616 const TemplateArgument &Arg2) {
4617 return Context.isSameTemplateArgument(Arg1, Arg2);
4618 };
4619
4620 if (VarDecl *Var = Template->getTemplatedDecl();
4621 ParsingInitForAutoVars.count(Var) &&
4622 // See comments on this function definition
4623 !IsLibstdcxxStdFormatKind(PP, Var) &&
4624 llvm::equal(
4625 CTAI.CanonicalConverted,
4626 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4627 IsSameTemplateArg)) {
4628 Diag(TemplateNameLoc,
4629 diag::err_auto_variable_cannot_appear_in_own_initializer)
4630 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4631 return true;
4632 }
4633
4635 Template->getPartialSpecializations(PartialSpecs);
4636 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4637 if (ParsingInitForAutoVars.count(Partial) &&
4638 llvm::equal(CTAI.CanonicalConverted,
4639 Partial->getTemplateArgs().asArray(),
4640 IsSameTemplateArg)) {
4641 Diag(TemplateNameLoc,
4642 diag::err_auto_variable_cannot_appear_in_own_initializer)
4643 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4644 << Partial->getType();
4645 return true;
4646 }
4647
4648 return DeclResult();
4649 }
4650
4651 // Find the variable template specialization declaration that
4652 // corresponds to these arguments.
4653 void *InsertPos = nullptr;
4655 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4656 checkSpecializationReachability(TemplateNameLoc, Spec);
4657 if (Spec->getType()->isUndeducedType()) {
4658 if (ParsingInitForAutoVars.count(Spec))
4659 Diag(TemplateNameLoc,
4660 diag::err_auto_variable_cannot_appear_in_own_initializer)
4661 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4662 << Spec->getType();
4663 else
4664 // We are substituting the initializer of this variable template
4665 // specialization.
4666 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4667 << Spec << Spec->getType();
4668
4669 return true;
4670 }
4671 // If we already have a variable template specialization, return it.
4672 return Spec;
4673 }
4674
4675 // This is the first time we have referenced this variable template
4676 // specialization. Create the canonical declaration and add it to
4677 // the set of specializations, based on the closest partial specialization
4678 // that it represents. That is,
4679 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4680 const TemplateArgumentList *PartialSpecArgs = nullptr;
4681 bool AmbiguousPartialSpec = false;
4682 typedef PartialSpecMatchResult MatchResult;
4684 SourceLocation PointOfInstantiation = TemplateNameLoc;
4685 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4686 /*ForTakingAddress=*/false);
4687
4688 // 1. Attempt to find the closest partial specialization that this
4689 // specializes, if any.
4690 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4691 // Perhaps better after unification of DeduceTemplateArguments() and
4692 // getMoreSpecializedPartialSpecialization().
4694 Template->getPartialSpecializations(PartialSpecs);
4695
4696 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4697 // C++ [temp.spec.partial.member]p2:
4698 // If the primary member template is explicitly specialized for a given
4699 // (implicit) specialization of the enclosing class template, the partial
4700 // specializations of the member template are ignored for this
4701 // specialization of the enclosing class template. If a partial
4702 // specialization of the member template is explicitly specialized for a
4703 // given (implicit) specialization of the enclosing class template, the
4704 // primary member template and its other partial specializations are still
4705 // considered for this specialization of the enclosing class template.
4706 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4707 !Partial->getMostRecentDecl()->isMemberSpecialization())
4708 continue;
4709
4710 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4711
4713 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4715 // Store the failed-deduction information for use in diagnostics, later.
4716 // TODO: Actually use the failed-deduction info?
4717 FailedCandidates.addCandidate().set(
4720 (void)Result;
4721 } else {
4722 Matched.push_back(PartialSpecMatchResult());
4723 Matched.back().Partial = Partial;
4724 Matched.back().Args = Info.takeSugared();
4725 }
4726 }
4727
4728 if (Matched.size() >= 1) {
4729 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4730 if (Matched.size() == 1) {
4731 // -- If exactly one matching specialization is found, the
4732 // instantiation is generated from that specialization.
4733 // We don't need to do anything for this.
4734 } else {
4735 // -- If more than one matching specialization is found, the
4736 // partial order rules (14.5.4.2) are used to determine
4737 // whether one of the specializations is more specialized
4738 // than the others. If none of the specializations is more
4739 // specialized than all of the other matching
4740 // specializations, then the use of the variable template is
4741 // ambiguous and the program is ill-formed.
4742 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4743 PEnd = Matched.end();
4744 P != PEnd; ++P) {
4745 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4746 PointOfInstantiation) ==
4747 P->Partial)
4748 Best = P;
4749 }
4750
4751 // Determine if the best partial specialization is more specialized than
4752 // the others.
4753 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4754 PEnd = Matched.end();
4755 P != PEnd; ++P) {
4757 P->Partial, Best->Partial,
4758 PointOfInstantiation) != Best->Partial) {
4759 AmbiguousPartialSpec = true;
4760 break;
4761 }
4762 }
4763 }
4764
4765 // Instantiate using the best variable template partial specialization.
4766 InstantiationPattern = Best->Partial;
4767 PartialSpecArgs = Best->Args;
4768 } else {
4769 // -- If no match is found, the instantiation is generated
4770 // from the primary template.
4771 // InstantiationPattern = Template->getTemplatedDecl();
4772 }
4773
4774 // 2. Create the canonical declaration.
4775 // Note that we do not instantiate a definition until we see an odr-use
4776 // in DoMarkVarDeclReferenced().
4777 // FIXME: LateAttrs et al.?
4778 if (AmbiguousPartialSpec) {
4779 // Partial ordering did not produce a clear winner. Complain.
4780 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4781 << Template;
4782 // Print the matching partial specializations.
4783 for (MatchResult P : Matched)
4784 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4785 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4786 *P.Args);
4787 return true;
4788 }
4789
4791 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4792 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4793 if (!Decl)
4794 return true;
4795 if (SetWrittenArgs)
4796 Decl->setTemplateArgsAsWritten(TemplateArgs);
4797
4799 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4800 Decl->setInstantiationOf(D, PartialSpecArgs);
4801
4802 checkSpecializationReachability(TemplateNameLoc, Decl);
4803
4804 assert(Decl && "No variable template specialization?");
4805 return Decl;
4806}
4807
4809 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4810 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4811 const TemplateArgumentListInfo *TemplateArgs) {
4812
4813 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4814 *TemplateArgs, /*SetWrittenArgs=*/false);
4815 if (Decl.isInvalid())
4816 return ExprError();
4817
4818 if (!Decl.get())
4819 return ExprResult();
4820
4821 VarDecl *Var = cast<VarDecl>(Decl.get());
4824 NameInfo.getLoc());
4825
4826 // Build an ordinary singleton decl ref.
4827 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4828}
4829
4831 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4833 const TemplateArgumentListInfo *TemplateArgs) {
4834 assert(Template && "A variable template id without template?");
4835
4836 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4837 Template->templateParameterKind() !=
4839 return ExprResult();
4840
4841 // Check that the template argument list is well-formed for this template.
4844 Template, TemplateLoc,
4845 // FIXME: TemplateArgs will not be modified because
4846 // UpdateArgsWithConversions is false, however, we should
4847 // CheckTemplateArgumentList to be const-correct.
4848 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4849 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4850 /*UpdateArgsWithConversions=*/false))
4851 return true;
4852
4854 R.addDecl(Template);
4855
4856 // FIXME: We model references to variable template and concept parameters
4857 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4858 // data, can generally be used in the same places and work the same way.
4859 // However, it might be cleaner to use a dedicated AST node in the long run.
4862 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4863 /*KnownDependent=*/false,
4864 /*KnownInstantiationDependent=*/false);
4865}
4866
4868 SourceLocation Loc) {
4869 Diag(Loc, diag::err_template_missing_args)
4870 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4871 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4872 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4873 }
4874}
4875
4877 bool TemplateKeyword,
4878 TemplateDecl *TD,
4879 SourceLocation Loc) {
4880 TemplateName Name = Context.getQualifiedTemplateName(
4881 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4883}
4884
4886 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4887 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4888 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4889 bool DoCheckConstraintSatisfaction) {
4890 assert(NamedConcept && "A concept template id without a template?");
4891
4892 if (NamedConcept->isInvalidDecl())
4893 return ExprError();
4894
4897 NamedConcept, ConceptNameInfo.getLoc(),
4898 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4899 /*DefaultArgs=*/{},
4900 /*PartialTemplateArgs=*/false, CTAI,
4901 /*UpdateArgsWithConversions=*/false))
4902 return ExprError();
4903
4904 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4905
4906 // There's a bug with CTAI.CanonicalConverted.
4907 // If the template argument contains a DependentDecltypeType that includes a
4908 // TypeAliasType, and the same written type had occurred previously in the
4909 // source, then the DependentDecltypeType would be canonicalized to that
4910 // previous type which would mess up the substitution.
4911 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4913 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4914 CTAI.SugaredConverted);
4915 ConstraintSatisfaction Satisfaction;
4916 bool AreArgsDependent =
4917 TemplateSpecializationType::anyDependentTemplateArguments(
4918 *TemplateArgs, CTAI.SugaredConverted);
4919 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4920 /*Final=*/false);
4922 Context,
4924 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4926
4927 bool Error = false;
4928 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4929 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4930 DoCheckConstraintSatisfaction) {
4931
4933
4936
4938 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4939 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4940 TemplateArgs->getRAngleLoc()),
4941 Satisfaction, CL);
4942 Satisfaction.ContainsErrors = Error;
4943 }
4944
4945 if (Error)
4946 return ExprError();
4947
4949 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4950}
4951
4953 SourceLocation TemplateKWLoc,
4954 LookupResult &R,
4955 bool RequiresADL,
4956 const TemplateArgumentListInfo *TemplateArgs) {
4957 // FIXME: Can we do any checking at this point? I guess we could check the
4958 // template arguments that we have against the template name, if the template
4959 // name refers to a single template. That's not a terribly common case,
4960 // though.
4961 // foo<int> could identify a single function unambiguously
4962 // This approach does NOT work, since f<int>(1);
4963 // gets resolved prior to resorting to overload resolution
4964 // i.e., template<class T> void f(double);
4965 // vs template<class T, class U> void f(U);
4966
4967 // These should be filtered out by our callers.
4968 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4969
4970 // Non-function templates require a template argument list.
4971 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4972 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4974 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4975 return ExprError();
4976 }
4977 }
4978 bool KnownDependent = false;
4979 // In C++1y, check variable template ids.
4980 if (R.getAsSingle<VarTemplateDecl>()) {
4982 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4983 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4984 if (Res.isInvalid() || Res.isUsable())
4985 return Res;
4986 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4987 KnownDependent = true;
4988 }
4989
4990 // We don't want lookup warnings at this point.
4991 R.suppressDiagnostics();
4992
4993 if (R.getAsSingle<ConceptDecl>()) {
4994 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4995 R.getRepresentativeDecl(),
4996 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4997 }
4998
4999 // Check variable template ids (C++17) and concept template parameters
5000 // (C++26).
5002 if (R.getAsSingle<TemplateTemplateParmDecl>())
5004 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
5005 TemplateKWLoc, TemplateArgs);
5006
5007 // Function templates
5009 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5010 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5011 R.begin(), R.end(), KnownDependent,
5012 /*KnownInstantiationDependent=*/false);
5013 // Model the templates with UnresolvedTemplateTy. The expression should then
5014 // either be transformed in an instantiation or be diagnosed in
5015 // CheckPlaceholderExpr.
5016 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5017 !R.getFoundDecl()->getAsFunction())
5018 ULE->setType(Context.UnresolvedTemplateTy);
5019
5020 return ULE;
5021}
5022
5024 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5025 const DeclarationNameInfo &NameInfo,
5026 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5027 assert(TemplateArgs || TemplateKWLoc.isValid());
5028
5029 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5030 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5031 /*EnteringContext=*/false, TemplateKWLoc))
5032 return ExprError();
5033
5034 if (R.isAmbiguous())
5035 return ExprError();
5036
5037 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5038 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5039
5040 if (R.empty()) {
5042 Diag(NameInfo.getLoc(), diag::err_no_member)
5043 << NameInfo.getName() << DC << SS.getRange();
5044 return ExprError();
5045 }
5046
5047 // If necessary, build an implicit class member access.
5048 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5049 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5050 /*S=*/nullptr);
5051
5052 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5053}
5054
5056 CXXScopeSpec &SS,
5057 SourceLocation TemplateKWLoc,
5058 const UnqualifiedId &Name,
5059 ParsedType ObjectType,
5060 bool EnteringContext,
5062 bool AllowInjectedClassName) {
5063 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5064 Diag(TemplateKWLoc,
5066 diag::warn_cxx98_compat_template_outside_of_template :
5067 diag::ext_template_outside_of_template)
5068 << FixItHint::CreateRemoval(TemplateKWLoc);
5069
5070 if (SS.isInvalid())
5071 return TNK_Non_template;
5072
5073 // Figure out where isTemplateName is going to look.
5074 DeclContext *LookupCtx = nullptr;
5075 if (SS.isNotEmpty())
5076 LookupCtx = computeDeclContext(SS, EnteringContext);
5077 else if (ObjectType)
5078 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5079
5080 // C++0x [temp.names]p5:
5081 // If a name prefixed by the keyword template is not the name of
5082 // a template, the program is ill-formed. [Note: the keyword
5083 // template may not be applied to non-template members of class
5084 // templates. -end note ] [ Note: as is the case with the
5085 // typename prefix, the template prefix is allowed in cases
5086 // where it is not strictly necessary; i.e., when the
5087 // nested-name-specifier or the expression on the left of the ->
5088 // or . is not dependent on a template-parameter, or the use
5089 // does not appear in the scope of a template. -end note]
5090 //
5091 // Note: C++03 was more strict here, because it banned the use of
5092 // the "template" keyword prior to a template-name that was not a
5093 // dependent name. C++ DR468 relaxed this requirement (the
5094 // "template" keyword is now permitted). We follow the C++0x
5095 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5096 bool MemberOfUnknownSpecialization;
5097 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5098 ObjectType, EnteringContext, Result,
5099 MemberOfUnknownSpecialization);
5100 if (TNK != TNK_Non_template) {
5101 // We resolved this to a (non-dependent) template name. Return it.
5102 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5103 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5105 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5106 // C++14 [class.qual]p2:
5107 // In a lookup in which function names are not ignored and the
5108 // nested-name-specifier nominates a class C, if the name specified
5109 // [...] is the injected-class-name of C, [...] the name is instead
5110 // considered to name the constructor
5111 //
5112 // We don't get here if naming the constructor would be valid, so we
5113 // just reject immediately and recover by treating the
5114 // injected-class-name as naming the template.
5115 Diag(Name.getBeginLoc(),
5116 diag::ext_out_of_line_qualified_id_type_names_constructor)
5117 << Name.Identifier
5118 << 0 /*injected-class-name used as template name*/
5119 << TemplateKWLoc.isValid();
5120 }
5121 return TNK;
5122 }
5123
5124 if (!MemberOfUnknownSpecialization) {
5125 // Didn't find a template name, and the lookup wasn't dependent.
5126 // Do the lookup again to determine if this is a "nothing found" case or
5127 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5128 // need to do this.
5130 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5132 // Tell LookupTemplateName that we require a template so that it diagnoses
5133 // cases where it finds a non-template.
5134 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5135 ? RequiredTemplateKind(TemplateKWLoc)
5137 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5138 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5139 !R.isAmbiguous()) {
5140 if (LookupCtx)
5141 Diag(Name.getBeginLoc(), diag::err_no_member)
5142 << DNI.getName() << LookupCtx << SS.getRange();
5143 else
5144 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5145 << DNI.getName() << SS.getRange();
5146 }
5147 return TNK_Non_template;
5148 }
5149
5150 NestedNameSpecifier Qualifier = SS.getScopeRep();
5151
5152 switch (Name.getKind()) {
5154 Result = TemplateTy::make(Context.getDependentTemplateName(
5155 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5157
5159 Result = TemplateTy::make(Context.getDependentTemplateName(
5160 {Qualifier, Name.OperatorFunctionId.Operator,
5161 TemplateKWLoc.isValid()}));
5162 return TNK_Function_template;
5163
5165 // This is a kind of template name, but can never occur in a dependent
5166 // scope (literal operators can only be declared at namespace scope).
5167 break;
5168
5169 default:
5170 break;
5171 }
5172
5173 // This name cannot possibly name a dependent template. Diagnose this now
5174 // rather than building a dependent template name that can never be valid.
5175 Diag(Name.getBeginLoc(),
5176 diag::err_template_kw_refers_to_dependent_non_template)
5178 << TemplateKWLoc.isValid() << TemplateKWLoc;
5179 return TNK_Non_template;
5180}
5181
5184 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5185 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5186 const TemplateArgument &Arg = AL.getArgument();
5188 TypeSourceInfo *TSI = nullptr;
5189
5190 // Check template type parameter.
5191 switch(Arg.getKind()) {
5193 // C++ [temp.arg.type]p1:
5194 // A template-argument for a template-parameter which is a
5195 // type shall be a type-id.
5196 ArgType = Arg.getAsType();
5197 TSI = AL.getTypeSourceInfo();
5198 break;
5201 // We have a template type parameter but the template argument
5202 // is a template without any arguments.
5203 SourceRange SR = AL.getSourceRange();
5206 return true;
5207 }
5209 // We have a template type parameter but the template argument is an
5210 // expression; see if maybe it is missing the "typename" keyword.
5211 CXXScopeSpec SS;
5212 DeclarationNameInfo NameInfo;
5213
5214 if (DependentScopeDeclRefExpr *ArgExpr =
5215 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5216 SS.Adopt(ArgExpr->getQualifierLoc());
5217 NameInfo = ArgExpr->getNameInfo();
5218 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5219 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5220 if (ArgExpr->isImplicitAccess()) {
5221 SS.Adopt(ArgExpr->getQualifierLoc());
5222 NameInfo = ArgExpr->getMemberNameInfo();
5223 }
5224 }
5225
5226 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5227 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5228 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5229
5230 if (Result.getAsSingle<TypeDecl>() ||
5231 Result.wasNotFoundInCurrentInstantiation()) {
5232 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5233 // Suggest that the user add 'typename' before the NNS.
5235 Diag(Loc, getLangOpts().MSVCCompat
5236 ? diag::ext_ms_template_type_arg_missing_typename
5237 : diag::err_template_arg_must_be_type_suggest)
5238 << FixItHint::CreateInsertion(Loc, "typename ");
5240
5241 // Recover by synthesizing a type using the location information that we
5242 // already have.
5243 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5244 SS.getScopeRep(), II);
5245 TypeLocBuilder TLB;
5247 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5249 TL.setNameLoc(NameInfo.getLoc());
5250 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5251
5252 // Overwrite our input TemplateArgumentLoc so that we can recover
5253 // properly.
5256
5257 break;
5258 }
5259 }
5260 // fallthrough
5261 [[fallthrough]];
5262 }
5263 default: {
5264 // We allow instantiating a template with template argument packs when
5265 // building deduction guides or mapping constraint template parameters.
5266 if (Arg.getKind() == TemplateArgument::Pack &&
5267 (CodeSynthesisContexts.back().Kind ==
5270 SugaredConverted.push_back(Arg);
5271 CanonicalConverted.push_back(Arg);
5272 return false;
5273 }
5274 // We have a template type parameter but the template argument
5275 // is not a type.
5276 SourceRange SR = AL.getSourceRange();
5277 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5279
5280 return true;
5281 }
5282 }
5283
5284 if (CheckTemplateArgument(TSI))
5285 return true;
5286
5287 // Objective-C ARC:
5288 // If an explicitly-specified template argument type is a lifetime type
5289 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5290 if (getLangOpts().ObjCAutoRefCount &&
5291 ArgType->isObjCLifetimeType() &&
5292 !ArgType.getObjCLifetime()) {
5293 Qualifiers Qs;
5295 ArgType = Context.getQualifiedType(ArgType, Qs);
5296 }
5297
5298 SugaredConverted.push_back(TemplateArgument(ArgType));
5299 CanonicalConverted.push_back(
5300 TemplateArgument(Context.getCanonicalType(ArgType)));
5301 return false;
5302}
5303
5304/// Substitute template arguments into the default template argument for
5305/// the given template type parameter.
5306///
5307/// \param SemaRef the semantic analysis object for which we are performing
5308/// the substitution.
5309///
5310/// \param Template the template that we are synthesizing template arguments
5311/// for.
5312///
5313/// \param TemplateLoc the location of the template name that started the
5314/// template-id we are checking.
5315///
5316/// \param RAngleLoc the location of the right angle bracket ('>') that
5317/// terminates the template-id.
5318///
5319/// \param Param the template template parameter whose default we are
5320/// substituting into.
5321///
5322/// \param Converted the list of template arguments provided for template
5323/// parameters that precede \p Param in the template parameter list.
5324///
5325/// \param Output the resulting substituted template argument.
5326///
5327/// \returns true if an error occurred.
5329 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5330 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5331 ArrayRef<TemplateArgument> SugaredConverted,
5332 ArrayRef<TemplateArgument> CanonicalConverted,
5333 TemplateArgumentLoc &Output) {
5334 Output = Param->getDefaultArgument();
5335
5336 // If the argument type is dependent, instantiate it now based
5337 // on the previously-computed template arguments.
5338 if (Output.getArgument().isInstantiationDependent()) {
5339 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5340 SugaredConverted,
5341 SourceRange(TemplateLoc, RAngleLoc));
5342 if (Inst.isInvalid())
5343 return true;
5344
5345 // Only substitute for the innermost template argument list.
5346 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5347 /*Final=*/true);
5348 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5349 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5350
5351 bool ForLambdaCallOperator = false;
5352 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5353 ForLambdaCallOperator = Rec->isLambda();
5354 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5355 !ForLambdaCallOperator);
5356
5357 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5358 Param->getDefaultArgumentLoc(),
5359 Param->getDeclName()))
5360 return true;
5361 }
5362
5363 return false;
5364}
5365
5366/// Substitute template arguments into the default template argument for
5367/// the given non-type template parameter.
5368///
5369/// \param SemaRef the semantic analysis object for which we are performing
5370/// the substitution.
5371///
5372/// \param Template the template that we are synthesizing template arguments
5373/// for.
5374///
5375/// \param TemplateLoc the location of the template name that started the
5376/// template-id we are checking.
5377///
5378/// \param RAngleLoc the location of the right angle bracket ('>') that
5379/// terminates the template-id.
5380///
5381/// \param Param the non-type template parameter whose default we are
5382/// substituting into.
5383///
5384/// \param Converted the list of template arguments provided for template
5385/// parameters that precede \p Param in the template parameter list.
5386///
5387/// \returns the substituted template argument, or NULL if an error occurred.
5389 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5390 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5391 ArrayRef<TemplateArgument> SugaredConverted,
5392 ArrayRef<TemplateArgument> CanonicalConverted,
5393 TemplateArgumentLoc &Output) {
5394 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5395 SugaredConverted,
5396 SourceRange(TemplateLoc, RAngleLoc));
5397 if (Inst.isInvalid())
5398 return true;
5399
5400 // Only substitute for the innermost template argument list.
5401 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5402 /*Final=*/true);
5403 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5404 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5405
5406 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5407 EnterExpressionEvaluationContext ConstantEvaluated(
5409 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5410 TemplateArgLists, Output);
5411}
5412
5413/// Substitute template arguments into the default template argument for
5414/// the given template template parameter.
5415///
5416/// \param SemaRef the semantic analysis object for which we are performing
5417/// the substitution.
5418///
5419/// \param Template the template that we are synthesizing template arguments
5420/// for.
5421///
5422/// \param TemplateLoc the location of the template name that started the
5423/// template-id we are checking.
5424///
5425/// \param RAngleLoc the location of the right angle bracket ('>') that
5426/// terminates the template-id.
5427///
5428/// \param Param the template template parameter whose default we are
5429/// substituting into.
5430///
5431/// \param Converted the list of template arguments provided for template
5432/// parameters that precede \p Param in the template parameter list.
5433///
5434/// \param QualifierLoc Will be set to the nested-name-specifier (with
5435/// source-location information) that precedes the template name.
5436///
5437/// \returns the substituted template argument, or NULL if an error occurred.
5439 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5440 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5442 ArrayRef<TemplateArgument> SugaredConverted,
5443 ArrayRef<TemplateArgument> CanonicalConverted,
5444 NestedNameSpecifierLoc &QualifierLoc) {
5446 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5447 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5448 if (Inst.isInvalid())
5449 return TemplateName();
5450
5451 // Only substitute for the innermost template argument list.
5452 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5453 /*Final=*/true);
5454 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5455 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5456
5457 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5458
5459 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5460 QualifierLoc = A.getTemplateQualifierLoc();
5461 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5463 A.getTemplateNameLoc(), TemplateArgLists);
5464}
5465
5467 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5468 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5469 ArrayRef<TemplateArgument> SugaredConverted,
5470 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5471 HasDefaultArg = false;
5472
5473 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5474 if (!hasReachableDefaultArgument(TypeParm))
5475 return TemplateArgumentLoc();
5476
5477 HasDefaultArg = true;
5478 TemplateArgumentLoc Output;
5479 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5480 RAngleLoc, TypeParm, SugaredConverted,
5481 CanonicalConverted, Output))
5482 return TemplateArgumentLoc();
5483 return Output;
5484 }
5485
5486 if (NonTypeTemplateParmDecl *NonTypeParm
5487 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5488 if (!hasReachableDefaultArgument(NonTypeParm))
5489 return TemplateArgumentLoc();
5490
5491 HasDefaultArg = true;
5492 TemplateArgumentLoc Output;
5493 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5494 RAngleLoc, NonTypeParm, SugaredConverted,
5495 CanonicalConverted, Output))
5496 return TemplateArgumentLoc();
5497 return Output;
5498 }
5499
5500 TemplateTemplateParmDecl *TempTempParm
5502 if (!hasReachableDefaultArgument(TempTempParm))
5503 return TemplateArgumentLoc();
5504
5505 HasDefaultArg = true;
5506 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5507 NestedNameSpecifierLoc QualifierLoc;
5509 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5510 SugaredConverted, CanonicalConverted, QualifierLoc);
5511 if (TName.isNull())
5512 return TemplateArgumentLoc();
5513
5514 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5515 QualifierLoc, A.getTemplateNameLoc());
5516}
5517
5518/// Convert a template-argument that we parsed as a type into a template, if
5519/// possible. C++ permits injected-class-names to perform dual service as
5520/// template template arguments and as template type arguments.
5523 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5524 if (!TagLoc)
5525 return TemplateArgumentLoc();
5526
5527 // If this type was written as an injected-class-name, it can be used as a
5528 // template template argument.
5529 // If this type was written as an injected-class-name, it may have been
5530 // converted to a RecordType during instantiation. If the RecordType is
5531 // *not* wrapped in a TemplateSpecializationType and denotes a class
5532 // template specialization, it must have come from an injected-class-name.
5533
5534 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5535 if (Name.isNull())
5536 return TemplateArgumentLoc();
5537
5538 return TemplateArgumentLoc(Context, Name,
5539 /*TemplateKWLoc=*/SourceLocation(),
5540 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5541}
5542
5545 SourceLocation TemplateLoc,
5546 SourceLocation RAngleLoc,
5547 unsigned ArgumentPackIndex,
5550 // Check template type parameters.
5551 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5552 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5553 CTAI.CanonicalConverted);
5554
5555 const TemplateArgument &Arg = ArgLoc.getArgument();
5556 // Check non-type template parameters.
5557 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5558 // Do substitution on the type of the non-type template parameter
5559 // with the template arguments we've seen thus far. But if the
5560 // template has a dependent context then we cannot substitute yet.
5561 QualType NTTPType = NTTP->getType();
5562 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5563 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5564
5565 if (NTTPType->isInstantiationDependentType()) {
5566 // Do substitution on the type of the non-type template parameter.
5567 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5568 CTAI.SugaredConverted,
5569 SourceRange(TemplateLoc, RAngleLoc));
5570 if (Inst.isInvalid())
5571 return true;
5572
5574 /*Final=*/true);
5575 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5576 // If the parameter is a pack expansion, expand this slice of the pack.
5577 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5578 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5579 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5580 NTTP->getDeclName());
5581 } else {
5582 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5583 NTTP->getDeclName());
5584 }
5585
5586 // If that worked, check the non-type template parameter type
5587 // for validity.
5588 if (!NTTPType.isNull())
5589 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5590 NTTP->getLocation());
5591 if (NTTPType.isNull())
5592 return true;
5593 }
5594
5595 auto checkExpr = [&](Expr *E) -> Expr * {
5596 TemplateArgument SugaredResult, CanonicalResult;
5598 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5599 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5600 // If the current template argument causes an error, give up now.
5601 if (Res.isInvalid())
5602 return nullptr;
5603 CTAI.SugaredConverted.push_back(SugaredResult);
5604 CTAI.CanonicalConverted.push_back(CanonicalResult);
5605 return Res.get();
5606 };
5607
5608 switch (Arg.getKind()) {
5610 llvm_unreachable("Should never see a NULL template argument here");
5611
5613 Expr *E = Arg.getAsExpr();
5614 Expr *R = checkExpr(E);
5615 if (!R)
5616 return true;
5617 // If the resulting expression is new, then use it in place of the
5618 // old expression in the template argument.
5619 if (R != E) {
5620 TemplateArgument TA(R, /*IsCanonical=*/false);
5621 ArgLoc = TemplateArgumentLoc(TA, R);
5622 }
5623 break;
5624 }
5625
5626 // As for the converted NTTP kinds, they still might need another
5627 // conversion, as the new corresponding parameter might be different.
5628 // Ideally, we would always perform substitution starting with sugared types
5629 // and never need these, as we would still have expressions. Since these are
5630 // needed so rarely, it's probably a better tradeoff to just convert them
5631 // back to expressions.
5636 // FIXME: StructuralValue is untested here.
5637 ExprResult R =
5639 assert(R.isUsable());
5640 if (!checkExpr(R.get()))
5641 return true;
5642 break;
5643 }
5644
5647 // We were given a template template argument. It may not be ill-formed;
5648 // see below.
5651 // We have a template argument such as \c T::template X, which we
5652 // parsed as a template template argument. However, since we now
5653 // know that we need a non-type template argument, convert this
5654 // template name into an expression.
5655
5656 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5657 ArgLoc.getTemplateNameLoc());
5658
5659 CXXScopeSpec SS;
5660 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5661 // FIXME: the template-template arg was a DependentTemplateName,
5662 // so it was provided with a template keyword. However, its source
5663 // location is not stored in the template argument structure.
5664 SourceLocation TemplateKWLoc;
5666 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5667 nullptr);
5668
5669 // If we parsed the template argument as a pack expansion, create a
5670 // pack expansion expression.
5673 if (E.isInvalid())
5674 return true;
5675 }
5676
5677 TemplateArgument SugaredResult, CanonicalResult;
5679 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5680 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5681 if (E.isInvalid())
5682 return true;
5683
5684 CTAI.SugaredConverted.push_back(SugaredResult);
5685 CTAI.CanonicalConverted.push_back(CanonicalResult);
5686 break;
5687 }
5688
5689 // We have a template argument that actually does refer to a class
5690 // template, alias template, or template template parameter, and
5691 // therefore cannot be a non-type template argument.
5692 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5693 << ArgLoc.getSourceRange();
5695
5696 return true;
5697
5699 // We have a non-type template parameter but the template
5700 // argument is a type.
5701
5702 // C++ [temp.arg]p2:
5703 // In a template-argument, an ambiguity between a type-id and
5704 // an expression is resolved to a type-id, regardless of the
5705 // form of the corresponding template-parameter.
5706 //
5707 // We warn specifically about this case, since it can be rather
5708 // confusing for users.
5709 QualType T = Arg.getAsType();
5710 SourceRange SR = ArgLoc.getSourceRange();
5711 if (T->isFunctionType())
5712 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5713 else
5714 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5716 return true;
5717 }
5718
5720 llvm_unreachable("Caller must expand template argument packs");
5721 }
5722
5723 return false;
5724 }
5725
5726
5727 // Check template template parameters.
5729
5730 TemplateParameterList *Params = TempParm->getTemplateParameters();
5731 if (TempParm->isExpandedParameterPack())
5732 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5733
5734 // Substitute into the template parameter list of the template
5735 // template parameter, since previously-supplied template arguments
5736 // may appear within the template template parameter.
5737 //
5738 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5739 {
5740 // Set up a template instantiation context.
5742 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5743 CTAI.SugaredConverted,
5744 SourceRange(TemplateLoc, RAngleLoc));
5745 if (Inst.isInvalid())
5746 return true;
5747
5748 Params = SubstTemplateParams(
5749 Params, CurContext,
5751 /*Final=*/true),
5752 /*EvaluateConstraints=*/false);
5753 if (!Params)
5754 return true;
5755 }
5756
5757 // C++1z [temp.local]p1: (DR1004)
5758 // When [the injected-class-name] is used [...] as a template-argument for
5759 // a template template-parameter [...] it refers to the class template
5760 // itself.
5761 if (Arg.getKind() == TemplateArgument::Type) {
5763 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5764 if (!ConvertedArg.getArgument().isNull())
5765 ArgLoc = ConvertedArg;
5766 }
5767
5768 switch (Arg.getKind()) {
5770 llvm_unreachable("Should never see a NULL template argument here");
5771
5774 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5775 CTAI.PartialOrdering,
5776 &CTAI.StrictPackMatch))
5777 return true;
5778
5779 CTAI.SugaredConverted.push_back(Arg);
5780 CTAI.CanonicalConverted.push_back(
5781 Context.getCanonicalTemplateArgument(Arg));
5782 break;
5783
5786 auto Kind = 0;
5787 switch (TempParm->templateParameterKind()) {
5789 Kind = 1;
5790 break;
5792 Kind = 2;
5793 break;
5794 default:
5795 break;
5796 }
5797
5798 // We have a template template parameter but the template
5799 // argument does not refer to a template.
5800 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5801 << Kind << getLangOpts().CPlusPlus11;
5802 return true;
5803 }
5804
5809 llvm_unreachable("non-type argument with template template parameter");
5810
5812 llvm_unreachable("Caller must expand template argument packs");
5813 }
5814
5815 return false;
5816}
5817
5818/// Diagnose a missing template argument.
5819template<typename TemplateParmDecl>
5821 TemplateDecl *TD,
5822 const TemplateParmDecl *D,
5824 // Dig out the most recent declaration of the template parameter; there may be
5825 // declarations of the template that are more recent than TD.
5827 ->getTemplateParameters()
5828 ->getParam(D->getIndex()));
5829
5830 // If there's a default argument that's not reachable, diagnose that we're
5831 // missing a module import.
5833 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5835 D->getDefaultArgumentLoc(), Modules,
5837 /*Recover*/true);
5838 return true;
5839 }
5840
5841 // FIXME: If there's a more recent default argument that *is* visible,
5842 // diagnose that it was declared too late.
5843
5845
5846 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5847 << /*not enough args*/0
5849 << TD;
5850 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5851 return true;
5852}
5853
5854/// Check that the given template argument list is well-formed
5855/// for specializing the given template.
5857 TemplateDecl *Template, SourceLocation TemplateLoc,
5858 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5859 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5860 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5862 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5863 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5865}
5866
5867/// Check that the given template argument list is well-formed
5868/// for specializing the given template.
5871 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5872 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5873 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5875
5877 *ConstraintsNotSatisfied = false;
5878
5879 // Make a copy of the template arguments for processing. Only make the
5880 // changes at the end when successful in matching the arguments to the
5881 // template.
5882 TemplateArgumentListInfo NewArgs = TemplateArgs;
5883
5884 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5885
5886 // C++23 [temp.arg.general]p1:
5887 // [...] The type and form of each template-argument specified in
5888 // a template-id shall match the type and form specified for the
5889 // corresponding parameter declared by the template in its
5890 // template-parameter-list.
5891 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5892 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5893 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5894 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5895 LocalInstantiationScope InstScope(*this, true);
5896 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5897 ParamEnd = Params->end(),
5898 Param = ParamBegin;
5899 Param != ParamEnd;
5900 /* increment in loop */) {
5901 if (size_t ParamIdx = Param - ParamBegin;
5902 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5903 // All written arguments should have been consumed by this point.
5904 assert(ArgIdx == NumArgs && "bad default argument deduction");
5905 if (ParamIdx == DefaultArgs.StartPos) {
5906 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5907 // Default arguments from a DeducedTemplateName are already converted.
5908 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5909 CTAI.SugaredConverted.push_back(DefArg);
5910 CTAI.CanonicalConverted.push_back(
5911 Context.getCanonicalTemplateArgument(DefArg));
5912 ++Param;
5913 }
5914 continue;
5915 }
5916 }
5917
5918 // If we have an expanded parameter pack, make sure we don't have too
5919 // many arguments.
5920 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5921 if (*Expansions == SugaredArgumentPack.size()) {
5922 // We're done with this parameter pack. Pack up its arguments and add
5923 // them to the list.
5924 CTAI.SugaredConverted.push_back(
5925 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5926 SugaredArgumentPack.clear();
5927
5928 CTAI.CanonicalConverted.push_back(
5929 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5930 CanonicalArgumentPack.clear();
5931
5932 // This argument is assigned to the next parameter.
5933 ++Param;
5934 continue;
5935 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5936 // Not enough arguments for this parameter pack.
5937 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5938 << /*not enough args*/0
5940 << Template;
5942 return true;
5943 }
5944 }
5945
5946 // Check for builtins producing template packs in this context, we do not
5947 // support them yet.
5948 if (const NonTypeTemplateParmDecl *NTTP =
5949 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5950 NTTP && NTTP->isPackExpansion()) {
5951 auto TL = NTTP->getTypeSourceInfo()
5952 ->getTypeLoc()
5955 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5956 for (const auto &UPP : Unexpanded) {
5957 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5958 if (!TST)
5959 continue;
5960 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5961 // Expanding a built-in pack in this context is not yet supported.
5962 Diag(TL.getEllipsisLoc(),
5963 diag::err_unsupported_builtin_template_pack_expansion)
5964 << TST->getTemplateName();
5965 return true;
5966 }
5967 }
5968
5969 if (ArgIdx < NumArgs) {
5970 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5971 bool NonPackParameter =
5972 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5973 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5974
5975 if (ArgIsExpansion && CTAI.MatchingTTP) {
5976 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5977 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5978 ++Param) {
5979 TemplateArgument &Arg = Args[Param - First];
5980 Arg = ArgLoc.getArgument();
5981 if (!(*Param)->isTemplateParameterPack() ||
5982 getExpandedPackSize(*Param))
5983 Arg = Arg.getPackExpansionPattern();
5984 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5985 SaveAndRestore _1(CTAI.PartialOrdering, false);
5986 SaveAndRestore _2(CTAI.MatchingTTP, true);
5987 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5988 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5990 return true;
5991 Arg = NewArgLoc.getArgument();
5992 CTAI.CanonicalConverted.back().setIsDefaulted(
5993 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5994 CTAI.CanonicalConverted,
5995 Params->getDepth()));
5996 }
5997 ArgLoc = TemplateArgumentLoc(
6000 } else {
6001 SaveAndRestore _1(CTAI.PartialOrdering, false);
6002 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6003 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6005 return true;
6006 CTAI.CanonicalConverted.back().setIsDefaulted(
6007 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6008 *Param, CTAI.CanonicalConverted,
6009 Params->getDepth()));
6010 if (ArgIsExpansion && NonPackParameter) {
6011 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6012 // alias template, builtin template, or concept, and it's not part of
6013 // a parameter pack. This can't be canonicalized, so reject it now.
6015 Template)) {
6016 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6018 : 0;
6019 Diag(ArgLoc.getLocation(),
6020 diag::err_template_expansion_into_fixed_list)
6021 << DiagSelect << ArgLoc.getSourceRange();
6023 return true;
6024 }
6025 }
6026 }
6027
6028 // We're now done with this argument.
6029 ++ArgIdx;
6030
6031 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6032 // Directly convert the remaining arguments, because we don't know what
6033 // parameters they'll match up with.
6034
6035 if (!SugaredArgumentPack.empty()) {
6036 // If we were part way through filling in an expanded parameter pack,
6037 // fall back to just producing individual arguments.
6038 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6039 SugaredArgumentPack.begin(),
6040 SugaredArgumentPack.end());
6041 SugaredArgumentPack.clear();
6042
6043 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6044 CanonicalArgumentPack.begin(),
6045 CanonicalArgumentPack.end());
6046 CanonicalArgumentPack.clear();
6047 }
6048
6049 while (ArgIdx < NumArgs) {
6050 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6051 CTAI.SugaredConverted.push_back(Arg);
6052 CTAI.CanonicalConverted.push_back(
6053 Context.getCanonicalTemplateArgument(Arg));
6054 ++ArgIdx;
6055 }
6056
6057 return false;
6058 }
6059
6060 if ((*Param)->isTemplateParameterPack()) {
6061 // The template parameter was a template parameter pack, so take the
6062 // deduced argument and place it on the argument pack. Note that we
6063 // stay on the same template parameter so that we can deduce more
6064 // arguments.
6065 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6066 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6067 } else {
6068 // Move to the next template parameter.
6069 ++Param;
6070 }
6071 continue;
6072 }
6073
6074 // If we're checking a partial template argument list, we're done.
6075 if (PartialTemplateArgs) {
6076 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6077 CTAI.SugaredConverted.push_back(
6078 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6079 CTAI.CanonicalConverted.push_back(
6080 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6081 }
6082 return false;
6083 }
6084
6085 // If we have a template parameter pack with no more corresponding
6086 // arguments, just break out now and we'll fill in the argument pack below.
6087 if ((*Param)->isTemplateParameterPack()) {
6088 assert(!getExpandedPackSize(*Param) &&
6089 "Should have dealt with this already");
6090
6091 // A non-expanded parameter pack before the end of the parameter list
6092 // only occurs for an ill-formed template parameter list, unless we've
6093 // got a partial argument list for a function template, so just bail out.
6094 if (Param + 1 != ParamEnd) {
6095 assert(
6096 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6097 "Concept templates must have parameter packs at the end.");
6098 return true;
6099 }
6100
6101 CTAI.SugaredConverted.push_back(
6102 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6103 SugaredArgumentPack.clear();
6104
6105 CTAI.CanonicalConverted.push_back(
6106 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6107 CanonicalArgumentPack.clear();
6108
6109 ++Param;
6110 continue;
6111 }
6112
6113 // Check whether we have a default argument.
6114 bool HasDefaultArg;
6115
6116 // Retrieve the default template argument from the template
6117 // parameter. For each kind of template parameter, we substitute the
6118 // template arguments provided thus far and any "outer" template arguments
6119 // (when the template parameter was part of a nested template) into
6120 // the default argument.
6122 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6123 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6124
6125 if (Arg.getArgument().isNull()) {
6126 if (!HasDefaultArg) {
6127 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6128 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6129 NewArgs);
6130 if (NonTypeTemplateParmDecl *NTTP =
6131 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6132 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6133 NewArgs);
6134 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6136 NewArgs);
6137 }
6138 return true;
6139 }
6140
6141 // Introduce an instantiation record that describes where we are using
6142 // the default template argument. We're not actually instantiating a
6143 // template here, we just create this object to put a note into the
6144 // context stack.
6145 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6146 CTAI.SugaredConverted,
6147 SourceRange(TemplateLoc, RAngleLoc));
6148 if (Inst.isInvalid())
6149 return true;
6150
6151 SaveAndRestore _1(CTAI.PartialOrdering, false);
6152 SaveAndRestore _2(CTAI.MatchingTTP, false);
6153 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6154 // Check the default template argument.
6155 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6156 CTAI, CTAK_Specified))
6157 return true;
6158
6159 CTAI.SugaredConverted.back().setIsDefaulted(true);
6160 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6161
6162 // Core issue 150 (assumed resolution): if this is a template template
6163 // parameter, keep track of the default template arguments from the
6164 // template definition.
6165 if (isTemplateTemplateParameter)
6166 NewArgs.addArgument(Arg);
6167
6168 // Move to the next template parameter and argument.
6169 ++Param;
6170 ++ArgIdx;
6171 }
6172
6173 // If we're performing a partial argument substitution, allow any trailing
6174 // pack expansions; they might be empty. This can happen even if
6175 // PartialTemplateArgs is false (the list of arguments is complete but
6176 // still dependent).
6177 if (CTAI.MatchingTTP ||
6179 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6180 while (ArgIdx < NumArgs &&
6181 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6182 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6183 CTAI.SugaredConverted.push_back(Arg);
6184 CTAI.CanonicalConverted.push_back(
6185 Context.getCanonicalTemplateArgument(Arg));
6186 }
6187 }
6188
6189 // If we have any leftover arguments, then there were too many arguments.
6190 // Complain and fail.
6191 if (ArgIdx < NumArgs) {
6192 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6193 << /*too many args*/1
6195 << Template
6196 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6198 return true;
6199 }
6200
6201 // No problems found with the new argument list, propagate changes back
6202 // to caller.
6203 if (UpdateArgsWithConversions)
6204 TemplateArgs = std::move(NewArgs);
6205
6206 if (!PartialTemplateArgs) {
6207 // Setup the context/ThisScope for the case where we are needing to
6208 // re-instantiate constraints outside of normal instantiation.
6209 DeclContext *NewContext = Template->getDeclContext();
6210
6211 // If this template is in a template, make sure we extract the templated
6212 // decl.
6213 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6214 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6215 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6216
6217 Qualifiers ThisQuals;
6218 if (const auto *Method =
6219 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6220 ThisQuals = Method->getMethodQualifiers();
6221
6222 ContextRAII Context(*this, NewContext);
6223 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6224
6226 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6227 /*RelativeToPrimary=*/true,
6228 /*Pattern=*/nullptr,
6229 /*ForConceptInstantiation=*/true);
6230 if (!isa<ConceptDecl>(Template) &&
6232 Template, MLTAL,
6233 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6236 return true;
6237 }
6238 }
6239
6240 return false;
6241}
6242
6243namespace {
6244 class UnnamedLocalNoLinkageFinder
6245 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6246 {
6247 Sema &S;
6248 SourceRange SR;
6249
6251
6252 public:
6253 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6254
6255 bool Visit(QualType T) {
6256 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6257 }
6258
6259#define TYPE(Class, Parent) \
6260 bool Visit##Class##Type(const Class##Type *);
6261#define ABSTRACT_TYPE(Class, Parent) \
6262 bool Visit##Class##Type(const Class##Type *) { return false; }
6263#define NON_CANONICAL_TYPE(Class, Parent) \
6264 bool Visit##Class##Type(const Class##Type *) { return false; }
6265#include "clang/AST/TypeNodes.inc"
6266
6267 bool VisitTagDecl(const TagDecl *Tag);
6268 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6269 };
6270} // end anonymous namespace
6271
6272bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6273 return false;
6274}
6275
6276bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6277 return Visit(T->getElementType());
6278}
6279
6280bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6281 return Visit(T->getPointeeType());
6282}
6283
6284bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6285 const BlockPointerType* T) {
6286 return Visit(T->getPointeeType());
6287}
6288
6289bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6290 const LValueReferenceType* T) {
6291 return Visit(T->getPointeeType());
6292}
6293
6294bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6295 const RValueReferenceType* T) {
6296 return Visit(T->getPointeeType());
6297}
6298
6299bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6300 const MemberPointerType *T) {
6301 if (Visit(T->getPointeeType()))
6302 return true;
6303 if (auto *RD = T->getMostRecentCXXRecordDecl())
6304 return VisitTagDecl(RD);
6305 return VisitNestedNameSpecifier(T->getQualifier());
6306}
6307
6308bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6309 const ConstantArrayType* T) {
6310 return Visit(T->getElementType());
6311}
6312
6313bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6314 const IncompleteArrayType* T) {
6315 return Visit(T->getElementType());
6316}
6317
6318bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6319 const VariableArrayType* T) {
6320 return Visit(T->getElementType());
6321}
6322
6323bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6324 const DependentSizedArrayType* T) {
6325 return Visit(T->getElementType());
6326}
6327
6328bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6329 const DependentSizedExtVectorType* T) {
6330 return Visit(T->getElementType());
6331}
6332
6333bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6334 const DependentSizedMatrixType *T) {
6335 return Visit(T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6339 const DependentAddressSpaceType *T) {
6340 return Visit(T->getPointeeType());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6344 return Visit(T->getElementType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6348 const DependentVectorType *T) {
6349 return Visit(T->getElementType());
6350}
6351
6352bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6353 return Visit(T->getElementType());
6354}
6355
6356bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6357 const ConstantMatrixType *T) {
6358 return Visit(T->getElementType());
6359}
6360
6361bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6362 const FunctionProtoType* T) {
6363 for (const auto &A : T->param_types()) {
6364 if (Visit(A))
6365 return true;
6366 }
6367
6368 return Visit(T->getReturnType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6372 const FunctionNoProtoType* T) {
6373 return Visit(T->getReturnType());
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6377 const UnresolvedUsingType*) {
6378 return false;
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6382 return false;
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6386 return Visit(T->getUnmodifiedType());
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6390 return false;
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6394 const PackIndexingType *) {
6395 return false;
6396}
6397
6398bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6399 const UnaryTransformType*) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6404 return Visit(T->getDeducedType());
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6408 const DeducedTemplateSpecializationType *T) {
6409 return Visit(T->getDeducedType());
6410}
6411
6412bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6413 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6417 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6421 const TemplateTypeParmType*) {
6422 return false;
6423}
6424
6425bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6426 const SubstTemplateTypeParmPackType *) {
6427 return false;
6428}
6429
6430bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6431 const SubstBuiltinTemplatePackType *) {
6432 return false;
6433}
6434
6435bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6436 const TemplateSpecializationType*) {
6437 return false;
6438}
6439
6440bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6441 const InjectedClassNameType* T) {
6442 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6443}
6444
6445bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6446 const DependentNameType* T) {
6447 return VisitNestedNameSpecifier(T->getQualifier());
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6451 const PackExpansionType* T) {
6452 return Visit(T->getPattern());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6456 return false;
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6460 const ObjCInterfaceType *) {
6461 return false;
6462}
6463
6464bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6465 const ObjCObjectPointerType *) {
6466 return false;
6467}
6468
6469bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6470 return Visit(T->getValueType());
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6474 const OverflowBehaviorType *T) {
6475 return Visit(T->getUnderlyingType());
6476}
6477
6478bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6479 return false;
6480}
6481
6482bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6483 return false;
6484}
6485
6486bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6487 const ArrayParameterType *T) {
6488 return VisitConstantArrayType(T);
6489}
6490
6491bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6492 const DependentBitIntType *T) {
6493 return false;
6494}
6495
6496bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6497 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6498 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6499 ? diag::warn_cxx98_compat_template_arg_local_type
6500 : diag::ext_template_arg_local_type)
6501 << S.Context.getCanonicalTagType(Tag) << SR;
6502 return true;
6503 }
6504
6505 if (!Tag->hasNameForLinkage()) {
6506 S.Diag(SR.getBegin(),
6507 S.getLangOpts().CPlusPlus11 ?
6508 diag::warn_cxx98_compat_template_arg_unnamed_type :
6509 diag::ext_template_arg_unnamed_type) << SR;
6510 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6511 return true;
6512 }
6513
6514 return false;
6515}
6516
6517bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6518 NestedNameSpecifier NNS) {
6519 switch (NNS.getKind()) {
6524 return false;
6526 return Visit(QualType(NNS.getAsType(), 0));
6527 }
6528 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6529}
6530
6531bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6532 const HLSLAttributedResourceType *T) {
6533 if (T->hasContainedType() && Visit(T->getContainedType()))
6534 return true;
6535 return Visit(T->getWrappedType());
6536}
6537
6538bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6539 const HLSLInlineSpirvType *T) {
6540 for (auto &Operand : T->getOperands())
6541 if (Operand.isConstant() && Operand.isLiteral())
6542 if (Visit(Operand.getResultType()))
6543 return true;
6544 return false;
6545}
6546
6548 assert(ArgInfo && "invalid TypeSourceInfo");
6549 QualType Arg = ArgInfo->getType();
6550 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6551 QualType CanonArg = Context.getCanonicalType(Arg);
6552
6553 if (CanonArg->isVariablyModifiedType()) {
6554 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6555 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6556 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6557 }
6558
6559 // C++03 [temp.arg.type]p2:
6560 // A local type, a type with no linkage, an unnamed type or a type
6561 // compounded from any of these types shall not be used as a
6562 // template-argument for a template type-parameter.
6563 //
6564 // C++11 allows these, and even in C++03 we allow them as an extension with
6565 // a warning.
6566 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6567 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6568 (void)Finder.Visit(CanonArg);
6569 }
6570
6571 return false;
6572}
6573
6579
6580/// Determine whether the given template argument is a null pointer
6581/// value of the appropriate type.
6584 QualType ParamType, Expr *Arg,
6585 Decl *Entity = nullptr) {
6586 if (Arg->isValueDependent() || Arg->isTypeDependent())
6587 return NPV_NotNullPointer;
6588
6589 // dllimport'd entities aren't constant but are available inside of template
6590 // arguments.
6591 if (Entity && Entity->hasAttr<DLLImportAttr>())
6592 return NPV_NotNullPointer;
6593
6594 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6595 llvm_unreachable(
6596 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6597
6598 if (!S.getLangOpts().CPlusPlus11)
6599 return NPV_NotNullPointer;
6600
6601 // Determine whether we have a constant expression.
6603 if (ArgRV.isInvalid())
6604 return NPV_Error;
6605 Arg = ArgRV.get();
6606
6607 Expr::EvalResult EvalResult;
6609 EvalResult.Diag = &Notes;
6610 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6611 EvalResult.HasSideEffects) {
6612 SourceLocation DiagLoc = Arg->getExprLoc();
6613
6614 // If our only note is the usual "invalid subexpression" note, just point
6615 // the caret at its location rather than producing an essentially
6616 // redundant note.
6617 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6618 diag::note_invalid_subexpr_in_const_expr) {
6619 DiagLoc = Notes[0].first;
6620 Notes.clear();
6621 }
6622
6623 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6624 << Arg->getType() << Arg->getSourceRange();
6625 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6626 S.Diag(Notes[I].first, Notes[I].second);
6627
6629 return NPV_Error;
6630 }
6631
6632 // C++11 [temp.arg.nontype]p1:
6633 // - an address constant expression of type std::nullptr_t
6634 if (Arg->getType()->isNullPtrType())
6635 return NPV_NullPointer;
6636
6637 // - a constant expression that evaluates to a null pointer value (4.10); or
6638 // - a constant expression that evaluates to a null member pointer value
6639 // (4.11); or
6640 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6641 (EvalResult.Val.isMemberPointer() &&
6642 !EvalResult.Val.getMemberPointerDecl())) {
6643 // If our expression has an appropriate type, we've succeeded.
6644 bool ObjCLifetimeConversion;
6645 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6646 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6647 ObjCLifetimeConversion))
6648 return NPV_NullPointer;
6649
6650 // The types didn't match, but we know we got a null pointer; complain,
6651 // then recover as if the types were correct.
6652 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6653 << Arg->getType() << ParamType << Arg->getSourceRange();
6655 return NPV_NullPointer;
6656 }
6657
6658 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6659 // We found a pointer that isn't null, but doesn't refer to an object.
6660 // We could just return NPV_NotNullPointer, but we can print a better
6661 // message with the information we have here.
6662 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6663 << EvalResult.Val.getAsString(S.Context, ParamType);
6665 return NPV_Error;
6666 }
6667
6668 // If we don't have a null pointer value, but we do have a NULL pointer
6669 // constant, suggest a cast to the appropriate type.
6671 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6672 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6673 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6675 ")");
6677 return NPV_NullPointer;
6678 }
6679
6680 // FIXME: If we ever want to support general, address-constant expressions
6681 // as non-type template arguments, we should return the ExprResult here to
6682 // be interpreted by the caller.
6683 return NPV_NotNullPointer;
6684}
6685
6686/// Checks whether the given template argument is compatible with its
6687/// template parameter.
6688static bool
6690 QualType ParamType, Expr *ArgIn,
6691 Expr *Arg, QualType ArgType) {
6692 bool ObjCLifetimeConversion;
6693 if (ParamType->isPointerType() &&
6694 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6695 S.IsQualificationConversion(ArgType, ParamType, false,
6696 ObjCLifetimeConversion)) {
6697 // For pointer-to-object types, qualification conversions are
6698 // permitted.
6699 } else {
6700 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6701 if (!ParamRef->getPointeeType()->isFunctionType()) {
6702 // C++ [temp.arg.nontype]p5b3:
6703 // For a non-type template-parameter of type reference to
6704 // object, no conversions apply. The type referred to by the
6705 // reference may be more cv-qualified than the (otherwise
6706 // identical) type of the template- argument. The
6707 // template-parameter is bound directly to the
6708 // template-argument, which shall be an lvalue.
6709
6710 // FIXME: Other qualifiers?
6711 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6712 unsigned ArgQuals = ArgType.getCVRQualifiers();
6713
6714 if ((ParamQuals | ArgQuals) != ParamQuals) {
6715 S.Diag(Arg->getBeginLoc(),
6716 diag::err_template_arg_ref_bind_ignores_quals)
6717 << ParamType << Arg->getType() << Arg->getSourceRange();
6719 return true;
6720 }
6721 }
6722 }
6723
6724 // At this point, the template argument refers to an object or
6725 // function with external linkage. We now need to check whether the
6726 // argument and parameter types are compatible.
6727 if (!S.Context.hasSameUnqualifiedType(ArgType,
6728 ParamType.getNonReferenceType())) {
6729 // We can't perform this conversion or binding.
6730 if (ParamType->isReferenceType())
6731 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6732 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6733 else
6734 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6735 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6737 return true;
6738 }
6739 }
6740
6741 return false;
6742}
6743
6744/// Checks whether the given template argument is the address
6745/// of an object or function according to C++ [temp.arg.nontype]p1.
6747 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6748 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6749 bool Invalid = false;
6750 Expr *Arg = ArgIn;
6751 QualType ArgType = Arg->getType();
6752
6753 bool AddressTaken = false;
6754 SourceLocation AddrOpLoc;
6755 if (S.getLangOpts().MicrosoftExt) {
6756 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6757 // dereference and address-of operators.
6758 Arg = Arg->IgnoreParenCasts();
6759
6760 bool ExtWarnMSTemplateArg = false;
6761 UnaryOperatorKind FirstOpKind;
6762 SourceLocation FirstOpLoc;
6763 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6764 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6765 if (UnOpKind == UO_Deref)
6766 ExtWarnMSTemplateArg = true;
6767 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6768 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6769 if (!AddrOpLoc.isValid()) {
6770 FirstOpKind = UnOpKind;
6771 FirstOpLoc = UnOp->getOperatorLoc();
6772 }
6773 } else
6774 break;
6775 }
6776 if (FirstOpLoc.isValid()) {
6777 if (ExtWarnMSTemplateArg)
6778 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6779 << ArgIn->getSourceRange();
6780
6781 if (FirstOpKind == UO_AddrOf)
6782 AddressTaken = true;
6783 else if (Arg->getType()->isPointerType()) {
6784 // We cannot let pointers get dereferenced here, that is obviously not a
6785 // constant expression.
6786 assert(FirstOpKind == UO_Deref);
6787 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6788 << Arg->getSourceRange();
6789 }
6790 }
6791 } else {
6792 // See through any implicit casts we added to fix the type.
6793 Arg = Arg->IgnoreImpCasts();
6794
6795 // C++ [temp.arg.nontype]p1:
6796 //
6797 // A template-argument for a non-type, non-template
6798 // template-parameter shall be one of: [...]
6799 //
6800 // -- the address of an object or function with external
6801 // linkage, including function templates and function
6802 // template-ids but excluding non-static class members,
6803 // expressed as & id-expression where the & is optional if
6804 // the name refers to a function or array, or if the
6805 // corresponding template-parameter is a reference; or
6806
6807 // In C++98/03 mode, give an extension warning on any extra parentheses.
6808 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6809 bool ExtraParens = false;
6810 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6811 if (!Invalid && !ExtraParens) {
6812 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6813 << Arg->getSourceRange();
6814 ExtraParens = true;
6815 }
6816
6817 Arg = Parens->getSubExpr();
6818 }
6819
6820 while (SubstNonTypeTemplateParmExpr *subst =
6821 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6822 Arg = subst->getReplacement()->IgnoreImpCasts();
6823
6824 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6825 if (UnOp->getOpcode() == UO_AddrOf) {
6826 Arg = UnOp->getSubExpr();
6827 AddressTaken = true;
6828 AddrOpLoc = UnOp->getOperatorLoc();
6829 }
6830 }
6831
6832 while (SubstNonTypeTemplateParmExpr *subst =
6833 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6834 Arg = subst->getReplacement()->IgnoreImpCasts();
6835 }
6836
6837 ValueDecl *Entity = nullptr;
6838 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6839 Entity = DRE->getDecl();
6840 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6841 Entity = CUE->getGuidDecl();
6842
6843 // If our parameter has pointer type, check for a null template value.
6844 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6845 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6846 Entity)) {
6847 case NPV_NullPointer:
6848 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6849 SugaredConverted = TemplateArgument(ParamType,
6850 /*isNullPtr=*/true);
6851 CanonicalConverted =
6853 /*isNullPtr=*/true);
6854 return false;
6855
6856 case NPV_Error:
6857 return true;
6858
6859 case NPV_NotNullPointer:
6860 break;
6861 }
6862 }
6863
6864 // Stop checking the precise nature of the argument if it is value dependent,
6865 // it should be checked when instantiated.
6866 if (Arg->isValueDependent()) {
6867 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6868 CanonicalConverted =
6869 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6870 return false;
6871 }
6872
6873 if (!Entity) {
6874 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6875 << Arg->getSourceRange();
6877 return true;
6878 }
6879
6880 // Cannot refer to non-static data members
6881 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6882 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6883 << Entity << Arg->getSourceRange();
6885 return true;
6886 }
6887
6888 // Cannot refer to non-static member functions
6889 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6890 if (!Method->isStatic()) {
6891 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6892 << Method << Arg->getSourceRange();
6894 return true;
6895 }
6896 }
6897
6898 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6899 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6900 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6901
6902 // A non-type template argument must refer to an object or function.
6903 if (!Func && !Var && !Guid) {
6904 // We found something, but we don't know specifically what it is.
6905 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6906 << Arg->getSourceRange();
6907 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6908 return true;
6909 }
6910
6911 // Address / reference template args must have external linkage in C++98.
6912 if (Entity->getFormalLinkage() == Linkage::Internal) {
6913 S.Diag(Arg->getBeginLoc(),
6914 S.getLangOpts().CPlusPlus11
6915 ? diag::warn_cxx98_compat_template_arg_object_internal
6916 : diag::ext_template_arg_object_internal)
6917 << !Func << Entity << Arg->getSourceRange();
6918 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6919 << !Func;
6920 } else if (!Entity->hasLinkage()) {
6921 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6922 << !Func << Entity << Arg->getSourceRange();
6923 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6924 << !Func;
6925 return true;
6926 }
6927
6928 if (Var) {
6929 // A value of reference type is not an object.
6930 if (Var->getType()->isReferenceType()) {
6931 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6932 << Var->getType() << Arg->getSourceRange();
6934 return true;
6935 }
6936
6937 // A template argument must have static storage duration.
6938 if (Var->getTLSKind()) {
6939 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6940 << Arg->getSourceRange();
6941 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6942 return true;
6943 }
6944 }
6945
6946 if (AddressTaken && ParamType->isReferenceType()) {
6947 // If we originally had an address-of operator, but the
6948 // parameter has reference type, complain and (if things look
6949 // like they will work) drop the address-of operator.
6950 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6951 ParamType.getNonReferenceType())) {
6952 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6953 << ParamType;
6955 return true;
6956 }
6957
6958 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6959 << ParamType
6960 << FixItHint::CreateRemoval(AddrOpLoc);
6962
6963 ArgType = Entity->getType();
6964 }
6965
6966 // If the template parameter has pointer type, either we must have taken the
6967 // address or the argument must decay to a pointer.
6968 if (!AddressTaken && ParamType->isPointerType()) {
6969 if (Func) {
6970 // Function-to-pointer decay.
6971 ArgType = S.Context.getPointerType(Func->getType());
6972 } else if (Entity->getType()->isArrayType()) {
6973 // Array-to-pointer decay.
6974 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6975 } else {
6976 // If the template parameter has pointer type but the address of
6977 // this object was not taken, complain and (possibly) recover by
6978 // taking the address of the entity.
6979 ArgType = S.Context.getPointerType(Entity->getType());
6980 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6981 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6982 << ParamType;
6984 return true;
6985 }
6986
6987 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6988 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6989
6991 }
6992 }
6993
6994 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6995 Arg, ArgType))
6996 return true;
6997
6998 // Create the template argument.
6999 SugaredConverted = TemplateArgument(Entity, ParamType);
7000 CanonicalConverted =
7002 S.Context.getCanonicalType(ParamType));
7003 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7004 return false;
7005}
7006
7007/// Checks whether the given template argument is a pointer to
7008/// member constant according to C++ [temp.arg.nontype]p1.
7010 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7011 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7012 bool Invalid = false;
7013
7014 Expr *Arg = ResultArg;
7015 bool ObjCLifetimeConversion;
7016
7017 // C++ [temp.arg.nontype]p1:
7018 //
7019 // A template-argument for a non-type, non-template
7020 // template-parameter shall be one of: [...]
7021 //
7022 // -- a pointer to member expressed as described in 5.3.1.
7023 DeclRefExpr *DRE = nullptr;
7024
7025 // In C++98/03 mode, give an extension warning on any extra parentheses.
7026 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7027 bool ExtraParens = false;
7028 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7029 if (!Invalid && !ExtraParens) {
7030 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7031 << Arg->getSourceRange();
7032 ExtraParens = true;
7033 }
7034
7035 Arg = Parens->getSubExpr();
7036 }
7037
7038 while (SubstNonTypeTemplateParmExpr *subst =
7039 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7040 Arg = subst->getReplacement()->IgnoreImpCasts();
7041
7042 // A pointer-to-member constant written &Class::member.
7043 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7044 if (UnOp->getOpcode() == UO_AddrOf) {
7045 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7046 if (DRE && !DRE->getQualifier())
7047 DRE = nullptr;
7048 }
7049 }
7050 // A constant of pointer-to-member type.
7051 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7052 ValueDecl *VD = DRE->getDecl();
7053 if (VD->getType()->isMemberPointerType()) {
7055 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7056 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7057 CanonicalConverted =
7058 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7059 } else {
7060 SugaredConverted = TemplateArgument(VD, ParamType);
7061 CanonicalConverted =
7063 S.Context.getCanonicalType(ParamType));
7064 }
7065 return Invalid;
7066 }
7067 }
7068
7069 DRE = nullptr;
7070 }
7071
7072 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7073
7074 // Check for a null pointer value.
7075 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7076 Entity)) {
7077 case NPV_Error:
7078 return true;
7079 case NPV_NullPointer:
7080 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7081 SugaredConverted = TemplateArgument(ParamType,
7082 /*isNullPtr*/ true);
7083 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7084 /*isNullPtr*/ true);
7085 return false;
7086 case NPV_NotNullPointer:
7087 break;
7088 }
7089
7090 if (S.IsQualificationConversion(ResultArg->getType(),
7091 ParamType.getNonReferenceType(), false,
7092 ObjCLifetimeConversion)) {
7093 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7094 ResultArg->getValueKind())
7095 .get();
7096 } else if (!S.Context.hasSameUnqualifiedType(
7097 ResultArg->getType(), ParamType.getNonReferenceType())) {
7098 // We can't perform this conversion.
7099 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7100 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7102 return true;
7103 }
7104
7105 if (!DRE)
7106 return S.Diag(Arg->getBeginLoc(),
7107 diag::err_template_arg_not_pointer_to_member_form)
7108 << Arg->getSourceRange();
7109
7110 if (isa<FieldDecl>(DRE->getDecl()) ||
7112 isa<CXXMethodDecl>(DRE->getDecl())) {
7113 assert((isa<FieldDecl>(DRE->getDecl()) ||
7116 ->isImplicitObjectMemberFunction()) &&
7117 "Only non-static member pointers can make it here");
7118
7119 // Okay: this is the address of a non-static member, and therefore
7120 // a member pointer constant.
7121 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7122 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7123 CanonicalConverted =
7124 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7125 } else {
7126 ValueDecl *D = DRE->getDecl();
7127 SugaredConverted = TemplateArgument(D, ParamType);
7128 CanonicalConverted =
7130 S.Context.getCanonicalType(ParamType));
7131 }
7132 return Invalid;
7133 }
7134
7135 // We found something else, but we don't know specifically what it is.
7136 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7137 << Arg->getSourceRange();
7138 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7139 return true;
7140}
7141
7142/// Check a template argument against its corresponding
7143/// non-type template parameter.
7144///
7145/// This routine implements the semantics of C++ [temp.arg.nontype].
7146/// If an error occurred, it returns ExprError(); otherwise, it
7147/// returns the converted template argument. \p ParamType is the
7148/// type of the non-type template parameter after it has been instantiated.
7150 Expr *Arg,
7151 TemplateArgument &SugaredConverted,
7152 TemplateArgument &CanonicalConverted,
7153 bool StrictCheck,
7155 SourceLocation StartLoc = Arg->getBeginLoc();
7156 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7157 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7158 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7159 DeductionArg = NewDeductionArg;
7160 if (ArgPE) {
7161 // Recreate a pack expansion if we unwrapped one.
7162 Arg = new (Context) PackExpansionExpr(
7163 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7164 } else {
7165 Arg = DeductionArg;
7166 }
7167 };
7168
7169 // If the parameter type somehow involves auto, deduce the type now.
7170 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7171 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7172 if (IsDeduced) {
7173 // When checking a deduced template argument, deduce from its type even if
7174 // the type is dependent, in order to check the types of non-type template
7175 // arguments line up properly in partial ordering.
7176 TypeSourceInfo *TSI =
7177 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7179 InitializedEntity Entity =
7182 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7183 Expr *Inits[1] = {DeductionArg};
7184 ParamType =
7186 if (ParamType.isNull())
7187 return ExprError();
7188 } else {
7189 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7190 Param->getTemplateDepth() + 1);
7191 ParamType = QualType();
7193 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7194 /*DependentDeduction=*/true,
7195 // We do not check constraints right now because the
7196 // immediately-declared constraint of the auto type is
7197 // also an associated constraint, and will be checked
7198 // along with the other associated constraints after
7199 // checking the template argument list.
7200 /*IgnoreConstraints=*/true);
7202 ParamType = TSI->getType();
7203 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7205 return ExprError();
7206 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7207 Diag(Arg->getExprLoc(),
7208 diag::err_non_type_template_parm_type_deduction_failure)
7209 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7210 << Arg->getSourceRange();
7212 return ExprError();
7213 }
7214 ParamType = SubstAutoTypeDependent(ParamType);
7215 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7216 }
7217 }
7218 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7219 // an error. The error message normally references the parameter
7220 // declaration, but here we'll pass the argument location because that's
7221 // where the parameter type is deduced.
7222 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7223 if (ParamType.isNull()) {
7225 return ExprError();
7226 }
7227 }
7228
7229 // We should have already dropped all cv-qualifiers by now.
7230 assert(!ParamType.hasQualifiers() &&
7231 "non-type template parameter type cannot be qualified");
7232
7233 // If either the parameter has a dependent type or the argument is
7234 // type-dependent, there's nothing we can check now.
7235 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7236 // Force the argument to the type of the parameter to maintain invariants.
7237 if (!IsDeduced) {
7239 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7240 ParamType->isLValueReferenceType() ? VK_LValue
7241 : ParamType->isRValueReferenceType() ? VK_XValue
7242 : VK_PRValue);
7243 if (E.isInvalid())
7244 return ExprError();
7245 setDeductionArg(E.get());
7246 }
7247 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7248 CanonicalConverted = TemplateArgument(
7249 Context.getCanonicalTemplateArgument(SugaredConverted));
7250 return Arg;
7251 }
7252
7253 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7254 if (CTAK == CTAK_Deduced && !StrictCheck &&
7255 (ParamType->isReferenceType()
7256 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7257 DeductionArg->getType())
7258 : !Context.hasSameUnqualifiedType(ParamType,
7259 DeductionArg->getType()))) {
7260 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7261 // we should actually be checking the type of the template argument in P,
7262 // not the type of the template argument deduced from A, against the
7263 // template parameter type.
7264 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7265 << Arg->getType() << ParamType.getUnqualifiedType();
7267 return ExprError();
7268 }
7269
7270 // If the argument is a pack expansion, we don't know how many times it would
7271 // expand. If we continue checking the argument, this will make the template
7272 // definition ill-formed if it would be ill-formed for any number of
7273 // expansions during instantiation time. When partial ordering or matching
7274 // template template parameters, this is exactly what we want. Otherwise, the
7275 // normal template rules apply: we accept the template if it would be valid
7276 // for any number of expansions (i.e. none).
7277 if (ArgPE && !StrictCheck) {
7278 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7279 CanonicalConverted = TemplateArgument(
7280 Context.getCanonicalTemplateArgument(SugaredConverted));
7281 return Arg;
7282 }
7283
7284 // Avoid making a copy when initializing a template parameter of class type
7285 // from a template parameter object of the same type. This is going beyond
7286 // the standard, but is required for soundness: in
7287 // template<A a> struct X { X *p; X<a> *q; };
7288 // ... we need p and q to have the same type.
7289 //
7290 // Similarly, don't inject a call to a copy constructor when initializing
7291 // from a template parameter of the same type.
7292 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7293 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7294 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7295 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7296 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7297
7298 SugaredConverted = TemplateArgument(TPO, ParamType);
7299 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7300 ParamType.getCanonicalType());
7301 return Arg;
7302 }
7304 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7305 CanonicalConverted =
7306 Context.getCanonicalTemplateArgument(SugaredConverted);
7307 return Arg;
7308 }
7309 }
7310
7311 // The initialization of the parameter from the argument is
7312 // a constant-evaluated context.
7315
7316 bool IsConvertedConstantExpression = true;
7317 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7319 StartLoc, /*DirectInit=*/false, DeductionArg);
7320 Expr *Inits[1] = {DeductionArg};
7321 InitializedEntity Entity =
7323 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7324 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7325 if (Result.isInvalid() || !Result.get())
7326 return ExprError();
7328 if (Result.isInvalid() || !Result.get())
7329 return ExprError();
7330 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7331 /*DiscardedValue=*/false,
7332 /*IsConstexpr=*/true,
7333 /*IsTemplateArgument=*/true)
7334 .get());
7335 IsConvertedConstantExpression = false;
7336 }
7337
7338 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7339 // C++17 [temp.arg.nontype]p1:
7340 // A template-argument for a non-type template parameter shall be
7341 // a converted constant expression of the type of the template-parameter.
7342 APValue Value;
7343 ExprResult ArgResult;
7344 if (IsConvertedConstantExpression) {
7346 DeductionArg, ParamType,
7347 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7348 assert(!ArgResult.isUnset());
7349 if (ArgResult.isInvalid()) {
7351 return ExprError();
7352 }
7353 } else {
7354 ArgResult = DeductionArg;
7355 }
7356
7357 // For a value-dependent argument, CheckConvertedConstantExpression is
7358 // permitted (and expected) to be unable to determine a value.
7359 if (ArgResult.get()->isValueDependent()) {
7360 setDeductionArg(ArgResult.get());
7361 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7362 CanonicalConverted =
7363 Context.getCanonicalTemplateArgument(SugaredConverted);
7364 return Arg;
7365 }
7366
7367 APValue PreNarrowingValue;
7369 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7370 false, PreNarrowingValue);
7371 if (ArgResult.isInvalid())
7372 return ExprError();
7373 setDeductionArg(ArgResult.get());
7374
7375 if (Value.isLValue()) {
7376 APValue::LValueBase Base = Value.getLValueBase();
7377 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7378 // For a non-type template-parameter of pointer or reference type,
7379 // the value of the constant expression shall not refer to
7380 assert(ParamType->isPointerOrReferenceType() ||
7381 ParamType->isNullPtrType());
7382 // -- a temporary object
7383 // -- a string literal
7384 // -- the result of a typeid expression, or
7385 // -- a predefined __func__ variable
7386 if (Base &&
7387 (!VD ||
7389 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7390 << Arg->getSourceRange();
7391 return ExprError();
7392 }
7393
7394 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7395 VD->getType()->isArrayType() &&
7396 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7397 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7398 if (ArgPE) {
7399 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7400 CanonicalConverted =
7401 Context.getCanonicalTemplateArgument(SugaredConverted);
7402 } else {
7403 SugaredConverted = TemplateArgument(VD, ParamType);
7404 CanonicalConverted =
7406 ParamType.getCanonicalType());
7407 }
7408 return Arg;
7409 }
7410
7411 // -- a subobject [until C++20]
7412 if (!getLangOpts().CPlusPlus20) {
7413 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7414 Value.isLValueOnePastTheEnd()) {
7415 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7416 << Value.getAsString(Context, ParamType);
7417 return ExprError();
7418 }
7419 assert((VD || !ParamType->isReferenceType()) &&
7420 "null reference should not be a constant expression");
7421 assert((!VD || !ParamType->isNullPtrType()) &&
7422 "non-null value of type nullptr_t?");
7423 }
7424 }
7425
7426 if (Value.isAddrLabelDiff())
7427 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7428
7429 if (ArgPE) {
7430 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7431 CanonicalConverted =
7432 Context.getCanonicalTemplateArgument(SugaredConverted);
7433 } else {
7434 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7435 CanonicalConverted =
7437 }
7438 return Arg;
7439 }
7440
7441 // These should have all been handled above using the C++17 rules.
7442 assert(!ArgPE && !StrictCheck);
7443
7444 // C++ [temp.arg.nontype]p5:
7445 // The following conversions are performed on each expression used
7446 // as a non-type template-argument. If a non-type
7447 // template-argument cannot be converted to the type of the
7448 // corresponding template-parameter then the program is
7449 // ill-formed.
7450 if (ParamType->isIntegralOrEnumerationType()) {
7451 // C++11:
7452 // -- for a non-type template-parameter of integral or
7453 // enumeration type, conversions permitted in a converted
7454 // constant expression are applied.
7455 //
7456 // C++98:
7457 // -- for a non-type template-parameter of integral or
7458 // enumeration type, integral promotions (4.5) and integral
7459 // conversions (4.7) are applied.
7460
7461 if (getLangOpts().CPlusPlus11) {
7462 // C++ [temp.arg.nontype]p1:
7463 // A template-argument for a non-type, non-template template-parameter
7464 // shall be one of:
7465 //
7466 // -- for a non-type template-parameter of integral or enumeration
7467 // type, a converted constant expression of the type of the
7468 // template-parameter; or
7469 llvm::APSInt Value;
7471 Arg, ParamType, Value, CCEKind::TemplateArg);
7472 if (ArgResult.isInvalid())
7473 return ExprError();
7474 Arg = ArgResult.get();
7475
7476 // We can't check arbitrary value-dependent arguments.
7477 if (Arg->isValueDependent()) {
7478 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7479 CanonicalConverted =
7480 Context.getCanonicalTemplateArgument(SugaredConverted);
7481 return Arg;
7482 }
7483
7484 // Widen the argument value to sizeof(parameter type). This is almost
7485 // always a no-op, except when the parameter type is bool. In
7486 // that case, this may extend the argument from 1 bit to 8 bits.
7487 QualType IntegerType = ParamType;
7488 if (const auto *ED = IntegerType->getAsEnumDecl())
7489 IntegerType = ED->getIntegerType();
7490 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7491 ? Context.getIntWidth(IntegerType)
7492 : Context.getTypeSize(IntegerType));
7493
7494 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7495 CanonicalConverted =
7496 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7497 return Arg;
7498 }
7499
7500 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7501 if (ArgResult.isInvalid())
7502 return ExprError();
7503 Arg = ArgResult.get();
7504
7505 QualType ArgType = Arg->getType();
7506
7507 // C++ [temp.arg.nontype]p1:
7508 // A template-argument for a non-type, non-template
7509 // template-parameter shall be one of:
7510 //
7511 // -- an integral constant-expression of integral or enumeration
7512 // type; or
7513 // -- the name of a non-type template-parameter; or
7514 llvm::APSInt Value;
7515 if (!ArgType->isIntegralOrEnumerationType()) {
7516 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7517 << ArgType << Arg->getSourceRange();
7519 return ExprError();
7520 }
7521 if (!Arg->isValueDependent()) {
7522 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7523 QualType T;
7524
7525 public:
7526 TmplArgICEDiagnoser(QualType T) : T(T) { }
7527
7528 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7529 SourceLocation Loc) override {
7530 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7531 }
7532 } Diagnoser(ArgType);
7533
7534 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7535 if (!Arg)
7536 return ExprError();
7537 }
7538
7539 // From here on out, all we care about is the unqualified form
7540 // of the argument type.
7541 ArgType = ArgType.getUnqualifiedType();
7542
7543 // Try to convert the argument to the parameter's type.
7544 if (Context.hasSameType(ParamType, ArgType)) {
7545 // Okay: no conversion necessary
7546 } else if (ParamType->isBooleanType()) {
7547 // This is an integral-to-boolean conversion.
7548 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7549 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7550 !ParamType->isEnumeralType()) {
7551 // This is an integral promotion or conversion.
7552 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7553 } else {
7554 // We can't perform this conversion.
7555 Diag(StartLoc, diag::err_template_arg_not_convertible)
7556 << Arg->getType() << ParamType << Arg->getSourceRange();
7558 return ExprError();
7559 }
7560
7561 // Add the value of this argument to the list of converted
7562 // arguments. We use the bitwidth and signedness of the template
7563 // parameter.
7564 if (Arg->isValueDependent()) {
7565 // The argument is value-dependent. Create a new
7566 // TemplateArgument with the converted expression.
7567 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7568 CanonicalConverted =
7569 Context.getCanonicalTemplateArgument(SugaredConverted);
7570 return Arg;
7571 }
7572
7573 QualType IntegerType = ParamType;
7574 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7575 IntegerType = ED->getIntegerType();
7576 }
7577
7578 if (ParamType->isBooleanType()) {
7579 // Value must be zero or one.
7580 Value = Value != 0;
7581 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7582 if (Value.getBitWidth() != AllowedBits)
7583 Value = Value.extOrTrunc(AllowedBits);
7584 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7585 } else {
7586 llvm::APSInt OldValue = Value;
7587
7588 // Coerce the template argument's value to the value it will have
7589 // based on the template parameter's type.
7590 unsigned AllowedBits = IntegerType->isBitIntType()
7591 ? Context.getIntWidth(IntegerType)
7592 : Context.getTypeSize(IntegerType);
7593 if (Value.getBitWidth() != AllowedBits)
7594 Value = Value.extOrTrunc(AllowedBits);
7595 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7596
7597 // Complain if an unsigned parameter received a negative value.
7598 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7599 (OldValue.isSigned() && OldValue.isNegative())) {
7600 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7601 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7602 << Arg->getSourceRange();
7604 }
7605
7606 // Complain if we overflowed the template parameter's type.
7607 unsigned RequiredBits;
7608 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7609 RequiredBits = OldValue.getActiveBits();
7610 else if (OldValue.isUnsigned())
7611 RequiredBits = OldValue.getActiveBits() + 1;
7612 else
7613 RequiredBits = OldValue.getSignificantBits();
7614 if (RequiredBits > AllowedBits) {
7615 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7616 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7617 << Arg->getSourceRange();
7619 }
7620 }
7621
7622 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7623 SugaredConverted = TemplateArgument(Context, Value, T);
7624 CanonicalConverted =
7625 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7626 return Arg;
7627 }
7628
7629 QualType ArgType = Arg->getType();
7630 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7631
7632 // Handle pointer-to-function, reference-to-function, and
7633 // pointer-to-member-function all in (roughly) the same way.
7634 if (// -- For a non-type template-parameter of type pointer to
7635 // function, only the function-to-pointer conversion (4.3) is
7636 // applied. If the template-argument represents a set of
7637 // overloaded functions (or a pointer to such), the matching
7638 // function is selected from the set (13.4).
7639 (ParamType->isPointerType() &&
7640 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7641 // -- For a non-type template-parameter of type reference to
7642 // function, no conversions apply. If the template-argument
7643 // represents a set of overloaded functions, the matching
7644 // function is selected from the set (13.4).
7645 (ParamType->isReferenceType() &&
7646 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7647 // -- For a non-type template-parameter of type pointer to
7648 // member function, no conversions apply. If the
7649 // template-argument represents a set of overloaded member
7650 // functions, the matching member function is selected from
7651 // the set (13.4).
7652 (ParamType->isMemberPointerType() &&
7653 ParamType->castAs<MemberPointerType>()->getPointeeType()
7654 ->isFunctionType())) {
7655
7656 if (Arg->getType() == Context.OverloadTy) {
7657 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7658 true,
7659 FoundResult)) {
7660 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7661 return ExprError();
7662
7663 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7664 if (Res.isInvalid())
7665 return ExprError();
7666 Arg = Res.get();
7667 ArgType = Arg->getType();
7668 } else
7669 return ExprError();
7670 }
7671
7672 if (!ParamType->isMemberPointerType()) {
7674 *this, Param, ParamType, Arg, SugaredConverted,
7675 CanonicalConverted))
7676 return ExprError();
7677 return Arg;
7678 }
7679
7681 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7682 return ExprError();
7683 return Arg;
7684 }
7685
7686 if (ParamType->isPointerType()) {
7687 // -- for a non-type template-parameter of type pointer to
7688 // object, qualification conversions (4.4) and the
7689 // array-to-pointer conversion (4.2) are applied.
7690 // C++0x also allows a value of std::nullptr_t.
7691 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7692 "Only object pointers allowed here");
7693
7695 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7696 return ExprError();
7697 return Arg;
7698 }
7699
7700 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7701 // -- For a non-type template-parameter of type reference to
7702 // object, no conversions apply. The type referred to by the
7703 // reference may be more cv-qualified than the (otherwise
7704 // identical) type of the template-argument. The
7705 // template-parameter is bound directly to the
7706 // template-argument, which must be an lvalue.
7707 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7708 "Only object references allowed here");
7709
7710 if (Arg->getType() == Context.OverloadTy) {
7712 ParamRefType->getPointeeType(),
7713 true,
7714 FoundResult)) {
7715 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7716 return ExprError();
7717 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7718 if (Res.isInvalid())
7719 return ExprError();
7720 Arg = Res.get();
7721 ArgType = Arg->getType();
7722 } else
7723 return ExprError();
7724 }
7725
7727 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7728 return ExprError();
7729 return Arg;
7730 }
7731
7732 // Deal with parameters of type std::nullptr_t.
7733 if (ParamType->isNullPtrType()) {
7734 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7735 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7736 CanonicalConverted =
7737 Context.getCanonicalTemplateArgument(SugaredConverted);
7738 return Arg;
7739 }
7740
7741 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7742 case NPV_NotNullPointer:
7743 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7744 << Arg->getType() << ParamType;
7746 return ExprError();
7747
7748 case NPV_Error:
7749 return ExprError();
7750
7751 case NPV_NullPointer:
7752 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7753 SugaredConverted = TemplateArgument(ParamType,
7754 /*isNullPtr=*/true);
7755 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7756 /*isNullPtr=*/true);
7757 return Arg;
7758 }
7759 }
7760
7761 // -- For a non-type template-parameter of type pointer to data
7762 // member, qualification conversions (4.4) are applied.
7763 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7764
7766 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7767 return ExprError();
7768 return Arg;
7769}
7770
7774
7777 const TemplateArgumentLoc &Arg) {
7778 // C++0x [temp.arg.template]p1:
7779 // A template-argument for a template template-parameter shall be
7780 // the name of a class template or an alias template, expressed as an
7781 // id-expression. When the template-argument names a class template, only
7782 // primary class templates are considered when matching the
7783 // template template argument with the corresponding parameter;
7784 // partial specializations are not considered even if their
7785 // parameter lists match that of the template template parameter.
7786 //
7787
7789 unsigned DiagFoundKind = 0;
7790
7791 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7792 switch (TTP->templateParameterKind()) {
7794 DiagFoundKind = 3;
7795 break;
7797 DiagFoundKind = 2;
7798 break;
7799 default:
7800 DiagFoundKind = 1;
7801 break;
7802 }
7803 Kind = TTP->templateParameterKind();
7804 } else if (isa<ConceptDecl>(Template)) {
7806 DiagFoundKind = 3;
7807 } else if (isa<FunctionTemplateDecl>(Template)) {
7809 DiagFoundKind = 0;
7810 } else if (isa<VarTemplateDecl>(Template)) {
7812 DiagFoundKind = 2;
7813 } else if (isa<ClassTemplateDecl>(Template) ||
7817 DiagFoundKind = 1;
7818 } else {
7819 assert(false && "Unexpected Decl");
7820 }
7821
7822 if (Kind == Param->templateParameterKind()) {
7823 return true;
7824 }
7825
7826 unsigned DiagKind = 0;
7827 switch (Param->templateParameterKind()) {
7829 DiagKind = 2;
7830 break;
7832 DiagKind = 1;
7833 break;
7834 default:
7835 DiagKind = 0;
7836 break;
7837 }
7838 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7839 << DiagKind;
7840 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7841 << DiagFoundKind << Template;
7842 return false;
7843}
7844
7845/// Check a template argument against its corresponding
7846/// template template parameter.
7847///
7848/// This routine implements the semantics of C++ [temp.arg.template].
7849/// It returns true if an error occurred, and false otherwise.
7851 TemplateParameterList *Params,
7853 bool PartialOrdering,
7854 bool *StrictPackMatch) {
7856 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7857 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7858 if (!Template) {
7859 // FIXME: Handle AssumedTemplateNames
7860 // Any dependent template name is fine.
7861 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7862 return false;
7863 }
7864
7865 if (Template->isInvalidDecl())
7866 return true;
7867
7869 return true;
7870 }
7871
7872 // C++1z [temp.arg.template]p3: (DR 150)
7873 // A template-argument matches a template template-parameter P when P
7874 // is at least as specialized as the template-argument A.
7876 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7877 PartialOrdering, StrictPackMatch))
7878 return true;
7879 // P2113
7880 // C++20[temp.func.order]p2
7881 // [...] If both deductions succeed, the partial ordering selects the
7882 // more constrained template (if one exists) as determined below.
7883 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7884 Params->getAssociatedConstraints(ParamsAC);
7885 // C++20[temp.arg.template]p3
7886 // [...] In this comparison, if P is unconstrained, the constraints on A
7887 // are not considered.
7888 if (ParamsAC.empty())
7889 return false;
7890
7891 Template->getAssociatedConstraints(TemplateAC);
7892
7893 bool IsParamAtLeastAsConstrained;
7894 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7895 IsParamAtLeastAsConstrained))
7896 return true;
7897 if (!IsParamAtLeastAsConstrained) {
7898 Diag(Arg.getLocation(),
7899 diag::err_template_template_parameter_not_at_least_as_constrained)
7900 << Template << Param << Arg.getSourceRange();
7901 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7902 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7904 TemplateAC);
7905 return true;
7906 }
7907 return false;
7908}
7909
7911 unsigned HereDiagID,
7912 unsigned ExternalDiagID) {
7913 if (Decl.getLocation().isValid())
7914 return S.Diag(Decl.getLocation(), HereDiagID);
7915
7916 SmallString<128> Str;
7917 llvm::raw_svector_ostream Out(Str);
7919 PP.TerseOutput = 1;
7920 Decl.print(Out, PP);
7921 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7922}
7923
7925 std::optional<SourceRange> ParamRange) {
7927 noteLocation(*this, Decl, diag::note_template_decl_here,
7928 diag::note_template_decl_external);
7929 if (ParamRange && ParamRange->isValid()) {
7930 assert(Decl.getLocation().isValid() &&
7931 "Parameter range has location when Decl does not");
7932 DB << *ParamRange;
7933 }
7934}
7935
7937 noteLocation(*this, Decl, diag::note_template_param_here,
7938 diag::note_template_param_external);
7939}
7940
7941/// Given a non-type template argument that refers to a
7942/// declaration and the type of its corresponding non-type template
7943/// parameter, produce an expression that properly refers to that
7944/// declaration.
7946 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7948 // C++ [temp.param]p8:
7949 //
7950 // A non-type template-parameter of type "array of T" or
7951 // "function returning T" is adjusted to be of type "pointer to
7952 // T" or "pointer to function returning T", respectively.
7953 if (ParamType->isArrayType())
7954 ParamType = Context.getArrayDecayedType(ParamType);
7955 else if (ParamType->isFunctionType())
7956 ParamType = Context.getPointerType(ParamType);
7957
7958 // For a NULL non-type template argument, return nullptr casted to the
7959 // parameter's type.
7960 if (Arg.getKind() == TemplateArgument::NullPtr) {
7961 return ImpCastExprToType(
7962 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7963 ParamType,
7964 ParamType->getAs<MemberPointerType>()
7965 ? CK_NullToMemberPointer
7966 : CK_NullToPointer);
7967 }
7968 assert(Arg.getKind() == TemplateArgument::Declaration &&
7969 "Only declaration template arguments permitted here");
7970
7971 ValueDecl *VD = Arg.getAsDecl();
7972
7973 CXXScopeSpec SS;
7974 if (ParamType->isMemberPointerType()) {
7975 // If this is a pointer to member, we need to use a qualified name to
7976 // form a suitable pointer-to-member constant.
7977 assert(VD->getDeclContext()->isRecord() &&
7978 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7980 CanQualType ClassType =
7981 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7982 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7983 SS.MakeTrivial(Context, Qualifier, Loc);
7984 }
7985
7987 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7988 if (RefExpr.isInvalid())
7989 return ExprError();
7990
7991 // For a pointer, the argument declaration is the pointee. Take its address.
7992 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7993 if (ParamType->isPointerType() && !ElemT.isNull() &&
7994 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7995 // Decay an array argument if we want a pointer to its first element.
7996 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7997 if (RefExpr.isInvalid())
7998 return ExprError();
7999 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8000 // For any other pointer, take the address (or form a pointer-to-member).
8001 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8002 if (RefExpr.isInvalid())
8003 return ExprError();
8004 } else if (ParamType->isRecordType()) {
8005 assert(isa<TemplateParamObjectDecl>(VD) &&
8006 "arg for class template param not a template parameter object");
8007 // No conversions apply in this case.
8008 return RefExpr;
8009 } else {
8010 assert(ParamType->isReferenceType() &&
8011 "unexpected type for decl template argument");
8012 if (NonTypeTemplateParmDecl *NTTP =
8013 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
8014 QualType TemplateParamType = NTTP->getType();
8015 const AutoType *AT = TemplateParamType->getAs<AutoType>();
8016 if (AT && AT->isDecltypeAuto()) {
8018 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
8019 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
8020 /*PackIndex=*/std::nullopt,
8021 /*RefParam=*/true, /*Final=*/true);
8022 }
8023 }
8024 }
8025
8026 // At this point we should have the right value category.
8027 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8028 "value kind mismatch for non-type template argument");
8029
8030 // The type of the template parameter can differ from the type of the
8031 // argument in various ways; convert it now if necessary.
8032 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8033 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8034 CastKind CK;
8035 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8036 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
8037 CK = CK_NoOp;
8038 } else if (ParamType->isVoidPointerType() &&
8039 RefExpr.get()->getType()->isPointerType()) {
8040 CK = CK_BitCast;
8041 } else {
8042 // FIXME: Pointers to members can need conversion derived-to-base or
8043 // base-to-derived conversions. We currently don't retain enough
8044 // information to convert properly (we need to track a cast path or
8045 // subobject number in the template argument).
8046 llvm_unreachable(
8047 "unexpected conversion required for non-type template argument");
8048 }
8049 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8050 RefExpr.get()->getValueKind());
8051 }
8052
8053 return RefExpr;
8054}
8055
8056/// Construct a new expression that refers to the given
8057/// integral template argument with the given source-location
8058/// information.
8059///
8060/// This routine takes care of the mapping from an integral template
8061/// argument (which may have any integral type) to the appropriate
8062/// literal value.
8064 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8065 assert(OrigT->isIntegralOrEnumerationType());
8066
8067 // If this is an enum type that we're instantiating, we need to use an integer
8068 // type the same size as the enumerator. We don't want to build an
8069 // IntegerLiteral with enum type. The integer type of an enum type can be of
8070 // any integral type with C++11 enum classes, make sure we create the right
8071 // type of literal for it.
8072 QualType T = OrigT;
8073 if (const auto *ED = OrigT->getAsEnumDecl())
8074 T = ED->getIntegerType();
8075
8076 Expr *E;
8077 if (T->isAnyCharacterType()) {
8079 if (T->isWideCharType())
8081 else if (T->isChar8Type() && S.getLangOpts().Char8)
8083 else if (T->isChar16Type())
8085 else if (T->isChar32Type())
8087 else
8089
8090 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8091 } else if (T->isBooleanType()) {
8092 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8093 } else {
8094 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8095 }
8096
8097 if (OrigT->isEnumeralType()) {
8098 // FIXME: This is a hack. We need a better way to handle substituted
8099 // non-type template parameters.
8100 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8101 nullptr, S.CurFPFeatureOverrides(),
8102 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8103 Loc, Loc);
8104 }
8105
8106 return E;
8107}
8108
8110 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8111 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8112 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8113 ILE->setType(T);
8114 return ILE;
8115 };
8116
8117 switch (Val.getKind()) {
8119 // This cannot occur in a template argument at all.
8120 case APValue::Array:
8121 case APValue::Struct:
8122 case APValue::Union:
8123 // These can only occur within a template parameter object, which is
8124 // represented as a TemplateArgument::Declaration.
8125 llvm_unreachable("unexpected template argument value");
8126
8127 case APValue::Int:
8129 Loc);
8130
8131 case APValue::Float:
8132 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8133 T, Loc);
8134
8137 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8138 Val.getFixedPoint().getScale());
8139
8140 case APValue::ComplexInt: {
8141 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8143 S, ElemT, Val.getComplexIntReal(), Loc),
8145 S, ElemT, Val.getComplexIntImag(), Loc)});
8146 }
8147
8148 case APValue::ComplexFloat: {
8149 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8150 return MakeInitList(
8152 ElemT, Loc),
8154 ElemT, Loc)});
8155 }
8156
8157 case APValue::Vector: {
8158 QualType ElemT = T->castAs<VectorType>()->getElementType();
8160 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8162 S, ElemT, Val.getVectorElt(I), Loc));
8163 return MakeInitList(Elts);
8164 }
8165
8166 case APValue::Matrix:
8167 llvm_unreachable("Matrix template argument expression not yet supported");
8168
8169 case APValue::None:
8171 llvm_unreachable("Unexpected APValue kind.");
8172 case APValue::LValue:
8174 // There isn't necessarily a valid equivalent source-level syntax for
8175 // these; in particular, a naive lowering might violate access control.
8176 // So for now we lower to a ConstantExpr holding the value, wrapped around
8177 // an OpaqueValueExpr.
8178 // FIXME: We should have a better representation for this.
8180 if (T->isReferenceType()) {
8181 T = T->getPointeeType();
8182 VK = VK_LValue;
8183 }
8184 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8185 return ConstantExpr::Create(S.Context, OVE, Val);
8186 }
8187 llvm_unreachable("Unhandled APValue::ValueKind enum");
8188}
8189
8192 SourceLocation Loc) {
8193 switch (Arg.getKind()) {
8199 llvm_unreachable("not a non-type template argument");
8200
8202 return Arg.getAsExpr();
8203
8207 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8208
8211 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8212
8215 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8216 }
8217 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8218}
8219
8220/// Match two template parameters within template parameter lists.
8222 Sema &S, NamedDecl *New,
8223 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8224 const NamedDecl *OldInstFrom, bool Complain,
8226 // Check the actual kind (type, non-type, template).
8227 if (Old->getKind() != New->getKind()) {
8228 if (Complain) {
8229 unsigned NextDiag = diag::err_template_param_different_kind;
8230 if (TemplateArgLoc.isValid()) {
8231 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8232 NextDiag = diag::note_template_param_different_kind;
8233 }
8234 S.Diag(New->getLocation(), NextDiag)
8235 << (Kind != Sema::TPL_TemplateMatch);
8236 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8237 << (Kind != Sema::TPL_TemplateMatch);
8238 }
8239
8240 return false;
8241 }
8242
8243 // Check that both are parameter packs or neither are parameter packs.
8244 // However, if we are matching a template template argument to a
8245 // template template parameter, the template template parameter can have
8246 // a parameter pack where the template template argument does not.
8247 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8248 if (Complain) {
8249 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8250 if (TemplateArgLoc.isValid()) {
8251 S.Diag(TemplateArgLoc,
8252 diag::err_template_arg_template_params_mismatch);
8253 NextDiag = diag::note_template_parameter_pack_non_pack;
8254 }
8255
8256 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8258 : 2;
8259 S.Diag(New->getLocation(), NextDiag)
8260 << ParamKind << New->isParameterPack();
8261 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8262 << ParamKind << Old->isParameterPack();
8263 }
8264
8265 return false;
8266 }
8267 // For non-type template parameters, check the type of the parameter.
8268 if (NonTypeTemplateParmDecl *OldNTTP =
8269 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8271
8272 // If we are matching a template template argument to a template
8273 // template parameter and one of the non-type template parameter types
8274 // is dependent, then we must wait until template instantiation time
8275 // to actually compare the arguments.
8277 (!OldNTTP->getType()->isDependentType() &&
8278 !NewNTTP->getType()->isDependentType())) {
8279 // C++20 [temp.over.link]p6:
8280 // Two [non-type] template-parameters are equivalent [if] they have
8281 // equivalent types ignoring the use of type-constraints for
8282 // placeholder types
8283 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8284 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8285 if (!S.Context.hasSameType(OldType, NewType)) {
8286 if (Complain) {
8287 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8288 if (TemplateArgLoc.isValid()) {
8289 S.Diag(TemplateArgLoc,
8290 diag::err_template_arg_template_params_mismatch);
8291 NextDiag = diag::note_template_nontype_parm_different_type;
8292 }
8293 S.Diag(NewNTTP->getLocation(), NextDiag)
8294 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8295 S.Diag(OldNTTP->getLocation(),
8296 diag::note_template_nontype_parm_prev_declaration)
8297 << OldNTTP->getType();
8298 }
8299 return false;
8300 }
8301 }
8302 }
8303 // For template template parameters, check the template parameter types.
8304 // The template parameter lists of template template
8305 // parameters must agree.
8306 else if (TemplateTemplateParmDecl *OldTTP =
8307 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8309 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8310 return false;
8312 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8313 OldTTP->getTemplateParameters(), Complain,
8316 : Kind),
8317 TemplateArgLoc))
8318 return false;
8319 }
8320
8324 const Expr *NewC = nullptr, *OldC = nullptr;
8325
8327 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8328 NewC = TC->getImmediatelyDeclaredConstraint();
8329 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8330 OldC = TC->getImmediatelyDeclaredConstraint();
8331 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8332 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8333 ->getPlaceholderTypeConstraint())
8334 NewC = E;
8335 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8336 ->getPlaceholderTypeConstraint())
8337 OldC = E;
8338 } else
8339 llvm_unreachable("unexpected template parameter type");
8340
8341 auto Diagnose = [&] {
8342 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8343 diag::err_template_different_type_constraint);
8344 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8345 diag::note_template_prev_declaration) << /*declaration*/0;
8346 };
8347
8348 if (!NewC != !OldC) {
8349 if (Complain)
8350 Diagnose();
8351 return false;
8352 }
8353
8354 if (NewC) {
8355 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8356 NewC)) {
8357 if (Complain)
8358 Diagnose();
8359 return false;
8360 }
8361 }
8362 }
8363
8364 return true;
8365}
8366
8367/// Diagnose a known arity mismatch when comparing template argument
8368/// lists.
8369static
8374 SourceLocation TemplateArgLoc) {
8375 unsigned NextDiag = diag::err_template_param_list_different_arity;
8376 if (TemplateArgLoc.isValid()) {
8377 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8378 NextDiag = diag::note_template_param_list_different_arity;
8379 }
8380 S.Diag(New->getTemplateLoc(), NextDiag)
8381 << (New->size() > Old->size())
8382 << (Kind != Sema::TPL_TemplateMatch)
8383 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8384 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8385 << (Kind != Sema::TPL_TemplateMatch)
8386 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8387}
8388
8391 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8392 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8393 if (Old->size() != New->size()) {
8394 if (Complain)
8396 TemplateArgLoc);
8397
8398 return false;
8399 }
8400
8401 // C++0x [temp.arg.template]p3:
8402 // A template-argument matches a template template-parameter (call it P)
8403 // when each of the template parameters in the template-parameter-list of
8404 // the template-argument's corresponding class template or alias template
8405 // (call it A) matches the corresponding template parameter in the
8406 // template-parameter-list of P. [...]
8407 TemplateParameterList::iterator NewParm = New->begin();
8408 TemplateParameterList::iterator NewParmEnd = New->end();
8409 for (TemplateParameterList::iterator OldParm = Old->begin(),
8410 OldParmEnd = Old->end();
8411 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8412 if (NewParm == NewParmEnd) {
8413 if (Complain)
8415 TemplateArgLoc);
8416 return false;
8417 }
8418 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8419 OldInstFrom, Complain, Kind,
8420 TemplateArgLoc))
8421 return false;
8422 }
8423
8424 // Make sure we exhausted all of the arguments.
8425 if (NewParm != NewParmEnd) {
8426 if (Complain)
8428 TemplateArgLoc);
8429
8430 return false;
8431 }
8432
8433 if (Kind != TPL_TemplateParamsEquivalent) {
8434 const Expr *NewRC = New->getRequiresClause();
8435 const Expr *OldRC = Old->getRequiresClause();
8436
8437 auto Diagnose = [&] {
8438 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8439 diag::err_template_different_requires_clause);
8440 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8441 diag::note_template_prev_declaration) << /*declaration*/0;
8442 };
8443
8444 if (!NewRC != !OldRC) {
8445 if (Complain)
8446 Diagnose();
8447 return false;
8448 }
8449
8450 if (NewRC) {
8451 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8452 NewRC)) {
8453 if (Complain)
8454 Diagnose();
8455 return false;
8456 }
8457 }
8458 }
8459
8460 return true;
8461}
8462
8463bool
8465 if (!S)
8466 return false;
8467
8468 // Find the nearest enclosing declaration scope.
8469 S = S->getDeclParent();
8470
8471 // C++ [temp.pre]p6: [P2096]
8472 // A template, explicit specialization, or partial specialization shall not
8473 // have C linkage.
8474 DeclContext *Ctx = S->getEntity();
8475 if (Ctx && Ctx->isExternCContext()) {
8476 SourceRange Range =
8477 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8478 ? TemplateParams->getParam(0)->getSourceRange()
8479 : TemplateParams->getSourceRange();
8480 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8481 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8482 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8483 return true;
8484 }
8485 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8486
8487 // C++ [temp]p2:
8488 // A template-declaration can appear only as a namespace scope or
8489 // class scope declaration.
8490 // C++ [temp.expl.spec]p3:
8491 // An explicit specialization may be declared in any scope in which the
8492 // corresponding primary template may be defined.
8493 // C++ [temp.class.spec]p6: [P2096]
8494 // A partial specialization may be declared in any scope in which the
8495 // corresponding primary template may be defined.
8496 if (Ctx) {
8497 if (Ctx->isFileContext())
8498 return false;
8499 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8500 // C++ [temp.mem]p2:
8501 // A local class shall not have member templates.
8502 if (RD->isLocalClass())
8503 return Diag(TemplateParams->getTemplateLoc(),
8504 diag::err_template_inside_local_class)
8505 << TemplateParams->getSourceRange();
8506 else
8507 return false;
8508 }
8509 }
8510
8511 return Diag(TemplateParams->getTemplateLoc(),
8512 diag::err_template_outside_namespace_or_class_scope)
8513 << TemplateParams->getSourceRange();
8514}
8515
8516/// Determine what kind of template specialization the given declaration
8517/// is.
8519 if (!D)
8520 return TSK_Undeclared;
8521
8522 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8523 return Record->getTemplateSpecializationKind();
8524 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8525 return Function->getTemplateSpecializationKind();
8526 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8527 return Var->getTemplateSpecializationKind();
8528
8529 return TSK_Undeclared;
8530}
8531
8532/// Check whether a specialization is well-formed in the current
8533/// context.
8534///
8535/// This routine determines whether a template specialization can be declared
8536/// in the current context (C++ [temp.expl.spec]p2).
8537///
8538/// \param S the semantic analysis object for which this check is being
8539/// performed.
8540///
8541/// \param Specialized the entity being specialized or instantiated, which
8542/// may be a kind of template (class template, function template, etc.) or
8543/// a member of a class template (member function, static data member,
8544/// member class).
8545///
8546/// \param PrevDecl the previous declaration of this entity, if any.
8547///
8548/// \param Loc the location of the explicit specialization or instantiation of
8549/// this entity.
8550///
8551/// \param IsPartialSpecialization whether this is a partial specialization of
8552/// a class template.
8553///
8554/// \returns true if there was an error that we cannot recover from, false
8555/// otherwise.
8557 NamedDecl *Specialized,
8558 NamedDecl *PrevDecl,
8559 SourceLocation Loc,
8561 // Keep these "kind" numbers in sync with the %select statements in the
8562 // various diagnostics emitted by this routine.
8563 int EntityKind = 0;
8564 if (isa<ClassTemplateDecl>(Specialized))
8565 EntityKind = IsPartialSpecialization? 1 : 0;
8566 else if (isa<VarTemplateDecl>(Specialized))
8567 EntityKind = IsPartialSpecialization ? 3 : 2;
8568 else if (isa<FunctionTemplateDecl>(Specialized))
8569 EntityKind = 4;
8570 else if (isa<CXXMethodDecl>(Specialized))
8571 EntityKind = 5;
8572 else if (isa<VarDecl>(Specialized))
8573 EntityKind = 6;
8574 else if (isa<RecordDecl>(Specialized))
8575 EntityKind = 7;
8576 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8577 EntityKind = 8;
8578 else {
8579 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8580 << S.getLangOpts().CPlusPlus11;
8581 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8582 return true;
8583 }
8584
8585 // C++ [temp.expl.spec]p2:
8586 // An explicit specialization may be declared in any scope in which
8587 // the corresponding primary template may be defined.
8589 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8590 << Specialized;
8591 return true;
8592 }
8593
8594 // C++ [temp.class.spec]p6:
8595 // A class template partial specialization may be declared in any
8596 // scope in which the primary template may be defined.
8597 DeclContext *SpecializedContext =
8598 Specialized->getDeclContext()->getRedeclContext();
8600
8601 // Make sure that this redeclaration (or definition) occurs in the same
8602 // scope or an enclosing namespace.
8603 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8604 : DC->Equals(SpecializedContext))) {
8605 if (isa<TranslationUnitDecl>(SpecializedContext))
8606 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8607 << EntityKind << Specialized;
8608 else {
8609 auto *ND = cast<NamedDecl>(SpecializedContext);
8610 int Diag = diag::err_template_spec_redecl_out_of_scope;
8611 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8612 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8613 S.Diag(Loc, Diag) << EntityKind << Specialized
8614 << ND << isa<CXXRecordDecl>(ND);
8615 }
8616
8617 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8618
8619 // Don't allow specializing in the wrong class during error recovery.
8620 // Otherwise, things can go horribly wrong.
8621 if (DC->isRecord())
8622 return true;
8623 }
8624
8625 return false;
8626}
8627
8629 if (!E->isTypeDependent())
8630 return SourceLocation();
8631 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8632 Checker.TraverseStmt(E);
8633 if (Checker.MatchLoc.isInvalid())
8634 return E->getSourceRange();
8635 return Checker.MatchLoc;
8636}
8637
8638static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8639 if (!TL.getType()->isDependentType())
8640 return SourceLocation();
8641 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8642 Checker.TraverseTypeLoc(TL);
8643 if (Checker.MatchLoc.isInvalid())
8644 return TL.getSourceRange();
8645 return Checker.MatchLoc;
8646}
8647
8648/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8649/// that checks non-type template partial specialization arguments.
8651 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8652 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8653 bool HasError = false;
8654 for (unsigned I = 0; I != NumArgs; ++I) {
8655 if (Args[I].getKind() == TemplateArgument::Pack) {
8657 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8658 Args[I].pack_size(), IsDefaultArgument))
8659 return true;
8660
8661 continue;
8662 }
8663
8664 if (Args[I].getKind() != TemplateArgument::Expression)
8665 continue;
8666
8667 Expr *ArgExpr = Args[I].getAsExpr();
8668 if (ArgExpr->containsErrors()) {
8669 HasError = true;
8670 continue;
8671 }
8672
8673 // We can have a pack expansion of any of the bullets below.
8674 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8675 ArgExpr = Expansion->getPattern();
8676
8677 // Strip off any implicit casts we added as part of type checking.
8678 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8679 ArgExpr = ICE->getSubExpr();
8680
8681 // C++ [temp.class.spec]p8:
8682 // A non-type argument is non-specialized if it is the name of a
8683 // non-type parameter. All other non-type arguments are
8684 // specialized.
8685 //
8686 // Below, we check the two conditions that only apply to
8687 // specialized non-type arguments, so skip any non-specialized
8688 // arguments.
8689 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8690 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8691 continue;
8692
8693 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8694 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8695 continue;
8696 }
8697
8698 // C++ [temp.class.spec]p9:
8699 // Within the argument list of a class template partial
8700 // specialization, the following restrictions apply:
8701 // -- A partially specialized non-type argument expression
8702 // shall not involve a template parameter of the partial
8703 // specialization except when the argument expression is a
8704 // simple identifier.
8705 // -- The type of a template parameter corresponding to a
8706 // specialized non-type argument shall not be dependent on a
8707 // parameter of the specialization.
8708 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8709 // We implement a compromise between the original rules and DR1315:
8710 // -- A specialized non-type template argument shall not be
8711 // type-dependent and the corresponding template parameter
8712 // shall have a non-dependent type.
8713 SourceRange ParamUseRange =
8714 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8715 if (ParamUseRange.isValid()) {
8716 if (IsDefaultArgument) {
8717 S.Diag(TemplateNameLoc,
8718 diag::err_dependent_non_type_arg_in_partial_spec);
8719 S.Diag(ParamUseRange.getBegin(),
8720 diag::note_dependent_non_type_default_arg_in_partial_spec)
8721 << ParamUseRange;
8722 } else {
8723 S.Diag(ParamUseRange.getBegin(),
8724 diag::err_dependent_non_type_arg_in_partial_spec)
8725 << ParamUseRange;
8726 }
8727 return true;
8728 }
8729
8730 ParamUseRange = findTemplateParameter(
8731 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8732 if (ParamUseRange.isValid()) {
8733 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8734 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8735 << Param->getType();
8737 return true;
8738 }
8739 }
8740
8741 return HasError;
8742}
8743
8745 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8746 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8747 // We have to be conservative when checking a template in a dependent
8748 // context.
8749 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8750 return false;
8751
8752 TemplateParameterList *TemplateParams =
8753 PrimaryTemplate->getTemplateParameters();
8754 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8756 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8757 if (!Param)
8758 continue;
8759
8760 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8761 Param, &TemplateArgs[I],
8762 1, I >= NumExplicit))
8763 return true;
8764 }
8765
8766 return false;
8767}
8768
8770 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8771 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8773 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8774 assert(TUK != TagUseKind::Reference && "References are not specializations");
8775
8776 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8777 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8778 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8779
8780 // Find the class template we're specializing
8781 TemplateName Name = TemplateId.Template.get();
8783 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8784
8785 if (!ClassTemplate) {
8786 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8787 << (Name.getAsTemplateDecl() &&
8789 return true;
8790 }
8791
8792 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8793 auto Message = DSA->getMessage();
8794 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8795 << ClassTemplate << !Message.empty() << Message;
8796 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8797 }
8798
8799 if (S->isTemplateParamScope())
8800 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8801
8802 DeclContext *DC = ClassTemplate->getDeclContext();
8803
8804 bool isMemberSpecialization = false;
8805 bool isPartialSpecialization = false;
8806
8807 if (SS.isSet()) {
8808 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8809 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8810 TemplateNameLoc, &TemplateId,
8811 /*IsMemberSpecialization=*/false))
8812 return true;
8813 }
8814
8815 // Check the validity of the template headers that introduce this
8816 // template.
8817 // FIXME: We probably shouldn't complain about these headers for
8818 // friend declarations.
8819 bool Invalid = false;
8820 TemplateParameterList *TemplateParams =
8822 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8823 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8824 if (Invalid)
8825 return true;
8826
8827 // Check that we can declare a template specialization here.
8828 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8829 return true;
8830
8831 if (TemplateParams && DC->isDependentContext()) {
8832 ContextRAII SavedContext(*this, DC);
8834 return true;
8835 }
8836
8837 if (TemplateParams && TemplateParams->size() > 0) {
8838 isPartialSpecialization = true;
8839
8840 if (TUK == TagUseKind::Friend) {
8841 Diag(KWLoc, diag::err_partial_specialization_friend)
8842 << SourceRange(LAngleLoc, RAngleLoc);
8843 return true;
8844 }
8845
8846 // C++ [temp.class.spec]p10:
8847 // The template parameter list of a specialization shall not
8848 // contain default template argument values.
8849 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8850 Decl *Param = TemplateParams->getParam(I);
8851 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8852 if (TTP->hasDefaultArgument()) {
8853 Diag(TTP->getDefaultArgumentLoc(),
8854 diag::err_default_arg_in_partial_spec);
8855 TTP->removeDefaultArgument();
8856 }
8857 } else if (NonTypeTemplateParmDecl *NTTP
8858 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8859 if (NTTP->hasDefaultArgument()) {
8860 Diag(NTTP->getDefaultArgumentLoc(),
8861 diag::err_default_arg_in_partial_spec)
8862 << NTTP->getDefaultArgument().getSourceRange();
8863 NTTP->removeDefaultArgument();
8864 }
8865 } else {
8867 if (TTP->hasDefaultArgument()) {
8869 diag::err_default_arg_in_partial_spec)
8871 TTP->removeDefaultArgument();
8872 }
8873 }
8874 }
8875 } else if (TemplateParams) {
8876 if (TUK == TagUseKind::Friend)
8877 Diag(KWLoc, diag::err_template_spec_friend)
8879 SourceRange(TemplateParams->getTemplateLoc(),
8880 TemplateParams->getRAngleLoc()))
8881 << SourceRange(LAngleLoc, RAngleLoc);
8882 } else {
8883 assert(TUK == TagUseKind::Friend &&
8884 "should have a 'template<>' for this decl");
8885 }
8886
8887 // Check that the specialization uses the same tag kind as the
8888 // original template.
8890 assert(Kind != TagTypeKind::Enum &&
8891 "Invalid enum tag in class template spec!");
8892 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8893 TUK == TagUseKind::Definition, KWLoc,
8894 ClassTemplate->getIdentifier())) {
8895 Diag(KWLoc, diag::err_use_with_wrong_tag)
8896 << ClassTemplate
8898 ClassTemplate->getTemplatedDecl()->getKindName());
8899 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8900 diag::note_previous_use);
8901 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8902 }
8903
8904 // Translate the parser's template argument list in our AST format.
8905 TemplateArgumentListInfo TemplateArgs =
8906 makeTemplateArgumentListInfo(*this, TemplateId);
8907
8908 // Check for unexpanded parameter packs in any of the template arguments.
8909 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8910 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8911 isPartialSpecialization
8914 return true;
8915
8916 // Check that the template argument list is well-formed for this
8917 // template.
8919 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8920 /*DefaultArgs=*/{},
8921 /*PartialTemplateArgs=*/false, CTAI,
8922 /*UpdateArgsWithConversions=*/true))
8923 return true;
8924
8925 // Find the class template (partial) specialization declaration that
8926 // corresponds to these arguments.
8927 if (isPartialSpecialization) {
8929 TemplateArgs.size(),
8930 CTAI.CanonicalConverted))
8931 return true;
8932
8933 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8934 // also do it during instantiation.
8935 if (!Name.isDependent() &&
8936 !TemplateSpecializationType::anyDependentTemplateArguments(
8937 TemplateArgs, CTAI.CanonicalConverted)) {
8938 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8939 << ClassTemplate->getDeclName();
8940 isPartialSpecialization = false;
8941 Invalid = true;
8942 }
8943 }
8944
8945 void *InsertPos = nullptr;
8946 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8947
8948 if (isPartialSpecialization)
8949 PrevDecl = ClassTemplate->findPartialSpecialization(
8950 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8951 else
8952 PrevDecl =
8953 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8954
8956
8957 // Check whether we can declare a class template specialization in
8958 // the current scope.
8959 if (TUK != TagUseKind::Friend &&
8961 TemplateNameLoc,
8962 isPartialSpecialization))
8963 return true;
8964
8965 if (!isPartialSpecialization) {
8966 // Create a new class template specialization declaration node for
8967 // this explicit specialization or friend declaration.
8969 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8970 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8971 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8973 if (TemplateParameterLists.size() > 0) {
8974 Specialization->setTemplateParameterListsInfo(Context,
8975 TemplateParameterLists);
8976 }
8977
8978 if (!PrevDecl)
8979 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8980 } else {
8982 Context.getCanonicalTemplateSpecializationType(
8984 TemplateName(ClassTemplate->getCanonicalDecl()),
8985 CTAI.CanonicalConverted));
8986 if (Context.hasSameType(
8987 CanonType,
8988 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8989 (!Context.getLangOpts().CPlusPlus20 ||
8990 !TemplateParams->hasAssociatedConstraints())) {
8991 // C++ [temp.class.spec]p9b3:
8992 //
8993 // -- The argument list of the specialization shall not be identical
8994 // to the implicit argument list of the primary template.
8995 //
8996 // This rule has since been removed, because it's redundant given DR1495,
8997 // but we keep it because it produces better diagnostics and recovery.
8998 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8999 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9000 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9001 return CheckClassTemplate(
9002 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9003 TemplateNameLoc, Attr, TemplateParams, AS_none,
9004 /*ModulePrivateLoc=*/SourceLocation(),
9005 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9006 TemplateParameterLists.data());
9007 }
9008
9009 // Create a new class template partial specialization declaration node.
9011 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9014 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9015 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9016 Partial->setTemplateArgsAsWritten(TemplateArgs);
9017 SetNestedNameSpecifier(*this, Partial, SS);
9018 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9020 Context, TemplateParameterLists.drop_back(1));
9021 }
9022
9023 if (!PrevPartial)
9024 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9025 Specialization = Partial;
9026
9027 // If we are providing an explicit specialization of a member class
9028 // template specialization, make a note of that.
9029 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9030 PrevPartial->setMemberSpecialization();
9031
9033 }
9034
9035 // C++ [temp.expl.spec]p6:
9036 // If a template, a member template or the member of a class template is
9037 // explicitly specialized then that specialization shall be declared
9038 // before the first use of that specialization that would cause an implicit
9039 // instantiation to take place, in every translation unit in which such a
9040 // use occurs; no diagnostic is required.
9041 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9042 bool Okay = false;
9043 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9044 // Is there any previous explicit specialization declaration?
9046 Okay = true;
9047 break;
9048 }
9049 }
9050
9051 if (!Okay) {
9052 SourceRange Range(TemplateNameLoc, RAngleLoc);
9053 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9054 << Context.getCanonicalTagType(Specialization) << Range;
9055
9056 Diag(PrevDecl->getPointOfInstantiation(),
9057 diag::note_instantiation_required_here)
9058 << (PrevDecl->getTemplateSpecializationKind()
9060 return true;
9061 }
9062 }
9063
9064 // If this is not a friend, note that this is an explicit specialization.
9065 if (TUK != TagUseKind::Friend)
9066 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9067
9068 // Check that this isn't a redefinition of this specialization.
9069 if (TUK == TagUseKind::Definition) {
9070 RecordDecl *Def = Specialization->getDefinition();
9071 NamedDecl *Hidden = nullptr;
9072 bool HiddenDefVisible = false;
9073 if (Def && SkipBody &&
9074 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9075 SkipBody->ShouldSkip = true;
9076 SkipBody->Previous = Def;
9077 if (!HiddenDefVisible && Hidden)
9079 } else if (Def) {
9080 SourceRange Range(TemplateNameLoc, RAngleLoc);
9081 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9082 Diag(Def->getLocation(), diag::note_previous_definition);
9083 Specialization->setInvalidDecl();
9084 return true;
9085 }
9086 }
9087
9090
9091 // Add alignment attributes if necessary; these attributes are checked when
9092 // the ASTContext lays out the structure.
9093 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9094 if (LangOpts.HLSL)
9095 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9098 }
9099
9100 if (ModulePrivateLoc.isValid())
9101 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9102 << (isPartialSpecialization? 1 : 0)
9103 << FixItHint::CreateRemoval(ModulePrivateLoc);
9104
9105 // C++ [temp.expl.spec]p9:
9106 // A template explicit specialization is in the scope of the
9107 // namespace in which the template was defined.
9108 //
9109 // We actually implement this paragraph where we set the semantic
9110 // context (in the creation of the ClassTemplateSpecializationDecl),
9111 // but we also maintain the lexical context where the actual
9112 // definition occurs.
9113 Specialization->setLexicalDeclContext(CurContext);
9114
9115 // We may be starting the definition of this specialization.
9116 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9117 Specialization->startDefinition();
9118
9119 if (TUK == TagUseKind::Friend) {
9120 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9121 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9122 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9124 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9125 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9126
9127 // Build the fully-sugared type for this class template
9128 // specialization as the user wrote in the specialization
9129 // itself. This means that we'll pretty-print the type retrieved
9130 // from the specialization's declaration the way that the user
9131 // actually wrote the specialization, rather than formatting the
9132 // name based on the "canonical" representation used to store the
9133 // template arguments in the specialization.
9135 TemplateNameLoc,
9136 WrittenTy,
9137 /*FIXME:*/KWLoc);
9138 Friend->setAccess(AS_public);
9139 CurContext->addDecl(Friend);
9140 } else {
9141 // Add the specialization into its lexical context, so that it can
9142 // be seen when iterating through the list of declarations in that
9143 // context. However, specializations are not found by name lookup.
9144 CurContext->addDecl(Specialization);
9145 }
9146
9147 if (SkipBody && SkipBody->ShouldSkip)
9148 return SkipBody->Previous;
9149
9150 Specialization->setInvalidDecl(Invalid);
9152 return Specialization;
9153}
9154
9156 MultiTemplateParamsArg TemplateParameterLists,
9157 Declarator &D) {
9158 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9159 ActOnDocumentableDecl(NewDecl);
9160 return NewDecl;
9161}
9162
9164 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9165 const IdentifierInfo *Name, SourceLocation NameLoc) {
9166 DeclContext *DC = CurContext;
9167
9168 if (!DC->getRedeclContext()->isFileContext()) {
9169 Diag(NameLoc,
9170 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9171 return nullptr;
9172 }
9173
9174 if (TemplateParameterLists.size() > 1) {
9175 Diag(NameLoc, diag::err_concept_extra_headers);
9176 return nullptr;
9177 }
9178
9179 TemplateParameterList *Params = TemplateParameterLists.front();
9180
9181 if (Params->size() == 0) {
9182 Diag(NameLoc, diag::err_concept_no_parameters);
9183 return nullptr;
9184 }
9185
9186 // Ensure that the parameter pack, if present, is the last parameter in the
9187 // template.
9188 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9189 ParamEnd = Params->end();
9190 ParamIt != ParamEnd; ++ParamIt) {
9191 Decl const *Param = *ParamIt;
9192 if (Param->isParameterPack()) {
9193 if (++ParamIt == ParamEnd)
9194 break;
9195 Diag(Param->getLocation(),
9196 diag::err_template_param_pack_must_be_last_template_parameter);
9197 return nullptr;
9198 }
9199 }
9200
9201 ConceptDecl *NewDecl =
9202 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9203
9204 if (NewDecl->hasAssociatedConstraints()) {
9205 // C++2a [temp.concept]p4:
9206 // A concept shall not have associated constraints.
9207 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9208 NewDecl->setInvalidDecl();
9209 }
9210
9211 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9212 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9214 LookupName(Previous, S);
9215 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9216 /*AllowInlineNamespace*/ false);
9217
9218 // We cannot properly handle redeclarations until we parse the constraint
9219 // expression, so only inject the name if we are sure we are not redeclaring a
9220 // symbol
9221 if (Previous.empty())
9222 PushOnScopeChains(NewDecl, S, true);
9223
9224 return NewDecl;
9225}
9226
9228 bool Found = false;
9229 LookupResult::Filter F = R.makeFilter();
9230 while (F.hasNext()) {
9231 NamedDecl *D = F.next();
9232 if (D == C) {
9233 F.erase();
9234 Found = true;
9235 break;
9236 }
9237 }
9238 F.done();
9239 return Found;
9240}
9241
9244 Expr *ConstraintExpr,
9245 const ParsedAttributesView &Attrs) {
9246 assert(!C->hasDefinition() && "Concept already defined");
9247 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9248 C->setInvalidDecl();
9249 return nullptr;
9250 }
9251 C->setDefinition(ConstraintExpr);
9252 ProcessDeclAttributeList(S, C, Attrs);
9253
9254 // Check for conflicting previous declaration.
9255 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9256 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9258 LookupName(Previous, S);
9259 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9260 /*AllowInlineNamespace*/ false);
9261 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9262 bool AddToScope = true;
9263 CheckConceptRedefinition(C, Previous, AddToScope);
9264
9266 if (!WasAlreadyAdded && AddToScope)
9267 PushOnScopeChains(C, S);
9268
9269 return C;
9270}
9271
9273 LookupResult &Previous, bool &AddToScope) {
9274 AddToScope = true;
9275
9276 if (Previous.empty())
9277 return;
9278
9279 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9280 if (!OldConcept) {
9281 auto *Old = Previous.getRepresentativeDecl();
9282 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9283 << NewDecl->getDeclName();
9284 notePreviousDefinition(Old, NewDecl->getLocation());
9285 AddToScope = false;
9286 return;
9287 }
9288 // Check if we can merge with a concept declaration.
9289 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9290 if (!IsSame) {
9291 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9292 << NewDecl->getDeclName();
9293 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9294 AddToScope = false;
9295 return;
9296 }
9297 if (hasReachableDefinition(OldConcept) &&
9298 IsRedefinitionInModule(NewDecl, OldConcept)) {
9299 Diag(NewDecl->getLocation(), diag::err_redefinition)
9300 << NewDecl->getDeclName();
9301 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9302 AddToScope = false;
9303 return;
9304 }
9305 if (!Previous.isSingleResult()) {
9306 // FIXME: we should produce an error in case of ambig and failed lookups.
9307 // Other decls (e.g. namespaces) also have this shortcoming.
9308 return;
9309 }
9310 // We unwrap canonical decl late to check for module visibility.
9311 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9312}
9313
9315 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9316 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9317 Diag(Loc, diag::err_recursive_concept) << CE;
9318 Diag(CE->getLocation(), diag::note_declared_at);
9319 return true;
9320 }
9321 // Concept template parameters don't have a definition and can't
9322 // be defined recursively.
9323 return false;
9324}
9325
9326/// \brief Strips various properties off an implicit instantiation
9327/// that has just been explicitly specialized.
9328static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9329 if (MinGW || (isa<FunctionDecl>(D) &&
9330 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9331 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9332
9333 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9334 FD->setInlineSpecified(false);
9335}
9336
9337/// Create an ExplicitInstantiationDecl to record source-location info for an
9338/// explicit template instantiation statement, and add it to \p CurContext.
9339///
9340/// For class templates / nested classes, the caller should build a
9341/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9342/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9343///
9344/// For function / variable templates, the caller should pass TypeAsWritten for
9345/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9347 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9348 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9349 NestedNameSpecifierLoc QualifierLoc,
9350 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9351 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9353 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9354 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9355 Context.addExplicitInstantiationDecl(Spec, EID);
9356 CurContext->addDecl(EID);
9357}
9358
9359/// Compute the diagnostic location for an explicit instantiation
9360// declaration or definition.
9361static SourceLocation
9363 SourceLocation PointOfInstantiation) {
9364 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9365 if (EID->getTemplateSpecializationKind() ==
9367 return EID->getTemplateLoc();
9368
9369 // Explicit instantiations following a specialization have no effect and
9370 // hence no PointOfInstantiation. In that case, walk decl backwards
9371 // until a valid name loc is found.
9372 SourceLocation PrevDiagLoc = PointOfInstantiation;
9373 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9374 Prev = Prev->getPreviousDecl()) {
9375 PrevDiagLoc = Prev->getLocation();
9376 }
9377 assert(PrevDiagLoc.isValid() &&
9378 "Explicit instantiation without point of instantiation?");
9379 return PrevDiagLoc;
9380}
9381
9382bool
9385 NamedDecl *PrevDecl,
9387 SourceLocation PrevPointOfInstantiation,
9388 bool &HasNoEffect) {
9389 HasNoEffect = false;
9390
9391 switch (NewTSK) {
9392 case TSK_Undeclared:
9394 assert(
9395 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9396 "previous declaration must be implicit!");
9397 return false;
9398
9400 switch (PrevTSK) {
9401 case TSK_Undeclared:
9403 // Okay, we're just specializing something that is either already
9404 // explicitly specialized or has merely been mentioned without any
9405 // instantiation.
9406 return false;
9407
9409 if (PrevPointOfInstantiation.isInvalid()) {
9410 // The declaration itself has not actually been instantiated, so it is
9411 // still okay to specialize it.
9413 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9414 return false;
9415 }
9416 // Fall through
9417 [[fallthrough]];
9418
9421 assert((PrevTSK == TSK_ImplicitInstantiation ||
9422 PrevPointOfInstantiation.isValid()) &&
9423 "Explicit instantiation without point of instantiation?");
9424
9425 // C++ [temp.expl.spec]p6:
9426 // If a template, a member template or the member of a class template
9427 // is explicitly specialized then that specialization shall be declared
9428 // before the first use of that specialization that would cause an
9429 // implicit instantiation to take place, in every translation unit in
9430 // which such a use occurs; no diagnostic is required.
9431 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9432 // Is there any previous explicit specialization declaration?
9434 return false;
9435 }
9436
9437 Diag(NewLoc, diag::err_specialization_after_instantiation)
9438 << PrevDecl;
9439 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9440 << (PrevTSK != TSK_ImplicitInstantiation);
9441
9442 return true;
9443 }
9444 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9445
9447 switch (PrevTSK) {
9449 // This explicit instantiation declaration is redundant (that's okay).
9450 HasNoEffect = true;
9451 return false;
9452
9453 case TSK_Undeclared:
9455 // We're explicitly instantiating something that may have already been
9456 // implicitly instantiated; that's fine.
9457 return false;
9458
9460 // C++0x [temp.explicit]p4:
9461 // For a given set of template parameters, if an explicit instantiation
9462 // of a template appears after a declaration of an explicit
9463 // specialization for that template, the explicit instantiation has no
9464 // effect.
9465 HasNoEffect = true;
9466 return false;
9467
9469 // C++0x [temp.explicit]p10:
9470 // If an entity is the subject of both an explicit instantiation
9471 // declaration and an explicit instantiation definition in the same
9472 // translation unit, the definition shall follow the declaration.
9473 Diag(NewLoc,
9474 diag::err_explicit_instantiation_declaration_after_definition);
9475
9476 // Explicit instantiations following a specialization have no effect and
9477 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9478 // until a valid name loc is found.
9479 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9480 diag::note_explicit_instantiation_definition_here);
9481 HasNoEffect = true;
9482 return false;
9483 }
9484 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9485
9487 switch (PrevTSK) {
9488 case TSK_Undeclared:
9490 // We're explicitly instantiating something that may have already been
9491 // implicitly instantiated; that's fine.
9492 return false;
9493
9495 // C++ DR 259, C++0x [temp.explicit]p4:
9496 // For a given set of template parameters, if an explicit
9497 // instantiation of a template appears after a declaration of
9498 // an explicit specialization for that template, the explicit
9499 // instantiation has no effect.
9500 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9501 << PrevDecl;
9502 Diag(PrevDecl->getLocation(),
9503 diag::note_previous_template_specialization);
9504 HasNoEffect = true;
9505 return false;
9506
9508 // We're explicitly instantiating a definition for something for which we
9509 // were previously asked to suppress instantiations. That's fine.
9510
9511 // C++0x [temp.explicit]p4:
9512 // For a given set of template parameters, if an explicit instantiation
9513 // of a template appears after a declaration of an explicit
9514 // specialization for that template, the explicit instantiation has no
9515 // effect.
9516 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9517 // Is there any previous explicit specialization declaration?
9519 HasNoEffect = true;
9520 break;
9521 }
9522 }
9523
9524 return false;
9525
9527 // C++0x [temp.spec]p5:
9528 // For a given template and a given set of template-arguments,
9529 // - an explicit instantiation definition shall appear at most once
9530 // in a program,
9531
9532 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9533 Diag(NewLoc, (getLangOpts().MSVCCompat)
9534 ? diag::ext_explicit_instantiation_duplicate
9535 : diag::err_explicit_instantiation_duplicate)
9536 << PrevDecl;
9537 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9538 diag::note_previous_explicit_instantiation);
9539 HasNoEffect = true;
9540 return false;
9541 }
9542 }
9543
9544 llvm_unreachable("Missing specialization/instantiation case?");
9545}
9546
9548 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9550 // Remove anything from Previous that isn't a function template in
9551 // the correct context.
9552 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9553 LookupResult::Filter F = Previous.makeFilter();
9554 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9555 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9556 while (F.hasNext()) {
9557 NamedDecl *D = F.next()->getUnderlyingDecl();
9558 if (!isa<FunctionTemplateDecl>(D)) {
9559 F.erase();
9560 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9561 continue;
9562 }
9563
9564 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9566 F.erase();
9567 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9568 continue;
9569 }
9570 }
9571 F.done();
9572
9573 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9574 if (Previous.empty()) {
9575 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9576 << IsFriend;
9577 for (auto &P : DiscardedCandidates)
9578 Diag(P.second->getLocation(),
9579 diag::note_dependent_function_template_spec_discard_reason)
9580 << P.first << IsFriend;
9581 return true;
9582 }
9583
9585 ExplicitTemplateArgs);
9586 return false;
9587}
9588
9590 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9591 LookupResult &Previous, bool QualifiedFriend) {
9592 // The set of function template specializations that could match this
9593 // explicit function template specialization.
9594 UnresolvedSet<8> Candidates;
9595 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9596 /*ForTakingAddress=*/false);
9597
9598 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9599 ConvertedTemplateArgs;
9600
9601 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9602 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9603 I != E; ++I) {
9604 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9605 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9606 // Only consider templates found within the same semantic lookup scope as
9607 // FD.
9608 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9610 continue;
9611
9612 QualType FT = FD->getType();
9613 // C++11 [dcl.constexpr]p8:
9614 // A constexpr specifier for a non-static member function that is not
9615 // a constructor declares that member function to be const.
9616 //
9617 // When matching a constexpr member function template specialization
9618 // against the primary template, we don't yet know whether the
9619 // specialization has an implicit 'const' (because we don't know whether
9620 // it will be a static member function until we know which template it
9621 // specializes). This rule was removed in C++14.
9622 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9623 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9625 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9626 if (OldMD && OldMD->isConst()) {
9627 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9629 EPI.TypeQuals.addConst();
9630 FT = Context.getFunctionType(FPT->getReturnType(),
9631 FPT->getParamTypes(), EPI);
9632 }
9633 }
9634
9636 if (ExplicitTemplateArgs)
9637 Args = *ExplicitTemplateArgs;
9638
9639 // C++ [temp.expl.spec]p11:
9640 // A trailing template-argument can be left unspecified in the
9641 // template-id naming an explicit function template specialization
9642 // provided it can be deduced from the function argument type.
9643 // Perform template argument deduction to determine whether we may be
9644 // specializing this template.
9645 // FIXME: It is somewhat wasteful to build
9646 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9647 FunctionDecl *Specialization = nullptr;
9649 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9650 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9652 // Template argument deduction failed; record why it failed, so
9653 // that we can provide nifty diagnostics.
9654 FailedCandidates.addCandidate().set(
9655 I.getPair(), FunTmpl->getTemplatedDecl(),
9656 MakeDeductionFailureInfo(Context, TDK, Info));
9657 (void)TDK;
9658 continue;
9659 }
9660
9661 // Target attributes are part of the cuda function signature, so
9662 // the deduced template's cuda target must match that of the
9663 // specialization. Given that C++ template deduction does not
9664 // take target attributes into account, we reject candidates
9665 // here that have a different target.
9666 if (LangOpts.CUDA &&
9667 CUDA().IdentifyTarget(Specialization,
9668 /* IgnoreImplicitHDAttr = */ true) !=
9669 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9670 FailedCandidates.addCandidate().set(
9671 I.getPair(), FunTmpl->getTemplatedDecl(),
9674 continue;
9675 }
9676
9677 // Record this candidate.
9678 if (ExplicitTemplateArgs)
9679 ConvertedTemplateArgs[Specialization] = std::move(Args);
9680 Candidates.addDecl(Specialization, I.getAccess());
9681 }
9682 }
9683
9684 // For a qualified friend declaration (with no explicit marker to indicate
9685 // that a template specialization was intended), note all (template and
9686 // non-template) candidates.
9687 if (QualifiedFriend && Candidates.empty()) {
9688 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9689 << FD->getDeclName() << FDLookupContext;
9690 // FIXME: We should form a single candidate list and diagnose all
9691 // candidates at once, to get proper sorting and limiting.
9692 for (auto *OldND : Previous) {
9693 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9694 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9695 }
9696 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9697 return true;
9698 }
9699
9700 // Find the most specialized function template.
9702 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9703 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9704 PDiag(diag::err_function_template_spec_ambiguous)
9705 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9706 PDiag(diag::note_function_template_spec_matched));
9707
9708 if (Result == Candidates.end())
9709 return true;
9710
9711 // Ignore access information; it doesn't figure into redeclaration checking.
9713
9714 if (const auto *PT = Specialization->getPrimaryTemplate();
9715 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9716 auto Message = DSA->getMessage();
9717 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9718 << PT << !Message.empty() << Message;
9719 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9720 }
9721
9722 // C++23 [except.spec]p13:
9723 // An exception specification is considered to be needed when:
9724 // - [...]
9725 // - the exception specification is compared to that of another declaration
9726 // (e.g., an explicit specialization or an overriding virtual function);
9727 // - [...]
9728 //
9729 // The exception specification of a defaulted function is evaluated as
9730 // described above only when needed; similarly, the noexcept-specifier of a
9731 // specialization of a function template or member function of a class
9732 // template is instantiated only when needed.
9733 //
9734 // The standard doesn't specify what the "comparison with another declaration"
9735 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9736 // not state which properties of an explicit specialization must match the
9737 // primary template.
9738 //
9739 // We assume that an explicit specialization must correspond with (per
9740 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9741 // the declaration produced by substitution into the function template.
9742 //
9743 // Since the determination whether two function declarations correspond does
9744 // not consider exception specification, we only need to instantiate it once
9745 // we determine the primary template when comparing types per
9746 // [basic.link]p11.1.
9747 auto *SpecializationFPT =
9748 Specialization->getType()->castAs<FunctionProtoType>();
9749 // If the function has a dependent exception specification, resolve it after
9750 // we have selected the primary template so we can check whether it matches.
9751 if (getLangOpts().CPlusPlus17 &&
9752 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9753 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9754 return true;
9755
9757 = Specialization->getTemplateSpecializationInfo();
9758 assert(SpecInfo && "Function template specialization info missing?");
9759
9760 // Note: do not overwrite location info if previous template
9761 // specialization kind was explicit.
9763 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9764 Specialization->setLocation(FD->getLocation());
9765 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9766 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9767 // function can differ from the template declaration with respect to
9768 // the constexpr specifier.
9769 // FIXME: We need an update record for this AST mutation.
9770 // FIXME: What if there are multiple such prior declarations (for instance,
9771 // from different modules)?
9772 Specialization->setConstexprKind(FD->getConstexprKind());
9773 }
9774
9775 // FIXME: Check if the prior specialization has a point of instantiation.
9776 // If so, we have run afoul of .
9777
9778 // If this is a friend declaration, then we're not really declaring
9779 // an explicit specialization.
9780 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9781
9782 // Check the scope of this explicit specialization.
9783 if (!isFriend &&
9785 Specialization->getPrimaryTemplate(),
9787 false))
9788 return true;
9789
9790 // C++ [temp.expl.spec]p6:
9791 // If a template, a member template or the member of a class template is
9792 // explicitly specialized then that specialization shall be declared
9793 // before the first use of that specialization that would cause an implicit
9794 // instantiation to take place, in every translation unit in which such a
9795 // use occurs; no diagnostic is required.
9796 bool HasNoEffect = false;
9797 if (!isFriend &&
9802 SpecInfo->getPointOfInstantiation(),
9803 HasNoEffect))
9804 return true;
9805
9806 // Mark the prior declaration as an explicit specialization, so that later
9807 // clients know that this is an explicit specialization.
9808 // A dependent friend specialization which has a definition should be treated
9809 // as explicit specialization, despite being invalid.
9810 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9811 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9812 // Since explicit specializations do not inherit '=delete' from their
9813 // primary function template - check if the 'specialization' that was
9814 // implicitly generated (during template argument deduction for partial
9815 // ordering) from the most specialized of all the function templates that
9816 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9817 // first check that it was implicitly generated during template argument
9818 // deduction by making sure it wasn't referenced, and then reset the deleted
9819 // flag to not-deleted, so that we can inherit that information from 'FD'.
9820 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9821 !Specialization->getCanonicalDecl()->isReferenced()) {
9822 // FIXME: This assert will not hold in the presence of modules.
9823 assert(
9824 Specialization->getCanonicalDecl() == Specialization &&
9825 "This must be the only existing declaration of this specialization");
9826 // FIXME: We need an update record for this AST mutation.
9827 Specialization->setDeletedAsWritten(false);
9828 }
9829 // FIXME: We need an update record for this AST mutation.
9832 }
9833
9834 // Turn the given function declaration into a function template
9835 // specialization, with the template arguments from the previous
9836 // specialization.
9837 // Take copies of (semantic and syntactic) template argument lists.
9839 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9840 FD->setFunctionTemplateSpecialization(
9841 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9843 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9844
9845 // A function template specialization inherits the target attributes
9846 // of its template. (We require the attributes explicitly in the
9847 // code to match, but a template may have implicit attributes by
9848 // virtue e.g. of being constexpr, and it passes these implicit
9849 // attributes on to its specializations.)
9850 if (LangOpts.CUDA)
9851 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9852
9853 // The "previous declaration" for this function template specialization is
9854 // the prior function template specialization.
9855 Previous.clear();
9856 Previous.addDecl(Specialization);
9857 return false;
9858}
9859
9860bool
9862 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9863 "Only for non-template members");
9864
9865 // Try to find the member we are instantiating.
9866 NamedDecl *FoundInstantiation = nullptr;
9867 NamedDecl *Instantiation = nullptr;
9868 NamedDecl *InstantiatedFrom = nullptr;
9869 MemberSpecializationInfo *MSInfo = nullptr;
9870
9871 if (Previous.empty()) {
9872 // Nowhere to look anyway.
9873 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9874 UnresolvedSet<8> Candidates;
9875 for (NamedDecl *Candidate : Previous) {
9876 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9877 // Ignore any candidates that aren't member functions.
9878 if (!Method)
9879 continue;
9880
9881 QualType Adjusted = Function->getType();
9882 if (!hasExplicitCallingConv(Adjusted))
9883 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9884 // Ignore any candidates with the wrong type.
9885 // This doesn't handle deduced return types, but both function
9886 // declarations should be undeduced at this point.
9887 // FIXME: The exception specification should probably be ignored when
9888 // comparing the types.
9889 if (!Context.hasSameType(Adjusted, Method->getType()))
9890 continue;
9891
9892 // Ignore any candidates with unsatisfied constraints.
9893 if (ConstraintSatisfaction Satisfaction;
9894 Method->getTrailingRequiresClause() &&
9895 (CheckFunctionConstraints(Method, Satisfaction,
9896 /*UsageLoc=*/Member->getLocation(),
9897 /*ForOverloadResolution=*/true) ||
9898 !Satisfaction.IsSatisfied))
9899 continue;
9900
9901 Candidates.addDecl(Candidate);
9902 }
9903
9904 // If we have no viable candidates left after filtering, we are done.
9905 if (Candidates.empty())
9906 return false;
9907
9908 // Find the function that is more constrained than every other function it
9909 // has been compared to.
9910 UnresolvedSetIterator Best = Candidates.begin();
9911 CXXMethodDecl *BestMethod = nullptr;
9912 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9913 I != E; ++I) {
9914 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9915 if (I == Best ||
9916 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9917 Best = I;
9918 BestMethod = Method;
9919 }
9920 }
9921
9922 FoundInstantiation = *Best;
9923 Instantiation = BestMethod;
9924 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9925 MSInfo = BestMethod->getMemberSpecializationInfo();
9926
9927 // Make sure the best candidate is more constrained than all of the others.
9928 bool Ambiguous = false;
9929 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9930 I != E; ++I) {
9931 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9932 if (I != Best &&
9933 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9934 Ambiguous = true;
9935 break;
9936 }
9937 }
9938
9939 if (Ambiguous) {
9940 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9941 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9942 for (NamedDecl *Candidate : Candidates) {
9943 Candidate = Candidate->getUnderlyingDecl();
9944 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9945 << Candidate;
9946 }
9947 return true;
9948 }
9949 } else if (isa<VarDecl>(Member)) {
9950 VarDecl *PrevVar;
9951 if (Previous.isSingleResult() &&
9952 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9953 if (PrevVar->isStaticDataMember()) {
9954 FoundInstantiation = Previous.getRepresentativeDecl();
9955 Instantiation = PrevVar;
9956 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9957 MSInfo = PrevVar->getMemberSpecializationInfo();
9958 }
9959 } else if (isa<RecordDecl>(Member)) {
9960 CXXRecordDecl *PrevRecord;
9961 if (Previous.isSingleResult() &&
9962 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9963 FoundInstantiation = Previous.getRepresentativeDecl();
9964 Instantiation = PrevRecord;
9965 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9966 MSInfo = PrevRecord->getMemberSpecializationInfo();
9967 }
9968 } else if (isa<EnumDecl>(Member)) {
9969 EnumDecl *PrevEnum;
9970 if (Previous.isSingleResult() &&
9971 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9972 FoundInstantiation = Previous.getRepresentativeDecl();
9973 Instantiation = PrevEnum;
9974 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9975 MSInfo = PrevEnum->getMemberSpecializationInfo();
9976 }
9977 }
9978
9979 if (!Instantiation) {
9980 // There is no previous declaration that matches. Since member
9981 // specializations are always out-of-line, the caller will complain about
9982 // this mismatch later.
9983 return false;
9984 }
9985
9986 // A member specialization in a friend declaration isn't really declaring
9987 // an explicit specialization, just identifying a specific (possibly implicit)
9988 // specialization. Don't change the template specialization kind.
9989 //
9990 // FIXME: Is this really valid? Other compilers reject.
9991 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9992 // Preserve instantiation information.
9993 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9994 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9995 cast<CXXMethodDecl>(InstantiatedFrom),
9997 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9998 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9999 cast<CXXRecordDecl>(InstantiatedFrom),
10001 }
10002
10003 Previous.clear();
10004 Previous.addDecl(FoundInstantiation);
10005 return false;
10006 }
10007
10008 // Make sure that this is a specialization of a member.
10009 if (!InstantiatedFrom) {
10010 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10011 << Member;
10012 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10013 return true;
10014 }
10015
10016 // C++ [temp.expl.spec]p6:
10017 // If a template, a member template or the member of a class template is
10018 // explicitly specialized then that specialization shall be declared
10019 // before the first use of that specialization that would cause an implicit
10020 // instantiation to take place, in every translation unit in which such a
10021 // use occurs; no diagnostic is required.
10022 assert(MSInfo && "Member specialization info missing?");
10023
10024 bool HasNoEffect = false;
10027 Instantiation,
10029 MSInfo->getPointOfInstantiation(),
10030 HasNoEffect))
10031 return true;
10032
10033 // Check the scope of this explicit specialization.
10035 InstantiatedFrom,
10036 Instantiation, Member->getLocation(),
10037 false))
10038 return true;
10039
10040 // Note that this member specialization is an "instantiation of" the
10041 // corresponding member of the original template.
10042 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10043 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10044 if (InstantiationFunction->getTemplateSpecializationKind() ==
10046 // Explicit specializations of member functions of class templates do not
10047 // inherit '=delete' from the member function they are specializing.
10048 if (InstantiationFunction->isDeleted()) {
10049 // FIXME: This assert will not hold in the presence of modules.
10050 assert(InstantiationFunction->getCanonicalDecl() ==
10051 InstantiationFunction);
10052 // FIXME: We need an update record for this AST mutation.
10053 InstantiationFunction->setDeletedAsWritten(false);
10054 }
10055 }
10056
10057 MemberFunction->setInstantiationOfMemberFunction(
10059 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10060 MemberVar->setInstantiationOfStaticDataMember(
10061 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10062 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10063 MemberClass->setInstantiationOfMemberClass(
10065 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10066 MemberEnum->setInstantiationOfMemberEnum(
10067 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10068 } else {
10069 llvm_unreachable("unknown member specialization kind");
10070 }
10071
10072 // Save the caller the trouble of having to figure out which declaration
10073 // this specialization matches.
10074 Previous.clear();
10075 Previous.addDecl(FoundInstantiation);
10076 return false;
10077}
10078
10079/// Complete the explicit specialization of a member of a class template by
10080/// updating the instantiated member to be marked as an explicit specialization.
10081///
10082/// \param OrigD The member declaration instantiated from the template.
10083/// \param Loc The location of the explicit specialization of the member.
10084template<typename DeclT>
10085static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10086 SourceLocation Loc) {
10087 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10088 return;
10089
10090 // FIXME: Inform AST mutation listeners of this AST mutation.
10091 // FIXME: If there are multiple in-class declarations of the member (from
10092 // multiple modules, or a declaration and later definition of a member type),
10093 // should we update all of them?
10094 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10095 OrigD->setLocation(Loc);
10096}
10097
10100 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10101 if (Instantiation == Member)
10102 return;
10103
10104 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10105 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10106 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10107 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10108 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10109 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10110 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10111 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10112 else
10113 llvm_unreachable("unknown member specialization kind");
10114}
10115
10116/// Check the scope of an explicit instantiation.
10117///
10118/// \returns true if a serious error occurs, false otherwise.
10120 SourceLocation InstLoc,
10121 bool WasQualifiedName) {
10123 DeclContext *CurContext = S.CurContext->getRedeclContext();
10124
10125 if (CurContext->isRecord()) {
10126 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10127 << D;
10128 return true;
10129 }
10130
10131 // C++11 [temp.explicit]p3:
10132 // An explicit instantiation shall appear in an enclosing namespace of its
10133 // template. If the name declared in the explicit instantiation is an
10134 // unqualified name, the explicit instantiation shall appear in the
10135 // namespace where its template is declared or, if that namespace is inline
10136 // (7.3.1), any namespace from its enclosing namespace set.
10137 //
10138 // This is DR275, which we do not retroactively apply to C++98/03.
10139 if (WasQualifiedName) {
10140 if (CurContext->Encloses(OrigContext))
10141 return false;
10142 } else {
10143 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10144 return false;
10145 }
10146
10147 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10148 if (WasQualifiedName)
10149 S.Diag(InstLoc,
10150 S.getLangOpts().CPlusPlus11?
10151 diag::err_explicit_instantiation_out_of_scope :
10152 diag::warn_explicit_instantiation_out_of_scope_0x)
10153 << D << NS;
10154 else
10155 S.Diag(InstLoc,
10156 S.getLangOpts().CPlusPlus11?
10157 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10158 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10159 << D << NS;
10160 } else
10161 S.Diag(InstLoc,
10162 S.getLangOpts().CPlusPlus11?
10163 diag::err_explicit_instantiation_must_be_global :
10164 diag::warn_explicit_instantiation_must_be_global_0x)
10165 << D;
10166 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10167 return false;
10168}
10169
10170/// Common checks for whether an explicit instantiation of \p D is valid.
10172 SourceLocation InstLoc,
10173 bool WasQualifiedName,
10175 // C++ [temp.explicit]p13:
10176 // An explicit instantiation declaration shall not name a specialization of
10177 // a template with internal linkage.
10180 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10181 return true;
10182 }
10183
10184 // C++11 [temp.explicit]p3: [DR 275]
10185 // An explicit instantiation shall appear in an enclosing namespace of its
10186 // template.
10187 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10188 return true;
10189
10190 return false;
10191}
10192
10193/// Determine whether the given scope specifier has a template-id in it.
10195 // C++11 [temp.explicit]p3:
10196 // If the explicit instantiation is for a member function, a member class
10197 // or a static data member of a class template specialization, the name of
10198 // the class template specialization in the qualified-id for the member
10199 // name shall be a simple-template-id.
10200 //
10201 // C++98 has the same restriction, just worded differently.
10202 for (NestedNameSpecifier NNS = SS.getScopeRep();
10204 /**/) {
10205 const Type *T = NNS.getAsType();
10207 return true;
10208 NNS = T->getPrefix();
10209 }
10210 return false;
10211}
10212
10213/// Make a dllexport or dllimport attr on a class template specialization take
10214/// effect.
10217 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10218 assert(A && "dllExportImportClassTemplateSpecialization called "
10219 "on Def without dllexport or dllimport");
10220
10221 // We reject explicit instantiations in class scope, so there should
10222 // never be any delayed exported classes to worry about.
10223 assert(S.DelayedDllExportClasses.empty() &&
10224 "delayed exports present at explicit instantiation");
10226
10227 // Propagate attribute to base class templates.
10228 for (auto &B : Def->bases()) {
10229 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10230 B.getType()->getAsCXXRecordDecl()))
10232 }
10233
10235}
10236
10238 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10239 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10240 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10241 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10242 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10243 // Find the class template we're specializing
10244 TemplateName Name = TemplateD.get();
10245 TemplateDecl *TD = Name.getAsTemplateDecl();
10246 // Check that the specialization uses the same tag kind as the
10247 // original template.
10249 assert(Kind != TagTypeKind::Enum &&
10250 "Invalid enum tag in class template explicit instantiation!");
10251
10252 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10253
10254 if (!ClassTemplate) {
10255 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10256 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10257 Diag(TD->getLocation(), diag::note_previous_use);
10258 return true;
10259 }
10260
10261 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10262 Kind, /*isDefinition*/false, KWLoc,
10263 ClassTemplate->getIdentifier())) {
10264 Diag(KWLoc, diag::err_use_with_wrong_tag)
10265 << ClassTemplate
10267 ClassTemplate->getTemplatedDecl()->getKindName());
10268 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10269 diag::note_previous_use);
10270 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10271 }
10272
10273 // C++0x [temp.explicit]p2:
10274 // There are two forms of explicit instantiation: an explicit instantiation
10275 // definition and an explicit instantiation declaration. An explicit
10276 // instantiation declaration begins with the extern keyword. [...]
10277 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10280
10282 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10283 // Check for dllexport class template instantiation declarations,
10284 // except for MinGW mode.
10285 for (const ParsedAttr &AL : Attr) {
10286 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10287 Diag(ExternLoc,
10288 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10289 Diag(AL.getLoc(), diag::note_attribute);
10290 break;
10291 }
10292 }
10293
10294 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10295 Diag(ExternLoc,
10296 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10297 Diag(A->getLocation(), diag::note_attribute);
10298 }
10299 }
10300
10301 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10302 // instantiation declarations for most purposes.
10303 bool DLLImportExplicitInstantiationDef = false;
10305 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10306 // Check for dllimport class template instantiation definitions.
10307 bool DLLImport =
10308 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10309 for (const ParsedAttr &AL : Attr) {
10310 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10311 DLLImport = true;
10312 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10313 // dllexport trumps dllimport here.
10314 DLLImport = false;
10315 break;
10316 }
10317 }
10318 if (DLLImport) {
10320 DLLImportExplicitInstantiationDef = true;
10321 }
10322 }
10323
10324 // Translate the parser's template argument list in our AST format.
10325 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10326 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10327
10328 // Check that the template argument list is well-formed for this
10329 // template.
10331 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10332 /*DefaultArgs=*/{}, false, CTAI,
10333 /*UpdateArgsWithConversions=*/true,
10334 /*ConstraintsNotSatisfied=*/nullptr))
10335 return true;
10336
10337 // Find the class template specialization declaration that
10338 // corresponds to these arguments.
10339 void *InsertPos = nullptr;
10341 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10342
10343 TemplateSpecializationKind PrevDecl_TSK
10344 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10345
10346 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10347 Context.getTargetInfo().getTriple().isOSCygMing()) {
10348 // Check for dllexport class template instantiation definitions in MinGW
10349 // mode, if a previous declaration of the instantiation was seen.
10350 for (const ParsedAttr &AL : Attr) {
10351 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10352 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10353 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10354 } else {
10355 Diag(AL.getLoc(),
10356 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10357 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10358 }
10359 break;
10360 }
10361 }
10362 }
10363
10364 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10365 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10366 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10367 return AL.getKind() == ParsedAttr::AT_DLLExport;
10368 })) {
10369 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10370 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10371 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10372 }
10373 }
10374
10375 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10376 SS.isSet(), TSK))
10377 return true;
10378
10380
10381 bool HasNoEffect = false;
10382 if (PrevDecl) {
10383 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10384 PrevDecl, PrevDecl_TSK,
10385 PrevDecl->getPointOfInstantiation(),
10386 HasNoEffect))
10387 return PrevDecl;
10388
10389 // Even though HasNoEffect == true means that this explicit instantiation
10390 // has no effect on semantics, we go on to put its syntax in the AST.
10391
10392 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10393 PrevDecl_TSK == TSK_Undeclared) {
10394 // Since the only prior class template specialization with these
10395 // arguments was referenced but not declared, reuse that
10396 // declaration node as our own, updating the source location
10397 // for the template name to reflect our new declaration.
10398 // (Other source locations will be updated later.)
10399 Specialization = PrevDecl;
10400 Specialization->setLocation(TemplateNameLoc);
10401 PrevDecl = nullptr;
10402 }
10403
10404 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10405 DLLImportExplicitInstantiationDef) {
10406 // The new specialization might add a dllimport attribute.
10407 HasNoEffect = false;
10408 }
10409 }
10410
10411 if (!Specialization) {
10412 // Create a new class template specialization declaration node for
10413 // this explicit specialization.
10415 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10416 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10418
10419 // A MSInheritanceAttr attached to the previous declaration must be
10420 // propagated to the new node prior to instantiation.
10421 if (PrevDecl) {
10422 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10423 auto *Clone = A->clone(getASTContext());
10424 Clone->setInherited(true);
10425 Specialization->addAttr(Clone);
10426 Consumer.AssignInheritanceModel(Specialization);
10427 }
10428 }
10429
10430 if (!HasNoEffect && !PrevDecl) {
10431 // Insert the new specialization.
10432 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10433 }
10434 }
10435
10436 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10437
10438 // Set source locations for keywords.
10439 Specialization->setExternKeywordLoc(ExternLoc);
10440 Specialization->setTemplateKeywordLoc(TemplateLoc);
10441 Specialization->setBraceRange(SourceRange());
10442
10443 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10446
10447 // Add the explicit instantiation into its lexical context. However,
10448 // since explicit instantiations are never found by name lookup, we
10449 // just put it into the declaration context directly.
10450 Specialization->setLexicalDeclContext(CurContext);
10451 CurContext->addDecl(Specialization);
10452
10453 // Syntax is now OK, so return if it has no other effect on semantics.
10454 if (HasNoEffect) {
10455 // Set the template specialization kind.
10456 Specialization->setTemplateSpecializationKind(TSK);
10457
10459 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10460 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10461 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10462 Context.getCanonicalTagType(Specialization));
10464 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10465 TemplateNameLoc, TSI, TSK);
10466 return Specialization;
10467 }
10468
10469 // C++ [temp.explicit]p3:
10470 // A definition of a class template or class member template
10471 // shall be in scope at the point of the explicit instantiation of
10472 // the class template or class member template.
10473 //
10474 // This check comes when we actually try to perform the
10475 // instantiation.
10477 = cast_or_null<ClassTemplateSpecializationDecl>(
10478 Specialization->getDefinition());
10479 if (!Def)
10481 /*Complain=*/true,
10482 CTAI.StrictPackMatch);
10483 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10484 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10485 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10486 }
10487
10488 // Instantiate the members of this class template specialization.
10489 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10490 Specialization->getDefinition());
10491 if (Def) {
10493 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10494 // TSK_ExplicitInstantiationDefinition
10495 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10497 DLLImportExplicitInstantiationDef)) {
10498 // FIXME: Need to notify the ASTMutationListener that we did this.
10500
10501 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10502 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10503 // An explicit instantiation definition can add a dll attribute to a
10504 // template with a previous instantiation declaration. MinGW doesn't
10505 // allow this.
10506 auto *A = cast<InheritableAttr>(
10508 A->setInherited(true);
10509 Def->addAttr(A);
10511 }
10512 }
10513
10514 // Fix a TSK_ImplicitInstantiation followed by a
10515 // TSK_ExplicitInstantiationDefinition
10516 bool NewlyDLLExported =
10517 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10518 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10519 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10520 // An explicit instantiation definition can add a dll attribute to a
10521 // template with a previous implicit instantiation. MinGW doesn't allow
10522 // this. We limit clang to only adding dllexport, to avoid potentially
10523 // strange codegen behavior. For example, if we extend this conditional
10524 // to dllimport, and we have a source file calling a method on an
10525 // implicitly instantiated template class instance and then declaring a
10526 // dllimport explicit instantiation definition for the same template
10527 // class, the codegen for the method call will not respect the dllimport,
10528 // while it will with cl. The Def will already have the DLL attribute,
10529 // since the Def and Specialization will be the same in the case of
10530 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10531 // attribute to the Specialization; we just need to make it take effect.
10532 assert(Def == Specialization &&
10533 "Def and Specialization should match for implicit instantiation");
10535 }
10536
10537 // In MinGW mode, export the template instantiation if the declaration
10538 // was marked dllexport.
10539 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10540 Context.getTargetInfo().getTriple().isOSCygMing() &&
10541 PrevDecl->hasAttr<DLLExportAttr>()) {
10543 }
10544
10545 // Set the template specialization kind. Make sure it is set before
10546 // instantiating the members which will trigger ASTConsumer callbacks.
10547 Specialization->setTemplateSpecializationKind(TSK);
10548 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10549 } else {
10550
10551 // Set the template specialization kind.
10552 Specialization->setTemplateSpecializationKind(TSK);
10553 }
10554
10556 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10557 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10558 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10559 Context.getCanonicalTagType(Specialization));
10561 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10562 TemplateNameLoc, TSI, TSK);
10563 return Specialization;
10564}
10565
10568 SourceLocation TemplateLoc, unsigned TagSpec,
10569 SourceLocation KWLoc, CXXScopeSpec &SS,
10570 IdentifierInfo *Name, SourceLocation NameLoc,
10571 const ParsedAttributesView &Attr) {
10572
10573 bool Owned = false;
10574 bool IsDependent = false;
10575 Decl *TagD =
10576 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10577 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10578 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10579 false, TypeResult(), /*IsTypeSpecifier*/ false,
10580 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10581 .get();
10582 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10583
10584 if (!TagD)
10585 return true;
10586
10587 TagDecl *Tag = cast<TagDecl>(TagD);
10588 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10589
10590 if (Tag->isInvalidDecl())
10591 return true;
10592
10594 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10595 if (!Pattern) {
10596 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10597 << Context.getCanonicalTagType(Record);
10598 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10599 return true;
10600 }
10601
10602 // C++0x [temp.explicit]p2:
10603 // If the explicit instantiation is for a class or member class, the
10604 // elaborated-type-specifier in the declaration shall include a
10605 // simple-template-id.
10606 //
10607 // C++98 has the same restriction, just worded differently.
10609 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10610 << Record << SS.getRange();
10611
10612 // C++0x [temp.explicit]p2:
10613 // There are two forms of explicit instantiation: an explicit instantiation
10614 // definition and an explicit instantiation declaration. An explicit
10615 // instantiation declaration begins with the extern keyword. [...]
10619
10620 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10621
10622 // Verify that it is okay to explicitly instantiate here.
10623 CXXRecordDecl *PrevDecl
10624 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10625 if (!PrevDecl && Record->getDefinition())
10626 PrevDecl = Record;
10627 if (PrevDecl) {
10629 bool HasNoEffect = false;
10630 assert(MSInfo && "No member specialization information?");
10631 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10632 PrevDecl,
10634 MSInfo->getPointOfInstantiation(),
10635 HasNoEffect))
10636 return true;
10637 if (HasNoEffect) {
10641 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10642 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10643 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10644 TL.setElaboratedKeywordLoc(KWLoc);
10645 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10646 TL.setNameLoc(NameLoc);
10648 TemplateLoc, NestedNameSpecifierLoc(),
10649 nullptr, NameLoc, TSI, TSK);
10650 return TagD;
10651 }
10652 }
10653
10654 CXXRecordDecl *RecordDef
10655 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10656 if (!RecordDef) {
10657 // C++ [temp.explicit]p3:
10658 // A definition of a member class of a class template shall be in scope
10659 // at the point of an explicit instantiation of the member class.
10660 CXXRecordDecl *Def
10661 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10662 if (!Def) {
10663 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10664 << 0 << Record->getDeclName() << Record->getDeclContext();
10665 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10666 << Pattern;
10667 return true;
10668 } else {
10669 if (InstantiateClass(NameLoc, Record, Def,
10671 TSK))
10672 return true;
10673
10674 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10675 if (!RecordDef)
10676 return true;
10677 }
10678 }
10679
10680 // Instantiate all of the members of the class.
10681 InstantiateClassMembers(NameLoc, RecordDef,
10683
10685 MarkVTableUsed(NameLoc, RecordDef, true);
10686
10689 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10690 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10691 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10692 TL.setElaboratedKeywordLoc(KWLoc);
10693 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10694 TL.setNameLoc(NameLoc);
10696 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10697 NameLoc, TSI, TSK);
10698 return TagD;
10699}
10700
10702 SourceLocation ExternLoc,
10703 SourceLocation TemplateLoc,
10704 Declarator &D) {
10705 // Explicit instantiations always require a name.
10706 // TODO: check if/when DNInfo should replace Name.
10708 DeclarationName Name = NameInfo.getName();
10709 if (!Name) {
10710 if (!D.isInvalidType())
10712 diag::err_explicit_instantiation_requires_name)
10714
10715 return true;
10716 }
10717
10718 // Get the innermost enclosing declaration scope.
10719 S = S->getDeclParent();
10720
10721 // Determine the type of the declaration.
10723 QualType R = T->getType();
10724 if (R.isNull())
10725 return true;
10726
10727 // C++ [dcl.stc]p1:
10728 // A storage-class-specifier shall not be specified in [...] an explicit
10729 // instantiation (14.7.2) directive.
10731 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10732 << Name;
10733 return true;
10734 } else if (D.getDeclSpec().getStorageClassSpec()
10736 // Complain about then remove the storage class specifier.
10737 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10739
10741 }
10742
10743 // C++0x [temp.explicit]p1:
10744 // [...] An explicit instantiation of a function template shall not use the
10745 // inline or constexpr specifiers.
10746 // Presumably, this also applies to member functions of class templates as
10747 // well.
10751 diag::err_explicit_instantiation_inline :
10752 diag::warn_explicit_instantiation_inline_0x)
10754 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10755 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10756 // not already specified.
10758 diag::err_explicit_instantiation_constexpr);
10759
10760 // A deduction guide is not on the list of entities that can be explicitly
10761 // instantiated.
10763 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10764 << /*explicit instantiation*/ 0;
10765 return true;
10766 }
10767
10768 // C++0x [temp.explicit]p2:
10769 // There are two forms of explicit instantiation: an explicit instantiation
10770 // definition and an explicit instantiation declaration. An explicit
10771 // instantiation declaration begins with the extern keyword. [...]
10775
10776 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10778 /*ObjectType=*/QualType());
10779
10780 if (!R->isFunctionType()) {
10781 // C++ [temp.explicit]p1:
10782 // A [...] static data member of a class template can be explicitly
10783 // instantiated from the member definition associated with its class
10784 // template.
10785 // C++1y [temp.explicit]p1:
10786 // A [...] variable [...] template specialization can be explicitly
10787 // instantiated from its template.
10788 if (Previous.isAmbiguous())
10789 return true;
10790
10791 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10792 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10793
10794 if (!PrevTemplate) {
10795 if (!Prev || !Prev->isStaticDataMember()) {
10796 // We expect to see a static data member here.
10797 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10798 << Name;
10799 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10800 P != PEnd; ++P)
10801 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10802 return true;
10803 }
10804
10806 // FIXME: Check for explicit specialization?
10808 diag::err_explicit_instantiation_data_member_not_instantiated)
10809 << Prev;
10810 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10811 // FIXME: Can we provide a note showing where this was declared?
10812 return true;
10813 }
10814 } else {
10815 // Explicitly instantiate a variable template.
10816
10817 // C++1y [dcl.spec.auto]p6:
10818 // ... A program that uses auto or decltype(auto) in a context not
10819 // explicitly allowed in this section is ill-formed.
10820 //
10821 // This includes auto-typed variable template instantiations.
10822 if (R->isUndeducedType()) {
10823 Diag(T->getTypeLoc().getBeginLoc(),
10824 diag::err_auto_not_allowed_var_inst);
10825 return true;
10826 }
10827
10829 // C++1y [temp.explicit]p3:
10830 // If the explicit instantiation is for a variable, the unqualified-id
10831 // in the declaration shall be a template-id.
10833 diag::err_explicit_instantiation_without_template_id)
10834 << PrevTemplate;
10835 Diag(PrevTemplate->getLocation(),
10836 diag::note_explicit_instantiation_here);
10837 return true;
10838 }
10839
10840 // Translate the parser's template argument list into our AST format.
10841 TemplateArgumentListInfo TemplateArgs =
10843
10844 DeclResult Res =
10845 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10846 TemplateArgs, /*SetWrittenArgs=*/true);
10847 if (Res.isInvalid())
10848 return true;
10849
10850 if (!Res.isUsable()) {
10851 // We somehow specified dependent template arguments in an explicit
10852 // instantiation. This should probably only happen during error
10853 // recovery.
10854 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10855 return true;
10856 }
10857
10858 // Ignore access control bits, we don't need them for redeclaration
10859 // checking.
10860 Prev = cast<VarDecl>(Res.get());
10861 }
10862
10863 // C++0x [temp.explicit]p2:
10864 // If the explicit instantiation is for a member function, a member class
10865 // or a static data member of a class template specialization, the name of
10866 // the class template specialization in the qualified-id for the member
10867 // name shall be a simple-template-id.
10868 //
10869 // C++98 has the same restriction, just worded differently.
10870 //
10871 // This does not apply to variable template specializations, where the
10872 // template-id is in the unqualified-id instead.
10873 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10875 diag::ext_explicit_instantiation_without_qualified_id)
10876 << Prev << D.getCXXScopeSpec().getRange();
10877
10878 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10879
10880 // Verify that it is okay to explicitly instantiate here.
10883 bool HasNoEffect = false;
10885 PrevTSK, POI, HasNoEffect))
10886 return true;
10887
10888 if (!HasNoEffect) {
10889 // Instantiate static data member or variable template.
10891 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10892 VTSD->setExternKeywordLoc(ExternLoc);
10893 VTSD->setTemplateKeywordLoc(TemplateLoc);
10894 }
10895
10896 // Merge attributes.
10898 if (PrevTemplate)
10899 ProcessAPINotes(Prev);
10900
10903 }
10904
10905 // Check the new variable specialization against the parsed input.
10906 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10907 Diag(T->getTypeLoc().getBeginLoc(),
10908 diag::err_invalid_var_template_spec_type)
10909 << 0 << PrevTemplate << R << Prev->getType();
10910 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10911 << 2 << PrevTemplate->getDeclName();
10912 return true;
10913 }
10914
10915 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10916 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev))
10917 ArgsAsWritten = VTSD->getTemplateArgsAsWritten();
10919 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10920 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10921 D.getIdentifierLoc(), T, TSK);
10922 return (Decl *)nullptr;
10923 }
10924
10925 // If the declarator is a template-id, translate the parser's template
10926 // argument list into our AST format.
10927 bool HasExplicitTemplateArgs = false;
10928 TemplateArgumentListInfo TemplateArgs;
10930 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10931 HasExplicitTemplateArgs = true;
10932 }
10933
10934 // C++ [temp.explicit]p1:
10935 // A [...] function [...] can be explicitly instantiated from its template.
10936 // A member function [...] of a class template can be explicitly
10937 // instantiated from the member definition associated with its class
10938 // template.
10939 UnresolvedSet<8> TemplateMatches;
10940 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10942 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10943 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10944 P != PEnd; ++P) {
10945 NamedDecl *Prev = *P;
10946 if (!HasExplicitTemplateArgs) {
10947 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10948 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10949 /*AdjustExceptionSpec*/true);
10950 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10951 if (Method->getPrimaryTemplate()) {
10952 TemplateMatches.addDecl(Method, P.getAccess());
10953 } else {
10954 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10955 C.FoundDecl = P.getPair();
10956 C.Function = Method;
10957 C.Viable = true;
10959 if (Method->getTrailingRequiresClause() &&
10961 /*ForOverloadResolution=*/true) ||
10962 !S.IsSatisfied)) {
10963 C.Viable = false;
10965 }
10966 }
10967 }
10968 }
10969 }
10970
10971 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10972 if (!FunTmpl)
10973 continue;
10974
10975 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10976 FunctionDecl *Specialization = nullptr;
10978 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10979 Specialization, Info);
10981 // Keep track of almost-matches.
10982 FailedTemplateCandidates.addCandidate().set(
10983 P.getPair(), FunTmpl->getTemplatedDecl(),
10984 MakeDeductionFailureInfo(Context, TDK, Info));
10985 (void)TDK;
10986 continue;
10987 }
10988
10989 // Target attributes are part of the cuda function signature, so
10990 // the cuda target of the instantiated function must match that of its
10991 // template. Given that C++ template deduction does not take
10992 // target attributes into account, we reject candidates here that
10993 // have a different target.
10994 if (LangOpts.CUDA &&
10995 CUDA().IdentifyTarget(Specialization,
10996 /* IgnoreImplicitHDAttr = */ true) !=
10997 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10998 FailedTemplateCandidates.addCandidate().set(
10999 P.getPair(), FunTmpl->getTemplatedDecl(),
11002 continue;
11003 }
11004
11005 TemplateMatches.addDecl(Specialization, P.getAccess());
11006 }
11007
11008 FunctionDecl *Specialization = nullptr;
11009 if (!NonTemplateMatches.empty()) {
11010 unsigned Msg = 0;
11011 OverloadCandidateDisplayKind DisplayKind;
11013 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11014 Best)) {
11015 case OR_Success:
11016 case OR_Deleted:
11017 Specialization = cast<FunctionDecl>(Best->Function);
11018 break;
11019 case OR_Ambiguous:
11020 Msg = diag::err_explicit_instantiation_ambiguous;
11021 DisplayKind = OCD_AmbiguousCandidates;
11022 break;
11024 Msg = diag::err_explicit_instantiation_no_candidate;
11025 DisplayKind = OCD_AllCandidates;
11026 break;
11027 }
11028 if (Msg) {
11029 PartialDiagnostic Diag = PDiag(Msg) << Name;
11030 NonTemplateMatches.NoteCandidates(
11031 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11032 {});
11033 return true;
11034 }
11035 }
11036
11037 if (!Specialization) {
11038 // Find the most specialized function template specialization.
11040 TemplateMatches.begin(), TemplateMatches.end(),
11041 FailedTemplateCandidates, D.getIdentifierLoc(),
11042 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11043 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11044 PDiag(diag::note_explicit_instantiation_candidate));
11045
11046 if (Result == TemplateMatches.end())
11047 return true;
11048
11049 // Ignore access control bits, we don't need them for redeclaration checking.
11051 }
11052
11053 // C++11 [except.spec]p4
11054 // In an explicit instantiation an exception-specification may be specified,
11055 // but is not required.
11056 // If an exception-specification is specified in an explicit instantiation
11057 // directive, it shall be compatible with the exception-specifications of
11058 // other declarations of that function.
11059 if (auto *FPT = R->getAs<FunctionProtoType>())
11060 if (FPT->hasExceptionSpec()) {
11061 unsigned DiagID =
11062 diag::err_mismatched_exception_spec_explicit_instantiation;
11063 if (getLangOpts().MicrosoftExt)
11064 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11066 PDiag(DiagID) << Specialization->getType(),
11067 PDiag(diag::note_explicit_instantiation_here),
11068 Specialization->getType()->getAs<FunctionProtoType>(),
11069 Specialization->getLocation(), FPT, D.getBeginLoc());
11070 // In Microsoft mode, mismatching exception specifications just cause a
11071 // warning.
11072 if (!getLangOpts().MicrosoftExt && Result)
11073 return true;
11074 }
11075
11076 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11078 diag::err_explicit_instantiation_member_function_not_instantiated)
11080 << (Specialization->getTemplateSpecializationKind() ==
11082 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11083 return true;
11084 }
11085
11086 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11087 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11088 PrevDecl = Specialization;
11089
11090 if (PrevDecl) {
11091 bool HasNoEffect = false;
11093 PrevDecl,
11095 PrevDecl->getPointOfInstantiation(),
11096 HasNoEffect))
11097 return true;
11098
11099 if (HasNoEffect) {
11100 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11101 if (HasExplicitTemplateArgs)
11102 ArgsAsWritten =
11105 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11106 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11107 D.getIdentifierLoc(), T, TSK);
11108 return (Decl *)nullptr;
11109 }
11110 }
11111
11112 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11113 // functions
11114 // valarray<size_t>::valarray(size_t) and
11115 // valarray<size_t>::~valarray()
11116 // that it declared to have internal linkage with the internal_linkage
11117 // attribute. Ignore the explicit instantiation declaration in this case.
11118 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11120 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11121 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11122 RD->isInStdNamespace())
11123 return (Decl*) nullptr;
11124 }
11125
11128
11129 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11130 // instantiation declarations.
11132 Specialization->hasAttr<DLLImportAttr>() &&
11133 Context.getTargetInfo().getCXXABI().isMicrosoft())
11135
11136 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11137 if (Specialization->isDefined()) {
11138 // Let the ASTConsumer know that this function has been explicitly
11139 // instantiated now, and its linkage might have changed.
11140 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11141 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11142 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11143 // be explicitly instantiated.
11144 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11145 RD && RD->isLambda()) {
11146 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11147 << /*instantiation*/ 1;
11148 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11149 return (Decl *)nullptr;
11150 }
11152 }
11153
11154 // C++0x [temp.explicit]p2:
11155 // If the explicit instantiation is for a member function, a member class
11156 // or a static data member of a class template specialization, the name of
11157 // the class template specialization in the qualified-id for the member
11158 // name shall be a simple-template-id.
11159 //
11160 // C++98 has the same restriction, just worded differently.
11161 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11162 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11163 D.getCXXScopeSpec().isSet() &&
11166 diag::ext_explicit_instantiation_without_qualified_id)
11168
11170 *this,
11171 FunTmpl ? (NamedDecl *)FunTmpl
11172 : Specialization->getInstantiatedFromMemberFunction(),
11173 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11174
11175 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11176 if (HasExplicitTemplateArgs)
11177 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11179 TemplateLoc,
11181 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11182 return (Decl *)nullptr;
11183}
11184
11186 const CXXScopeSpec &SS,
11187 const IdentifierInfo *Name,
11188 SourceLocation TagLoc,
11189 SourceLocation NameLoc) {
11190 // This has to hold, because SS is expected to be defined.
11191 assert(Name && "Expected a name in a dependent tag");
11192
11194 if (!NNS)
11195 return true;
11196
11198
11199 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11200 Diag(NameLoc, diag::err_dependent_tag_decl)
11201 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11202 return true;
11203 }
11204
11205 // Create the resulting type.
11207 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11208
11209 // Create type-source location information for this type.
11210 TypeLocBuilder TLB;
11212 TL.setElaboratedKeywordLoc(TagLoc);
11214 TL.setNameLoc(NameLoc);
11216}
11217
11219 const CXXScopeSpec &SS,
11220 const IdentifierInfo &II,
11221 SourceLocation IdLoc,
11222 ImplicitTypenameContext IsImplicitTypename) {
11223 if (SS.isInvalid())
11224 return true;
11225
11226 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11227 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11228 << FixItHint::CreateRemoval(TypenameLoc);
11229
11231 TypeSourceInfo *TSI = nullptr;
11232 QualType T =
11235 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11236 /*DeducedTSTContext=*/true);
11237 if (T.isNull())
11238 return true;
11239 return CreateParsedType(T, TSI);
11240}
11241
11244 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11245 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11246 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11247 ASTTemplateArgsPtr TemplateArgsIn,
11248 SourceLocation RAngleLoc) {
11249 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11250 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11251 ? diag::compat_cxx11_typename_outside_of_template
11252 : diag::compat_pre_cxx11_typename_outside_of_template)
11253 << FixItHint::CreateRemoval(TypenameLoc);
11254
11255 // Strangely, non-type results are not ignored by this lookup, so the
11256 // program is ill-formed if it finds an injected-class-name.
11257 if (TypenameLoc.isValid()) {
11258 auto *LookupRD =
11259 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11260 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11261 Diag(TemplateIILoc,
11262 diag::ext_out_of_line_qualified_id_type_names_constructor)
11263 << TemplateII << 0 /*injected-class-name used as template name*/
11264 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11265 }
11266 }
11267
11268 // Translate the parser's template argument list in our AST format.
11269 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11270 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11271
11275 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11276 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11277 if (T.isNull())
11278 return true;
11279
11280 // Provide source-location information for the template specialization type.
11281 TypeLocBuilder Builder;
11283 = Builder.push<TemplateSpecializationTypeLoc>(T);
11284 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11285 TemplateIILoc, TemplateArgs);
11286 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11287 return CreateParsedType(T, TSI);
11288}
11289
11290/// Determine whether this failed name lookup should be treated as being
11291/// disabled by a usage of std::enable_if.
11293 SourceRange &CondRange, Expr *&Cond) {
11294 // We must be looking for a ::type...
11295 if (!II.isStr("type"))
11296 return false;
11297
11298 // ... within an explicitly-written template specialization...
11300 return false;
11301
11302 // FIXME: Look through sugar.
11303 auto EnableIfTSTLoc =
11305 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11306 return false;
11307 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11308
11309 // ... which names a complete class template declaration...
11310 const TemplateDecl *EnableIfDecl =
11311 EnableIfTST->getTemplateName().getAsTemplateDecl();
11312 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11313 return false;
11314
11315 // ... called "enable_if".
11316 const IdentifierInfo *EnableIfII =
11317 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11318 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11319 return false;
11320
11321 // Assume the first template argument is the condition.
11322 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11323
11324 // Dig out the condition.
11325 Cond = nullptr;
11326 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11328 return true;
11329
11330 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11331
11332 // Ignore Boolean literals; they add no value.
11333 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11334 Cond = nullptr;
11335
11336 return true;
11337}
11338
11341 SourceLocation KeywordLoc,
11342 NestedNameSpecifierLoc QualifierLoc,
11343 const IdentifierInfo &II,
11344 SourceLocation IILoc,
11345 TypeSourceInfo **TSI,
11346 bool DeducedTSTContext) {
11347 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11348 DeducedTSTContext);
11349 if (T.isNull())
11350 return QualType();
11351
11352 TypeLocBuilder TLB;
11353 if (isa<DependentNameType>(T)) {
11354 auto TL = TLB.push<DependentNameTypeLoc>(T);
11355 TL.setElaboratedKeywordLoc(KeywordLoc);
11356 TL.setQualifierLoc(QualifierLoc);
11357 TL.setNameLoc(IILoc);
11360 TL.setElaboratedKeywordLoc(KeywordLoc);
11361 TL.setQualifierLoc(QualifierLoc);
11362 TL.setNameLoc(IILoc);
11363 } else if (isa<TemplateTypeParmType>(T)) {
11364 // FIXME: There might be a 'typename' keyword here, but we just drop it
11365 // as it can't be represented.
11366 assert(!QualifierLoc);
11367 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11368 } else if (isa<TagType>(T)) {
11369 auto TL = TLB.push<TagTypeLoc>(T);
11370 TL.setElaboratedKeywordLoc(KeywordLoc);
11371 TL.setQualifierLoc(QualifierLoc);
11372 TL.setNameLoc(IILoc);
11373 } else if (isa<TypedefType>(T)) {
11374 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11375 } else {
11376 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11377 }
11378 *TSI = TLB.getTypeSourceInfo(Context, T);
11379 return T;
11380}
11381
11382/// Build the type that describes a C++ typename specifier,
11383/// e.g., "typename T::type".
11386 SourceLocation KeywordLoc,
11387 NestedNameSpecifierLoc QualifierLoc,
11388 const IdentifierInfo &II,
11389 SourceLocation IILoc, bool DeducedTSTContext) {
11390 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11391
11392 CXXScopeSpec SS;
11393 SS.Adopt(QualifierLoc);
11394
11395 DeclContext *Ctx = nullptr;
11396 if (QualifierLoc) {
11397 Ctx = computeDeclContext(SS);
11398 if (!Ctx) {
11399 // If the nested-name-specifier is dependent and couldn't be
11400 // resolved to a type, build a typename type.
11401 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11402 return Context.getDependentNameType(Keyword,
11403 QualifierLoc.getNestedNameSpecifier(),
11404 &II);
11405 }
11406
11407 // If the nested-name-specifier refers to the current instantiation,
11408 // the "typename" keyword itself is superfluous. In C++03, the
11409 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11410 // allows such extraneous "typename" keywords, and we retroactively
11411 // apply this DR to C++03 code with only a warning. In any case we continue.
11412
11413 if (RequireCompleteDeclContext(SS, Ctx))
11414 return QualType();
11415 }
11416
11417 DeclarationName Name(&II);
11418 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11419 if (Ctx)
11420 LookupQualifiedName(Result, Ctx, SS);
11421 else
11422 LookupName(Result, CurScope);
11423 unsigned DiagID = 0;
11424 Decl *Referenced = nullptr;
11425 switch (Result.getResultKind()) {
11427 // If we're looking up 'type' within a template named 'enable_if', produce
11428 // a more specific diagnostic.
11429 SourceRange CondRange;
11430 Expr *Cond = nullptr;
11431 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11432 // If we have a condition, narrow it down to the specific failed
11433 // condition.
11434 if (Cond) {
11435 Expr *FailedCond;
11436 std::string FailedDescription;
11437 std::tie(FailedCond, FailedDescription) =
11439
11440 Diag(FailedCond->getExprLoc(),
11441 diag::err_typename_nested_not_found_requirement)
11442 << FailedDescription
11443 << FailedCond->getSourceRange();
11444 return QualType();
11445 }
11446
11447 Diag(CondRange.getBegin(),
11448 diag::err_typename_nested_not_found_enable_if)
11449 << Ctx << CondRange;
11450 return QualType();
11451 }
11452
11453 DiagID = Ctx ? diag::err_typename_nested_not_found
11454 : diag::err_unknown_typename;
11455 break;
11456 }
11457
11459 // We found a using declaration that is a value. Most likely, the using
11460 // declaration itself is meant to have the 'typename' keyword.
11461 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11462 IILoc);
11463 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11464 << Name << Ctx << FullRange;
11465 if (UnresolvedUsingValueDecl *Using
11466 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11467 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11468 Diag(Loc, diag::note_using_value_decl_missing_typename)
11469 << FixItHint::CreateInsertion(Loc, "typename ");
11470 }
11471 }
11472 // Fall through to create a dependent typename type, from which we can
11473 // recover better.
11474 [[fallthrough]];
11475
11477 // Okay, it's a member of an unknown instantiation.
11478 return Context.getDependentNameType(Keyword,
11479 QualifierLoc.getNestedNameSpecifier(),
11480 &II);
11481
11483 // FXIME: Missing support for UsingShadowDecl on this path?
11484 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11485 // C++ [class.qual]p2:
11486 // In a lookup in which function names are not ignored and the
11487 // nested-name-specifier nominates a class C, if the name specified
11488 // after the nested-name-specifier, when looked up in C, is the
11489 // injected-class-name of C [...] then the name is instead considered
11490 // to name the constructor of class C.
11491 //
11492 // Unlike in an elaborated-type-specifier, function names are not ignored
11493 // in typename-specifier lookup. However, they are ignored in all the
11494 // contexts where we form a typename type with no keyword (that is, in
11495 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11496 //
11497 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11498 // ignore functions, but that appears to be an oversight.
11503 Type, IILoc);
11504 // FIXME: This appears to be the only case where a template type parameter
11505 // can have an elaborated keyword. We should preserve it somehow.
11508 assert(!QualifierLoc);
11510 }
11511 return Context.getTypeDeclType(
11512 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11513 }
11514
11515 // C++ [dcl.type.simple]p2:
11516 // A type-specifier of the form
11517 // typename[opt] nested-name-specifier[opt] template-name
11518 // is a placeholder for a deduced class type [...].
11519 if (getLangOpts().CPlusPlus17) {
11520 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11521 if (!DeducedTSTContext) {
11522 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11523 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11524 Diag(IILoc, diag::err_dependent_deduced_tst)
11526 << QualType(Qualifier.getAsType(), 0);
11527 else
11528 Diag(IILoc, diag::err_deduced_tst)
11531 return QualType();
11532 }
11533 TemplateName Name = Context.getQualifiedTemplateName(
11534 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11535 TemplateName(TD));
11536 return Context.getDeducedTemplateSpecializationType(
11537 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11538 Name);
11539 }
11540 }
11541
11542 DiagID = Ctx ? diag::err_typename_nested_not_type
11543 : diag::err_typename_not_type;
11544 Referenced = Result.getFoundDecl();
11545 break;
11546
11548 DiagID = Ctx ? diag::err_typename_nested_not_type
11549 : diag::err_typename_not_type;
11550 Referenced = *Result.begin();
11551 break;
11552
11554 return QualType();
11555 }
11556
11557 // If we get here, it's because name lookup did not find a
11558 // type. Emit an appropriate diagnostic and return an error.
11559 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11560 IILoc);
11561 if (Ctx)
11562 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11563 else
11564 Diag(IILoc, DiagID) << FullRange << Name;
11565 if (Referenced)
11566 Diag(Referenced->getLocation(),
11567 Ctx ? diag::note_typename_member_refers_here
11568 : diag::note_typename_refers_here)
11569 << Name;
11570 return QualType();
11571}
11572
11573namespace {
11574 // See Sema::RebuildTypeInCurrentInstantiation
11575 class CurrentInstantiationRebuilder
11576 : public TreeTransform<CurrentInstantiationRebuilder> {
11577 SourceLocation Loc;
11578 DeclarationName Entity;
11579
11580 public:
11582
11583 CurrentInstantiationRebuilder(Sema &SemaRef,
11584 SourceLocation Loc,
11585 DeclarationName Entity)
11586 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11587 Loc(Loc), Entity(Entity) { }
11588
11589 /// Determine whether the given type \p T has already been
11590 /// transformed.
11591 ///
11592 /// For the purposes of type reconstruction, a type has already been
11593 /// transformed if it is NULL or if it is not dependent.
11594 bool AlreadyTransformed(QualType T) {
11595 return T.isNull() || !T->isInstantiationDependentType();
11596 }
11597
11598 /// Returns the location of the entity whose type is being
11599 /// rebuilt.
11600 SourceLocation getBaseLocation() { return Loc; }
11601
11602 /// Returns the name of the entity whose type is being rebuilt.
11603 DeclarationName getBaseEntity() { return Entity; }
11604
11605 /// Sets the "base" location and entity when that
11606 /// information is known based on another transformation.
11607 void setBase(SourceLocation Loc, DeclarationName Entity) {
11608 this->Loc = Loc;
11609 this->Entity = Entity;
11610 }
11611
11612 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11613 // Lambdas never need to be transformed.
11614 return E;
11615 }
11616 };
11617} // end anonymous namespace
11618
11620 SourceLocation Loc,
11621 DeclarationName Name) {
11622 if (!T || !T->getType()->isInstantiationDependentType())
11623 return T;
11624
11625 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11626 return Rebuilder.TransformType(T);
11627}
11628
11630 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11631 DeclarationName());
11632 return Rebuilder.TransformExpr(E);
11633}
11634
11636 if (SS.isInvalid())
11637 return true;
11638
11640 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11641 DeclarationName());
11643 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11644 if (!Rebuilt)
11645 return true;
11646
11647 SS.Adopt(Rebuilt);
11648 return false;
11649}
11650
11652 TemplateParameterList *Params) {
11653 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11654 Decl *Param = Params->getParam(I);
11655
11656 // There is nothing to rebuild in a type parameter.
11657 if (isa<TemplateTypeParmDecl>(Param))
11658 continue;
11659
11660 // Rebuild the template parameter list of a template template parameter.
11662 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11664 TTP->getTemplateParameters()))
11665 return true;
11666
11667 continue;
11668 }
11669
11670 // Rebuild the type of a non-type template parameter.
11672 TypeSourceInfo *NewTSI
11674 NTTP->getLocation(),
11675 NTTP->getDeclName());
11676 if (!NewTSI)
11677 return true;
11678
11679 if (NewTSI->getType()->isUndeducedType()) {
11680 // C++17 [temp.dep.expr]p3:
11681 // An id-expression is type-dependent if it contains
11682 // - an identifier associated by name lookup with a non-type
11683 // template-parameter declared with a type that contains a
11684 // placeholder type (7.1.7.4),
11685 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11686 }
11687
11688 if (NewTSI != NTTP->getTypeSourceInfo()) {
11689 NTTP->setTypeSourceInfo(NewTSI);
11690 NTTP->setType(NewTSI->getType());
11691 }
11692 }
11693
11694 return false;
11695}
11696
11697std::string
11699 const TemplateArgumentList &Args) {
11700 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11701}
11702
11703std::string
11705 const TemplateArgument *Args,
11706 unsigned NumArgs) {
11707 SmallString<128> Str;
11708 llvm::raw_svector_ostream Out(Str);
11709
11710 if (!Params || Params->size() == 0 || NumArgs == 0)
11711 return std::string();
11712
11713 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11714 if (I >= NumArgs)
11715 break;
11716
11717 if (I == 0)
11718 Out << "[with ";
11719 else
11720 Out << ", ";
11721
11722 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11723 Out << Id->getName();
11724 } else {
11725 Out << '$' << I;
11726 }
11727
11728 Out << " = ";
11729 Args[I].print(getPrintingPolicy(), Out,
11731 getPrintingPolicy(), Params, I));
11732 }
11733
11734 Out << ']';
11735 return std::string(Out.str());
11736}
11737
11739 CachedTokens &Toks) {
11740 if (!FD)
11741 return;
11742
11743 auto LPT = std::make_unique<LateParsedTemplate>();
11744
11745 // Take tokens to avoid allocations
11746 LPT->Toks.swap(Toks);
11747 LPT->D = FnD;
11748 LPT->FPO = getCurFPFeatures();
11749 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11750
11751 FD->setLateTemplateParsed(true);
11752}
11753
11755 if (!FD)
11756 return;
11757 FD->setLateTemplateParsed(false);
11758}
11759
11761 DeclContext *DC = CurContext;
11762
11763 while (DC) {
11764 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11765 const FunctionDecl *FD = RD->isLocalClass();
11766 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11767 } else if (DC->isTranslationUnit() || DC->isNamespace())
11768 return false;
11769
11770 DC = DC->getParent();
11771 }
11772 return false;
11773}
11774
11775namespace {
11776/// Walk the path from which a declaration was instantiated, and check
11777/// that every explicit specialization along that path is visible. This enforces
11778/// C++ [temp.expl.spec]/6:
11779///
11780/// If a template, a member template or a member of a class template is
11781/// explicitly specialized then that specialization shall be declared before
11782/// the first use of that specialization that would cause an implicit
11783/// instantiation to take place, in every translation unit in which such a
11784/// use occurs; no diagnostic is required.
11785///
11786/// and also C++ [temp.class.spec]/1:
11787///
11788/// A partial specialization shall be declared before the first use of a
11789/// class template specialization that would make use of the partial
11790/// specialization as the result of an implicit or explicit instantiation
11791/// in every translation unit in which such a use occurs; no diagnostic is
11792/// required.
11793class ExplicitSpecializationVisibilityChecker {
11794 Sema &S;
11795 SourceLocation Loc;
11798
11799public:
11800 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11802 : S(S), Loc(Loc), Kind(Kind) {}
11803
11804 void check(NamedDecl *ND) {
11805 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11806 return checkImpl(FD);
11807 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11808 return checkImpl(RD);
11809 if (auto *VD = dyn_cast<VarDecl>(ND))
11810 return checkImpl(VD);
11811 if (auto *ED = dyn_cast<EnumDecl>(ND))
11812 return checkImpl(ED);
11813 }
11814
11815private:
11816 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11817 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11818 : Sema::MissingImportKind::ExplicitSpecialization;
11819 const bool Recover = true;
11820
11821 // If we got a custom set of modules (because only a subset of the
11822 // declarations are interesting), use them, otherwise let
11823 // diagnoseMissingImport intelligently pick some.
11824 if (Modules.empty())
11825 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11826 else
11827 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11828 }
11829
11830 bool CheckMemberSpecialization(const NamedDecl *D) {
11831 return Kind == Sema::AcceptableKind::Visible
11834 }
11835
11836 bool CheckExplicitSpecialization(const NamedDecl *D) {
11837 return Kind == Sema::AcceptableKind::Visible
11840 }
11841
11842 bool CheckDeclaration(const NamedDecl *D) {
11843 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11845 }
11846
11847 // Check a specific declaration. There are three problematic cases:
11848 //
11849 // 1) The declaration is an explicit specialization of a template
11850 // specialization.
11851 // 2) The declaration is an explicit specialization of a member of an
11852 // templated class.
11853 // 3) The declaration is an instantiation of a template, and that template
11854 // is an explicit specialization of a member of a templated class.
11855 //
11856 // We don't need to go any deeper than that, as the instantiation of the
11857 // surrounding class / etc is not triggered by whatever triggered this
11858 // instantiation, and thus should be checked elsewhere.
11859 template<typename SpecDecl>
11860 void checkImpl(SpecDecl *Spec) {
11861 bool IsHiddenExplicitSpecialization = false;
11862 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11863 // Some invalid friend declarations are written as specializations but are
11864 // instantiated implicitly.
11865 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11866 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11867 if (SpecKind == TSK_ExplicitSpecialization) {
11868 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11869 ? !CheckMemberSpecialization(Spec)
11870 : !CheckExplicitSpecialization(Spec);
11871 } else {
11872 checkInstantiated(Spec);
11873 }
11874
11875 if (IsHiddenExplicitSpecialization)
11876 diagnose(Spec->getMostRecentDecl(), false);
11877 }
11878
11879 void checkInstantiated(FunctionDecl *FD) {
11880 if (auto *TD = FD->getPrimaryTemplate())
11881 checkTemplate(TD);
11882 }
11883
11884 void checkInstantiated(CXXRecordDecl *RD) {
11885 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11886 if (!SD)
11887 return;
11888
11889 auto From = SD->getSpecializedTemplateOrPartial();
11890 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11891 checkTemplate(TD);
11892 else if (auto *TD =
11893 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11894 if (!CheckDeclaration(TD))
11895 diagnose(TD, true);
11896 checkTemplate(TD);
11897 }
11898 }
11899
11900 void checkInstantiated(VarDecl *RD) {
11901 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11902 if (!SD)
11903 return;
11904
11905 auto From = SD->getSpecializedTemplateOrPartial();
11906 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11907 checkTemplate(TD);
11908 else if (auto *TD =
11909 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11910 if (!CheckDeclaration(TD))
11911 diagnose(TD, true);
11912 checkTemplate(TD);
11913 }
11914 }
11915
11916 void checkInstantiated(EnumDecl *FD) {}
11917
11918 template<typename TemplDecl>
11919 void checkTemplate(TemplDecl *TD) {
11920 if (TD->isMemberSpecialization()) {
11921 if (!CheckMemberSpecialization(TD))
11922 diagnose(TD->getMostRecentDecl(), false);
11923 }
11924 }
11925};
11926} // end anonymous namespace
11927
11929 if (!getLangOpts().Modules)
11930 return;
11931
11932 ExplicitSpecializationVisibilityChecker(*this, Loc,
11934 .check(Spec);
11935}
11936
11938 NamedDecl *Spec) {
11939 if (!getLangOpts().CPlusPlusModules)
11940 return checkSpecializationVisibility(Loc, Spec);
11941
11942 ExplicitSpecializationVisibilityChecker(*this, Loc,
11944 .check(Spec);
11945}
11946
11949 return N->getLocation();
11950 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11952 return FD->getLocation();
11955 return N->getLocation();
11956 }
11957 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11958 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11959 continue;
11960 return CSC.PointOfInstantiation;
11961 }
11962 return N->getLocation();
11963}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
APSInt & getInt()
Definition APValue.h:508
APSInt & getComplexIntImag()
Definition APValue.h:546
ValueKind getKind() const
Definition APValue.h:479
APFixedPoint & getFixedPoint()
Definition APValue.h:530
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isMemberPointer() const
Definition APValue.h:496
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isNullPointer() const
Definition APValue.cpp:1051
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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:3947
QualType getElementType() const
Definition TypeBase.h:3789
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8235
Attr - This represents one attribute.
Definition Attr.h:46
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2393
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2411
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2461
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2454
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2429
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2435
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2441
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8288
Pointer to a block type.
Definition TypeBase.h:3597
QualType getPointeeType() const
Definition TypeBase.h:3609
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:3219
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:2109
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:739
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3870
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1557
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2030
base_class_range bases()
Definition DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2056
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2037
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2071
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:75
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:182
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:208
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:187
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:81
SourceLocation getBeginLoc() const
Definition DeclSpec.h:85
bool isSet() const
Deprecated.
Definition DeclSpec.h:200
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:96
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:185
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:180
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3330
QualType getElementType() const
Definition TypeBase.h:3340
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3815
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:355
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4442
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isFileContext() const
Definition DeclBase.h:2193
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:2211
bool isTranslationUnit() const
Definition DeclBase.h:2198
bool isRecord() const
Definition DeclBase.h:2202
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1374
ValueDecl * getDecl()
Definition Expr.h:1341
Captures information about "declaration specifiers".
Definition DeclSpec.h:219
bool isVirtualSpecified() const
Definition DeclSpec.h:654
void ClearStorageClassSpecs()
Definition DeclSpec.h:499
bool isNoreturnSpecified() const
Definition DeclSpec.h:667
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:494
SCS getStorageClassSpec() const
Definition DeclSpec.h:485
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:559
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:558
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:668
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:660
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:486
ParsedAttributes & getAttributes()
Definition DeclSpec.h:879
bool isInlineSpecified() const
Definition DeclSpec.h:643
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:495
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:655
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:842
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:646
bool hasExplicitSpecifier() const
Definition DeclSpec.h:657
bool hasConstexprSpecifier() const
Definition DeclSpec.h:843
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:1074
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1239
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
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:1230
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:850
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:820
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:1193
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2806
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:931
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1942
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2089
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2378
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2768
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2125
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2108
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2104
bool hasEllipsis() const
Definition DeclSpec.h:2767
bool isInvalidType() const
Definition DeclSpec.h:2756
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2124
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2096
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2372
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4116
QualType getPointeeType() const
Definition TypeBase.h:4128
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3510
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:549
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4066
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4156
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4528
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4282
QualType getElementType() const
Definition TypeBase.h:4294
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateName(TemplateName Template)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4029
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4301
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5149
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3100
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3095
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:830
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3075
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:4073
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:282
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4322
Represents a member of a struct/union/class.
Definition Decl.h:3178
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1002
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1081
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Represents a function declaration or definition.
Definition Decl.h:2018
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2494
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4200
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4509
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4308
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4167
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3742
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4139
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:4373
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2380
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4412
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3164
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4160
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4940
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5362
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5651
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5647
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5802
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:4898
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3964
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5302
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:980
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3672
Represents a linkage specification.
Definition DeclCXX.h:3020
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
A global _GUID constant.
Definition DeclCXX.h:4403
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4406
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3708
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3740
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5583
QualType getPointeeType() const
Definition TypeBase.h:3726
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:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:212
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:266
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1681
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:714
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7998
Represents a pointer to an Objective C object.
Definition TypeBase.h:8054
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
bool isVarDeclReference() const
Definition ExprCXX.h:3302
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3318
bool isConceptReference() const
Definition ExprCXX.h:3291
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3337
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4363
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8254
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3383
QualType getPointeeType() const
Definition TypeBase.h:3393
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8525
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3678
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1167
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8436
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:8621
QualType getCanonicalType() const
Definition TypeBase.h:8488
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8530
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3671
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1343
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3690
Represents a struct/union/class.
Definition Decl.h:4343
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4527
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5348
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3628
QualType getPointeeType() const
Definition TypeBase.h:3646
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13758
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8532
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
Whether and why a template name is required in this lookup.
Definition Sema.h:11492
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11500
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12551
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12585
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7801
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13697
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13148
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2628
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9411
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9418
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:9725
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void NoteAllFoundTemplates(TemplateName Name)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition Sema.h:1473
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4200
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11463
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12061
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12064
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12068
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1308
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:939
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12241
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12259
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12249
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12269
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:11513
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11520
@ None
This is not assumed to be a template name.
Definition Sema.h:11515
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11517
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:11449
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14565
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14553
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14562
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14556
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14580
const LangOptions & getLangOpts() const
Definition Sema.h:932
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1307
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1306
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13796
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:15580
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ASTConsumer & Consumer
Definition Sema.h:1309
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4698
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:6811
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6790
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:14073
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:11490
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11673
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11683
@ TPC_FriendFunctionTemplate
Definition Sema.h:11681
@ TPC_ClassTemplateMember
Definition Sema.h:11679
@ TPC_FunctionTemplate
Definition Sema.h:11678
@ TPC_FriendClassTemplate
Definition Sema.h:11680
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11682
friend class InitializationSequence
Definition Sema.h:1588
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6361
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6498
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1300
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3519
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11455
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:149
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9734
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12991
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:8743
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13793
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4664
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3735
StringRef getKindName() const
Definition Decl.h:3931
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4901
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5037
TagKind getTagKind() const
Definition Decl.h:3935
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3706
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:3531
const Type * getTypeForDecl() const
Definition Decl.h:3556
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3565
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:884
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6273
A container of type source information.
Definition TypeBase.h:8407
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:8418
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:1871
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2538
bool isBooleanType() const
Definition TypeBase.h:9176
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2355
bool isRValueReferenceType() const
Definition TypeBase.h:8705
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8772
bool isPointerType() const
Definition TypeBase.h:8673
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9333
bool isReferenceType() const
Definition TypeBase.h:8697
bool isEnumeralType() const
Definition TypeBase.h:8804
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9161
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8860
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2954
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2845
bool isLValueReferenceType() const
Definition TypeBase.h:8701
bool isBitIntType() const
Definition TypeBase.h:8948
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8796
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2109
bool isMemberPointerType() const
Definition TypeBase.h:8754
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2855
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9182
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:5027
bool isPointerOrReferenceType() const
Definition TypeBase.h:8677
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8669
bool isVectorType() const
Definition TypeBase.h:8812
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2976
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2464
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9266
bool isNullPtrType() const
Definition TypeBase.h:9076
bool isRecordType() const
Definition TypeBase.h:8800
QualType getUnderlyingType() const
Definition Decl.h:3635
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4169
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1034
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1066
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1246
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1243
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1062
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1116
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1086
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6078
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3945
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3468
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
TLSKind getTLSKind() const
Definition Decl.cpp:2147
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2751
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:2886
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:2779
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:2758
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2877
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4021
Represents a GCC generic vector type.
Definition TypeBase.h:4230
QualType getElementType() const
Definition TypeBase.h:4244
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
const PartialDiagnosticAt & peekSFINAEDiagnostic() const
Peek at the SFINAE diagnostic.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1925
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1026
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1018
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1012
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1014
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Extern
Definition Specifiers.h:252
@ TSCS_unspecified
Definition Specifiers.h:237
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5986
@ Enum
The "enum" keyword.
Definition TypeBase.h:6000
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1805
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1251
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5961
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5982
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5975
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5979
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
CharacterLiteralKind
Definition Expr.h:1606
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5447
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3381
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3398
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3363
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12099
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12095
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12088
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12085
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12085
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13306
A stack object to be created when performing template instantiation.
Definition Sema.h:13393
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13546
NamedDecl * Previous
Definition Sema.h:356
Location information for a TemplateArgument.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1045