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