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