clang 24.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
24#include "clang/AST/Type.h"
32#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/Overload.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/SemaCUDA.h"
41#include "clang/Sema/Template.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/SmallBitVector.h"
45#include "llvm/ADT/StringExtras.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/SaveAndRestore.h"
48
49#include <optional>
50using namespace clang;
51using namespace sema;
52
53// Exported for use by Parser.
56 unsigned N) {
57 if (!N) return SourceRange();
58 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
59}
60
61unsigned Sema::getTemplateDepth(Scope *S) const {
62 unsigned Depth = 0;
63
64 // Each template parameter scope represents one level of template parameter
65 // depth.
66 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
67 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
68 ++Depth;
69 }
70
71 // Note that there are template parameters with the given depth.
72 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
73
74 // Look for parameters of an enclosing generic lambda. We don't create a
75 // template parameter scope for these.
77 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
78 if (!LSI->TemplateParams.empty()) {
79 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
80 break;
81 }
82 if (LSI->GLTemplateParameterList) {
83 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
84 break;
85 }
86 }
87 }
88
89 // Look for parameters of an enclosing terse function template. We don't
90 // create a template parameter scope for these either.
91 for (const InventedTemplateParameterInfo &Info :
93 if (!Info.TemplateParams.empty()) {
94 ParamsAtDepth(Info.AutoTemplateParameterDepth);
95 break;
96 }
97 }
98
99 return Depth;
100}
101
102/// \brief Determine whether the declaration found is acceptable as the name
103/// of a template and, if so, return that template declaration. Otherwise,
104/// returns null.
105///
106/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
107/// is true. In all other cases it will return a TemplateDecl (or null).
109 bool AllowFunctionTemplates,
110 bool AllowDependent) {
111 D = D->getUnderlyingDecl();
112
113 if (isa<TemplateDecl>(D)) {
114 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
115 return nullptr;
116
117 return D;
118 }
119
120 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
121 // C++ [temp.local]p1:
122 // Like normal (non-template) classes, class templates have an
123 // injected-class-name (Clause 9). The injected-class-name
124 // can be used with or without a template-argument-list. When
125 // it is used without a template-argument-list, it is
126 // equivalent to the injected-class-name followed by the
127 // template-parameters of the class template enclosed in
128 // <>. When it is used with a template-argument-list, it
129 // refers to the specified class template specialization,
130 // which could be the current specialization or another
131 // specialization.
132 if (Record->isInjectedClassName()) {
133 Record = cast<CXXRecordDecl>(Record->getDeclContext());
134 if (Record->getDescribedClassTemplate())
135 return Record->getDescribedClassTemplate();
136
137 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
138 return Spec->getSpecializedTemplate();
139 }
140
141 return nullptr;
142 }
143
144 // 'using Dependent::foo;' can resolve to a template name.
145 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
146 // injected-class-name).
147 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
148 return D;
149
150 return nullptr;
151}
152
154 bool AllowFunctionTemplates,
155 bool AllowDependent) {
156 LookupResult::Filter filter = R.makeFilter();
157 while (filter.hasNext()) {
158 NamedDecl *Orig = filter.next();
159 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
160 filter.erase();
161 }
162 filter.done();
163}
164
166 bool AllowFunctionTemplates,
167 bool AllowDependent,
168 bool AllowNonTemplateFunctions) {
169 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
170 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
171 return true;
172 if (AllowNonTemplateFunctions &&
173 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
174 return true;
175 }
176
177 return false;
178}
179
181Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
182 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
183 bool EnteringContext, TemplateTy &TemplateResult,
184 bool &MemberOfUnknownSpecialization,
185 bool AllowTypoCorrection) {
186 assert(getLangOpts().CPlusPlus && "No template names in C!");
187
188 DeclarationName TName;
189 MemberOfUnknownSpecialization = false;
190
191 switch (Name.getKind()) {
193 TName = DeclarationName(Name.Identifier);
194 break;
195
197 TName = Context.DeclarationNames.getCXXOperatorName(
199 break;
200
202 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203 break;
204
205 default:
206 return TNK_Non_template;
207 }
208
209 QualType ObjectType = ObjectTypePtr.get();
210
211 AssumedTemplateKind AssumedTemplate;
212 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214 /*RequiredTemplate=*/SourceLocation(),
215 &AssumedTemplate, AllowTypoCorrection))
216 return TNK_Non_template;
217 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
218
219 if (AssumedTemplate != AssumedTemplateKind::None) {
220 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
221 // Let the parser know whether we found nothing or found functions; if we
222 // found nothing, we want to more carefully check whether this is actually
223 // a function template name versus some other kind of undeclared identifier.
224 return AssumedTemplate == AssumedTemplateKind::FoundNothing
227 }
228
229 if (R.empty())
230 return TNK_Non_template;
231
232 NamedDecl *D = nullptr;
233 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
234 if (R.isAmbiguous()) {
235 // If we got an ambiguity involving a non-function template, treat this
236 // as a template name, and pick an arbitrary template for error recovery.
237 bool AnyFunctionTemplates = false;
238 for (NamedDecl *FoundD : R) {
239 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
240 if (isa<FunctionTemplateDecl>(FoundTemplate))
241 AnyFunctionTemplates = true;
242 else {
243 D = FoundTemplate;
244 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
245 break;
246 }
247 }
248 }
249
250 // If we didn't find any templates at all, this isn't a template name.
251 // Leave the ambiguity for a later lookup to diagnose.
252 if (!D && !AnyFunctionTemplates) {
253 R.suppressDiagnostics();
254 return TNK_Non_template;
255 }
256
257 // If the only templates were function templates, filter out the rest.
258 // We'll diagnose the ambiguity later.
259 if (!D)
261 }
262
263 // At this point, we have either picked a single template name declaration D
264 // or we have a non-empty set of results R containing either one template name
265 // declaration or a set of function templates.
266
268 TemplateNameKind TemplateKind;
269
270 unsigned ResultCount = R.end() - R.begin();
271 if (!D && ResultCount > 1) {
272 // We assume that we'll preserve the qualifier from a function
273 // template name in other ways.
274 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
275 TemplateKind = TNK_Function_template;
276
277 // We'll do this lookup again later.
278 R.suppressDiagnostics();
279 } else {
280 if (!D) {
281 D = getAsTemplateNameDecl(*R.begin());
282 assert(D && "unambiguous result is not a template name");
283 }
284
286 // We don't yet know whether this is a template-name or not.
287 MemberOfUnknownSpecialization = true;
288 return TNK_Non_template;
289 }
290
292 Template =
293 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
294 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
295 if (!SS.isInvalid()) {
296 NestedNameSpecifier Qualifier = SS.getScopeRep();
297 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
298 Template);
299 }
300
302 TemplateKind = TNK_Function_template;
303
304 // We'll do this lookup again later.
305 R.suppressDiagnostics();
306 } else {
310 TemplateKind =
312 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
316 }
317 }
318
320 S->getTemplateParamParent() == nullptr)
321 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
322 // Recover by returning the template, even though we would never be able to
323 // substitute it.
324
325 TemplateResult = TemplateTy::make(Template);
326 return TemplateKind;
327}
328
330 SourceLocation NameLoc, CXXScopeSpec &SS,
331 ParsedTemplateTy *Template /*=nullptr*/) {
332 // We could use redeclaration lookup here, but we don't need to: the
333 // syntactic form of a deduction guide is enough to identify it even
334 // if we can't look up the template name at all.
335 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
336 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
337 /*EnteringContext*/ false))
338 return false;
339
340 if (R.empty()) return false;
341 if (R.isAmbiguous()) {
342 // FIXME: Diagnose an ambiguity if we find at least one template.
343 R.suppressDiagnostics();
344 return false;
345 }
346
347 // We only treat template-names that name type templates as valid deduction
348 // guide names.
349 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
350 if (!TD || !getAsTypeTemplateDecl(TD))
351 return false;
352
353 if (Template) {
354 TemplateName Name = Context.getQualifiedTemplateName(
355 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
356 *Template = TemplateTy::make(Name);
357 }
358 return true;
359}
360
362 SourceLocation IILoc,
363 Scope *S,
364 const CXXScopeSpec *SS,
365 TemplateTy &SuggestedTemplate,
366 TemplateNameKind &SuggestedKind) {
367 // We can't recover unless there's a dependent scope specifier preceding the
368 // template name.
369 // FIXME: Typo correction?
370 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
372 return false;
373
374 // The code is missing a 'template' keyword prior to the dependent template
375 // name.
376 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
377 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
378 Diag(IILoc, diag::err_template_kw_missing)
379 << SuggestedTemplate.get()
380 << FixItHint::CreateInsertion(IILoc, "template ");
381 SuggestedKind = TNK_Dependent_template_name;
382 return true;
383}
384
386 QualType ObjectType, bool EnteringContext,
387 RequiredTemplateKind RequiredTemplate,
389 bool AllowTypoCorrection) {
390 if (ATK)
392
393 if (SS.isInvalid())
394 return true;
395
396 Found.setTemplateNameLookup(true);
397
398 // Determine where to perform name lookup
399 DeclContext *LookupCtx = nullptr;
400 bool IsDependent = false;
401 if (!ObjectType.isNull()) {
402 // This nested-name-specifier occurs in a member access expression, e.g.,
403 // x->B::f, and we are looking into the type of the object.
404 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
405 LookupCtx = computeDeclContext(ObjectType);
406 IsDependent = !LookupCtx && ObjectType->isDependentType();
407 assert((IsDependent || !ObjectType->isIncompleteType() ||
408 !ObjectType->getAs<TagType>() ||
409 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
410 "Caller should have completed object type");
411
412 // Template names cannot appear inside an Objective-C class or object type
413 // or a vector type.
414 //
415 // FIXME: This is wrong. For example:
416 //
417 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
418 // Vec<int> vi;
419 // vi.Vec<int>::~Vec<int>();
420 //
421 // ... should be accepted but we will not treat 'Vec' as a template name
422 // here. The right thing to do would be to check if the name is a valid
423 // vector component name, and look up a template name if not. And similarly
424 // for lookups into Objective-C class and object types, where the same
425 // problem can arise.
426 if (ObjectType->isObjCObjectOrInterfaceType() ||
427 ObjectType->isVectorType()) {
428 Found.clear();
429 return false;
430 }
431 } else if (SS.isNotEmpty()) {
432 // This nested-name-specifier occurs after another nested-name-specifier,
433 // so long into the context associated with the prior nested-name-specifier.
434 LookupCtx = computeDeclContext(SS, EnteringContext);
435 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
436
437 // The declaration context must be complete.
438 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
439 return true;
440 }
441
442 bool ObjectTypeSearchedInScope = false;
443 bool AllowFunctionTemplatesInLookup = true;
444 if (LookupCtx) {
445 // Perform "qualified" name lookup into the declaration context we
446 // computed, which is either the type of the base of a member access
447 // expression or the declaration context associated with a prior
448 // nested-name-specifier.
449 LookupQualifiedName(Found, LookupCtx);
450
451 // FIXME: The C++ standard does not clearly specify what happens in the
452 // case where the object type is dependent, and implementations vary. In
453 // Clang, we treat a name after a . or -> as a template-name if lookup
454 // finds a non-dependent member or member of the current instantiation that
455 // is a type template, or finds no such members and lookup in the context
456 // of the postfix-expression finds a type template. In the latter case, the
457 // name is nonetheless dependent, and we may resolve it to a member of an
458 // unknown specialization when we come to instantiate the template.
459 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
460 }
461
462 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
463 // C++ [basic.lookup.classref]p1:
464 // In a class member access expression (5.2.5), if the . or -> token is
465 // immediately followed by an identifier followed by a <, the
466 // identifier must be looked up to determine whether the < is the
467 // beginning of a template argument list (14.2) or a less-than operator.
468 // The identifier is first looked up in the class of the object
469 // expression. If the identifier is not found, it is then looked up in
470 // the context of the entire postfix-expression and shall name a class
471 // template.
472 if (S)
473 LookupName(Found, S);
474
475 if (!ObjectType.isNull()) {
476 // FIXME: We should filter out all non-type templates here, particularly
477 // variable templates and concepts. But the exclusion of alias templates
478 // and template template parameters is a wording defect.
479 AllowFunctionTemplatesInLookup = false;
480 ObjectTypeSearchedInScope = true;
481 }
482
483 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
484 }
485
486 if (Found.isAmbiguous())
487 return false;
488
489 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
490 !RequiredTemplate.hasTemplateKeyword()) {
491 // C++2a [temp.names]p2:
492 // A name is also considered to refer to a template if it is an
493 // unqualified-id followed by a < and name lookup finds either one or more
494 // functions or finds nothing.
495 //
496 // To keep our behavior consistent, we apply the "finds nothing" part in
497 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
498 // successfully form a call to an undeclared template-id.
499 bool AllFunctions =
500 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
502 });
503 if (AllFunctions || (Found.empty() && !IsDependent)) {
504 // If lookup found any functions, or if this is a name that can only be
505 // used for a function, then strongly assume this is a function
506 // template-id.
507 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
510 Found.clear();
511 return false;
512 }
513 }
514
515 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
516 // If we did not find any names, and this is not a disambiguation, attempt
517 // to correct any typos.
518 DeclarationName Name = Found.getLookupName();
519 Found.clear();
520
521 class TemplateNameLookupValidatorCCC final
523 public:
525
526 bool ValidateCandidate(const TypoCorrection &Candidate) final {
527 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
528 !ND || !isa<TemplateDecl>(ND))
529 return false;
531 }
532
533 std::unique_ptr<CorrectionCandidateCallback> clone() final {
534 return std::make_unique<TemplateNameLookupValidatorCCC>(*this);
535 }
536 };
537
538 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
539 FilterCCC.WantTypeSpecifiers = false;
540 FilterCCC.WantExpressionKeywords = false;
541 FilterCCC.WantRemainingKeywords = false;
542 FilterCCC.WantCXXNamedCasts = true;
543 if (TypoCorrection Corrected = CorrectTypo(
544 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
545 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
546 if (auto *ND = Corrected.getFoundDecl())
547 Found.addDecl(ND);
549 if (Found.isAmbiguous()) {
550 Found.clear();
551 } else if (!Found.empty()) {
552 // Do not erase the typo-corrected result to avoid duplicated
553 // diagnostics.
554 AllowFunctionTemplatesInLookup = true;
555 Found.setLookupName(Corrected.getCorrection());
556 if (LookupCtx) {
557 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
558 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
559 Name.getAsString() == CorrectedStr;
560 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
561 << Name << LookupCtx << DroppedSpecifier
562 << SS.getRange());
563 } else {
564 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
565 }
566
567 if (Corrected.WillReplaceSpecifier()) {
568 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
569 // In order to be valid, a non-empty CXXScopeSpec needs a source
570 // range.
571 SS.MakeTrivial(Context, NNS,
572 NNS ? Found.getNameLoc() : SourceRange());
573 }
574 }
575 }
576 }
577
578 NamedDecl *ExampleLookupResult =
579 Found.empty() ? nullptr : Found.getRepresentativeDecl();
580 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
581 if (Found.empty()) {
582 if (IsDependent) {
583 Found.setNotFoundInCurrentInstantiation();
584 return false;
585 }
586
587 // If a 'template' keyword was used, a lookup that finds only non-template
588 // names is an error.
589 if (ExampleLookupResult && RequiredTemplate) {
590 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
591 << Found.getLookupName() << SS.getRange()
592 << RequiredTemplate.hasTemplateKeyword()
593 << RequiredTemplate.getTemplateKeywordLoc();
594 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
595 diag::note_template_kw_refers_to_non_template)
596 << Found.getLookupName();
597 return true;
598 }
599
600 return false;
601 }
602
603 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
605 // C++03 [basic.lookup.classref]p1:
606 // [...] If the lookup in the class of the object expression finds a
607 // template, the name is also looked up in the context of the entire
608 // postfix-expression and [...]
609 //
610 // Note: C++11 does not perform this second lookup.
611 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
613 FoundOuter.setTemplateNameLookup(true);
614 LookupName(FoundOuter, S);
615 // FIXME: We silently accept an ambiguous lookup here, in violation of
616 // [basic.lookup]/1.
617 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
618
619 NamedDecl *OuterTemplate;
620 if (FoundOuter.empty()) {
621 // - if the name is not found, the name found in the class of the
622 // object expression is used, otherwise
623 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
624 !(OuterTemplate =
625 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
626 // - if the name is found in the context of the entire
627 // postfix-expression and does not name a class template, the name
628 // found in the class of the object expression is used, otherwise
629 FoundOuter.clear();
630 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
631 // - if the name found is a class template, it must refer to the same
632 // entity as the one found in the class of the object expression,
633 // otherwise the program is ill-formed.
634 if (!Found.isSingleResult() ||
635 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
636 OuterTemplate->getCanonicalDecl()) {
637 Diag(Found.getNameLoc(),
638 diag::ext_nested_name_member_ref_lookup_ambiguous)
639 << Found.getLookupName()
640 << ObjectType;
641 Diag(Found.getRepresentativeDecl()->getLocation(),
642 diag::note_ambig_member_ref_object_type)
643 << ObjectType;
644 Diag(FoundOuter.getFoundDecl()->getLocation(),
645 diag::note_ambig_member_ref_scope);
646
647 // Recover by taking the template that we found in the object
648 // expression's type.
649 }
650 }
651 }
652
653 return false;
654}
655
659 if (TemplateName.isInvalid())
660 return;
661
662 DeclarationNameInfo NameInfo;
663 CXXScopeSpec SS;
664 LookupNameKind LookupKind;
665
666 DeclContext *LookupCtx = nullptr;
667 NamedDecl *Found = nullptr;
668 bool MissingTemplateKeyword = false;
669
670 // Figure out what name we looked up.
671 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
672 NameInfo = DRE->getNameInfo();
673 SS.Adopt(DRE->getQualifierLoc());
674 LookupKind = LookupOrdinaryName;
675 Found = DRE->getFoundDecl();
676 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
677 NameInfo = ME->getMemberNameInfo();
678 SS.Adopt(ME->getQualifierLoc());
679 LookupKind = LookupMemberName;
680 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
681 Found = ME->getMemberDecl();
682 } else if (auto *DSDRE =
683 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
684 NameInfo = DSDRE->getNameInfo();
685 SS.Adopt(DSDRE->getQualifierLoc());
686 MissingTemplateKeyword = true;
687 } else if (auto *DSME =
688 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
689 NameInfo = DSME->getMemberNameInfo();
690 SS.Adopt(DSME->getQualifierLoc());
691 MissingTemplateKeyword = true;
692 } else {
693 llvm_unreachable("unexpected kind of potential template name");
694 }
695
696 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
697 // was missing.
698 if (MissingTemplateKeyword) {
699 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
700 << NameInfo.getName() << SourceRange(Less, Greater);
701 return;
702 }
703
704 // Try to correct the name by looking for templates and C++ named casts.
705 struct TemplateCandidateFilter : CorrectionCandidateCallback {
706 Sema &S;
707 TemplateCandidateFilter(Sema &S) : S(S) {
708 WantTypeSpecifiers = false;
709 WantExpressionKeywords = false;
710 WantRemainingKeywords = false;
711 WantCXXNamedCasts = true;
712 };
713 bool ValidateCandidate(const TypoCorrection &Candidate) override {
714 if (auto *ND = Candidate.getCorrectionDecl())
715 return S.getAsTemplateNameDecl(ND);
716 return Candidate.isKeyword();
717 }
718
719 std::unique_ptr<CorrectionCandidateCallback> clone() override {
720 return std::make_unique<TemplateCandidateFilter>(*this);
721 }
722 };
723
724 DeclarationName Name = NameInfo.getName();
725 TemplateCandidateFilter CCC(*this);
726 if (TypoCorrection Corrected =
727 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
728 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
729 auto *ND = Corrected.getFoundDecl();
730 if (ND)
731 ND = getAsTemplateNameDecl(ND);
732 if (ND || Corrected.isKeyword()) {
733 if (LookupCtx) {
734 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
735 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
736 Name.getAsString() == CorrectedStr;
737 diagnoseTypo(Corrected,
738 PDiag(diag::err_non_template_in_member_template_id_suggest)
739 << Name << LookupCtx << DroppedSpecifier
740 << SS.getRange(), false);
741 } else {
742 diagnoseTypo(Corrected,
743 PDiag(diag::err_non_template_in_template_id_suggest)
744 << Name, false);
745 }
746 if (Found)
747 Diag(Found->getLocation(),
748 diag::note_non_template_in_template_id_found);
749 return;
750 }
751 }
752
753 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
754 << Name << SourceRange(Less, Greater);
755 if (Found)
756 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
757}
758
761 SourceLocation TemplateKWLoc,
762 const DeclarationNameInfo &NameInfo,
763 bool isAddressOfOperand,
764 const TemplateArgumentListInfo *TemplateArgs) {
765 if (SS.isEmpty()) {
766 // FIXME: This codepath is only used by dependent unqualified names
767 // (e.g. a dependent conversion-function-id, or operator= once we support
768 // it). It doesn't quite do the right thing, and it will silently fail if
769 // getCurrentThisType() returns null.
770 QualType ThisType = getCurrentThisType();
771 if (ThisType.isNull())
772 return ExprError();
773
775 Context, /*Base=*/nullptr, ThisType,
776 /*IsArrow=*/!Context.getLangOpts().HLSL,
777 /*OperatorLoc=*/SourceLocation(),
778 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
779 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
780 }
781 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
782}
783
786 SourceLocation TemplateKWLoc,
787 const DeclarationNameInfo &NameInfo,
788 const TemplateArgumentListInfo *TemplateArgs) {
789 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
790 if (!SS.isValid())
791 return CreateRecoveryExpr(
792 SS.getBeginLoc(),
793 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
794
796 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
797 TemplateArgs);
798}
799
801Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
802 QualType ParamType, SourceLocation Loc,
804 UnsignedOrNone PackIndex, bool Final) {
805 // The template argument itself might be an expression, in which case we just
806 // return that expression. This happens when substituting into an alias
807 // template.
808 Expr *Replacement;
810 Replacement = Arg.getAsExpr();
811 } else {
812 ExprResult result =
813 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
814 if (result.isInvalid())
815 return ExprError();
816 Replacement = result.get();
817 }
818 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
819 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
820 AssociatedDecl, ParamType, Index, PackIndex, Final);
821}
822
824 NamedDecl *Instantiation,
825 bool InstantiatedFromMember,
826 const NamedDecl *Pattern,
827 const NamedDecl *PatternDef,
829 bool Complain, bool *Unreachable) {
830 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
831 isa<VarDecl>(Instantiation));
832
833 bool IsEntityBeingDefined = false;
834 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
835 IsEntityBeingDefined = TD->isBeingDefined();
836
837 if (PatternDef && !IsEntityBeingDefined) {
838 NamedDecl *SuggestedDef = nullptr;
839 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
840 &SuggestedDef,
841 /*OnlyNeedComplete*/ false)) {
842 if (Unreachable)
843 *Unreachable = true;
844 // If we're allowed to diagnose this and recover, do so.
845 bool Recover = Complain && !isSFINAEContext();
846 if (Complain)
847 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
849 return !Recover;
850 }
851 return false;
852 }
853
854 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
855 return true;
856
857 CanQualType InstantiationTy;
858 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
859 InstantiationTy = Context.getCanonicalTagType(TD);
860 if (PatternDef) {
861 Diag(PointOfInstantiation,
862 diag::err_template_instantiate_within_definition)
863 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
864 << InstantiationTy;
865 // Not much point in noting the template declaration here, since
866 // we're lexically inside it.
867 Instantiation->setInvalidDecl();
868 } else if (InstantiatedFromMember) {
869 if (isa<FunctionDecl>(Instantiation)) {
870 Diag(PointOfInstantiation,
871 diag::err_explicit_instantiation_undefined_member)
872 << /*member function*/ 1 << Instantiation->getDeclName()
873 << Instantiation->getDeclContext();
874 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
875 } else {
876 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
877 Diag(PointOfInstantiation,
878 diag::err_implicit_instantiate_member_undefined)
879 << InstantiationTy;
880 Diag(Pattern->getLocation(), diag::note_member_declared_at);
881 }
882 } else {
883 if (isa<FunctionDecl>(Instantiation)) {
884 Diag(PointOfInstantiation,
885 diag::err_explicit_instantiation_undefined_func_template)
886 << Pattern;
887 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
888 } else if (isa<TagDecl>(Instantiation)) {
889 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
890 << (TSK != TSK_ImplicitInstantiation)
891 << InstantiationTy;
892 NoteTemplateLocation(*Pattern);
893 } else {
894 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
895 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
896 Diag(PointOfInstantiation,
897 diag::err_explicit_instantiation_undefined_var_template)
898 << Instantiation;
899 Instantiation->setInvalidDecl();
900 } else
901 Diag(PointOfInstantiation,
902 diag::err_explicit_instantiation_undefined_member)
903 << /*static data member*/ 2 << Instantiation->getDeclName()
904 << Instantiation->getDeclContext();
905 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
906 }
907 }
908
909 // In general, Instantiation isn't marked invalid to get more than one
910 // error for multiple undefined instantiations. But the code that does
911 // explicit declaration -> explicit definition conversion can't handle
912 // invalid declarations, so mark as invalid in that case.
914 Instantiation->setInvalidDecl();
915 return true;
916}
917
919 bool SupportedForCompatibility) {
920 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
921
922 // C++23 [temp.local]p6:
923 // The name of a template-parameter shall not be bound to any following.
924 // declaration whose locus is contained by the scope to which the
925 // template-parameter belongs.
926 //
927 // When MSVC compatibility is enabled, the diagnostic is always a warning
928 // by default. Otherwise, it an error unless SupportedForCompatibility is
929 // true, in which case it is a default-to-error warning.
930 unsigned DiagId =
931 getLangOpts().MSVCCompat
932 ? diag::ext_template_param_shadow
933 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
934 : diag::err_template_param_shadow);
935 const auto *ND = cast<NamedDecl>(PrevDecl);
936 Diag(Loc, DiagId) << ND->getDeclName();
938}
939
941 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
942 D = Temp->getTemplatedDecl();
943 return Temp;
944 }
945 return nullptr;
946}
947
949 SourceLocation EllipsisLoc) const {
950 assert(Kind == Template &&
951 "Only template template arguments can be pack expansions here");
952 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
953 "Template template argument pack expansion without packs");
955 Result.EllipsisLoc = EllipsisLoc;
956 return Result;
957}
958
960 const ParsedTemplateArgument &Arg) {
961
962 switch (Arg.getKind()) {
964 TypeSourceInfo *TSI;
965 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
966 if (!TSI)
967 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
969 }
970
972 Expr *E = Arg.getAsExpr();
973 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
974 }
975
978 TemplateArgument TArg;
979 if (Arg.getEllipsisLoc().isValid())
980 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
981 else
982 TArg = Template;
983 return TemplateArgumentLoc(
984 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
986 Arg.getNameLoc(), Arg.getEllipsisLoc());
987 }
988 }
989
990 llvm_unreachable("Unhandled parsed template argument");
991}
992
994 TemplateArgumentListInfo &TemplateArgs) {
995 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
996 TemplateArgs.addArgument(translateTemplateArgument(*this,
997 TemplateArgsIn[I]));
998}
999
1001 SourceLocation Loc,
1002 const IdentifierInfo *Name) {
1003 NamedDecl *PrevDecl =
1004 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
1006 if (PrevDecl && PrevDecl->isTemplateParameter())
1007 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1008}
1009
1011 TypeSourceInfo *TInfo;
1012 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1013 if (T.isNull())
1014 return ParsedTemplateArgument();
1015 assert(TInfo && "template argument with no location");
1016
1017 // If we might have formed a deduced template specialization type, convert
1018 // it to a template template argument.
1019 if (getLangOpts().CPlusPlus17) {
1020 TypeLoc TL = TInfo->getTypeLoc();
1021 SourceLocation EllipsisLoc;
1022 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1023 EllipsisLoc = PET.getEllipsisLoc();
1024 TL = PET.getPatternLoc();
1025 }
1026
1027 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1028 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1029 CXXScopeSpec SS;
1030 SS.Adopt(DTST.getQualifierLoc());
1031 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1032 TemplateTy::make(Name),
1033 DTST.getTemplateNameLoc());
1034 if (EllipsisLoc.isValid())
1035 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1036 return Result;
1037 }
1038 }
1039
1040 // This is a normal type template argument. Note, if the type template
1041 // argument is an injected-class-name for a template, it has a dual nature
1042 // and can be used as either a type or a template. We handle that in
1043 // convertTypeTemplateArgumentToTemplate.
1045 ParsedType.get().getAsOpaquePtr(),
1046 TInfo->getTypeLoc().getBeginLoc());
1047}
1048
1050 SourceLocation EllipsisLoc,
1051 SourceLocation KeyLoc,
1052 IdentifierInfo *ParamName,
1053 SourceLocation ParamNameLoc,
1054 unsigned Depth, unsigned Position,
1055 SourceLocation EqualLoc,
1056 ParsedType DefaultArg,
1057 bool HasTypeConstraint) {
1058 assert(S->isTemplateParamScope() &&
1059 "Template type parameter not in template parameter scope!");
1060
1061 bool IsParameterPack = EllipsisLoc.isValid();
1063 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1064 KeyLoc, ParamNameLoc, Depth, Position,
1065 ParamName, Typename, IsParameterPack,
1066 HasTypeConstraint);
1067 Param->setAccess(AS_public);
1068
1069 if (Param->isParameterPack())
1070 if (auto *CSI = getEnclosingLambdaOrBlock())
1071 CSI->LocalPacks.push_back(Param);
1072
1073 if (ParamName) {
1074 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1075
1076 // Add the template parameter into the current scope.
1077 S->AddDecl(Param);
1078 IdResolver.AddDecl(Param);
1079 }
1080
1081 // C++0x [temp.param]p9:
1082 // A default template-argument may be specified for any kind of
1083 // template-parameter that is not a template parameter pack.
1084 if (DefaultArg && IsParameterPack) {
1085 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1086 DefaultArg = nullptr;
1087 }
1088
1089 // Handle the default argument, if provided.
1090 if (DefaultArg) {
1091 TypeSourceInfo *DefaultTInfo;
1092 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1093
1094 assert(DefaultTInfo && "expected source information for type");
1095
1096 // Check for unexpanded parameter packs.
1097 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1099 return Param;
1100
1101 // Check the template argument itself.
1102 if (CheckTemplateArgument(DefaultTInfo)) {
1103 Param->setInvalidDecl();
1104 return Param;
1105 }
1106
1107 Param->setDefaultArgument(
1108 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1109 }
1110
1111 return Param;
1112}
1113
1114/// Convert the parser's template argument list representation into our form.
1117 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1118 TemplateId.RAngleLoc);
1119 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1120 TemplateId.NumArgs);
1121 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1122 return TemplateArgs;
1123}
1124
1126
1127 TemplateName TN = TypeConstr->Template.get();
1128 NamedDecl *CD = nullptr;
1129 bool IsTypeConcept = false;
1130 bool RequiresArguments = false;
1131 if (auto *TTP = TN.getAsTemplateTemplateParmDecl()) {
1132 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1133 RequiresArguments =
1134 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1135 CD = TTP;
1136 } else {
1137 CD = TN.getAsTemplateDecl();
1138 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1139 RequiresArguments = cast<ConceptDecl>(CD)
1140 ->getTemplateParameters()
1141 ->getMinRequiredArguments() > 1;
1142 }
1143
1144 // C++2a [temp.param]p4:
1145 // [...] The concept designated by a type-constraint shall be a type
1146 // concept ([temp.concept]).
1147 if (!IsTypeConcept) {
1148 Diag(TypeConstr->TemplateNameLoc,
1149 diag::err_type_constraint_non_type_concept);
1150 return true;
1151 }
1152
1153 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1154 return true;
1155
1156 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1157
1158 if (!WereArgsSpecified && RequiresArguments) {
1159 Diag(TypeConstr->TemplateNameLoc,
1160 diag::err_type_constraint_missing_arguments)
1161 << CD;
1162 return true;
1163 }
1164 return false;
1165}
1166
1168 TemplateIdAnnotation *TypeConstr,
1169 TemplateTypeParmDecl *ConstrainedParameter,
1170 SourceLocation EllipsisLoc) {
1171 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1172 false);
1173}
1174
1176 TemplateIdAnnotation *TypeConstr,
1177 TemplateTypeParmDecl *ConstrainedParameter,
1178 SourceLocation EllipsisLoc,
1179 bool AllowUnexpandedPack) {
1180
1181 if (CheckTypeConstraint(TypeConstr))
1182 return true;
1183
1184 TemplateName TN = TypeConstr->Template.get();
1187
1188 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1189 TypeConstr->TemplateNameLoc);
1190
1191 TemplateArgumentListInfo TemplateArgs;
1192 if (TypeConstr->LAngleLoc.isValid()) {
1193 TemplateArgs =
1194 makeTemplateArgumentListInfo(*this, *TypeConstr);
1195
1196 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1197 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1199 return true;
1200 }
1201 }
1202 }
1203 return AttachTypeConstraint(
1205 ConceptName, TN,
1206 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : cast_if_present<NamedDecl>(CD),
1207 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1208 ConstrainedParameter, EllipsisLoc);
1209}
1210
1211template <typename ArgumentLocAppender>
1214 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1215 SourceLocation RAngleLoc, QualType ConstrainedType,
1216 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1217 SourceLocation EllipsisLoc) {
1218
1219 TemplateArgumentListInfo ConstraintArgs;
1220 ConstraintArgs.addArgument(
1222 /*NTTPType=*/QualType(), ParamNameLoc));
1223
1224 ConstraintArgs.setRAngleLoc(RAngleLoc);
1225 ConstraintArgs.setLAngleLoc(LAngleLoc);
1226 Appender(ConstraintArgs);
1227
1228 // C++2a [temp.param]p4:
1229 // [...] This constraint-expression E is called the immediately-declared
1230 // constraint of T. [...]
1231 CXXScopeSpec SS;
1232 SS.Adopt(NS);
1233 ExprResult ImmediatelyDeclaredConstraint;
1234 if (auto *CD =
1235 dyn_cast_if_present<ConceptDecl>(NamedConcept.getAsTemplateDecl())) {
1236 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1237 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1238 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1239 /*DoCheckConstraintSatisfaction=*/
1241 }
1242 // We have a template template parameter
1243 else {
1244 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1245 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1246 NameInfo, NamedConcept, &ConstraintArgs);
1247 }
1248 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1249 return ImmediatelyDeclaredConstraint;
1250
1251 // C++2a [temp.param]p4:
1252 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1253 //
1254 // We have the following case:
1255 //
1256 // template<typename T> concept C1 = true;
1257 // template<C1... T> struct s1;
1258 //
1259 // The constraint: (C1<T> && ...)
1260 //
1261 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1262 // any unqualified lookups for 'operator&&' here.
1263 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1264 /*LParenLoc=*/SourceLocation(),
1265 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1266 EllipsisLoc, /*RHS=*/nullptr,
1267 /*RParenLoc=*/SourceLocation(),
1268 /*NumExpansions=*/std::nullopt);
1269}
1270
1272 DeclarationNameInfo NameInfo,
1273 TemplateName NamedConcept, NamedDecl *FoundDecl,
1274 const TemplateArgumentListInfo *TemplateArgs,
1275 TemplateTypeParmDecl *ConstrainedParameter,
1276 SourceLocation EllipsisLoc) {
1277 // C++2a [temp.param]p4:
1278 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1279 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1280 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1282 *TemplateArgs) : nullptr;
1283
1284 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1285
1286 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1287 *this, NS, NameInfo, NamedConcept, FoundDecl,
1288 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1289 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1290 ParamAsArgument, ConstrainedParameter->getLocation(),
1291 [&](TemplateArgumentListInfo &ConstraintArgs) {
1292 if (TemplateArgs)
1293 for (const auto &ArgLoc : TemplateArgs->arguments())
1294 ConstraintArgs.addArgument(ArgLoc);
1295 },
1296 EllipsisLoc);
1297 if (ImmediatelyDeclaredConstraint.isInvalid())
1298 return true;
1299
1300 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1301 /*TemplateKWLoc=*/SourceLocation{},
1302 /*ConceptNameInfo=*/NameInfo,
1303 /*FoundDecl=*/FoundDecl,
1304 /*NamedConcept=*/NamedConcept,
1305 /*ArgsWritten=*/ArgsAsWritten);
1306 ConstrainedParameter->setTypeConstraint(
1307 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1308 return false;
1309}
1310
1312 NonTypeTemplateParmDecl *NewConstrainedParm,
1313 NonTypeTemplateParmDecl *OrigConstrainedParm,
1314 SourceLocation EllipsisLoc) {
1315 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1317 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1318 diag::err_unsupported_placeholder_constraint)
1319 << NewConstrainedParm->getTypeSourceInfo()
1320 ->getTypeLoc()
1321 .getSourceRange();
1322 NewConstrainedParm->setType(TL.getType());
1323 return true;
1324 }
1325 // FIXME: Concepts: This should be the type of the placeholder, but this is
1326 // unclear in the wording right now.
1327 DeclRefExpr *Ref =
1328 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1329 VK_PRValue, OrigConstrainedParm->getLocation());
1330 if (!Ref)
1331 return true;
1332 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1334 TL.getNamedConcept(),
1335 /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1336 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1337 [&](TemplateArgumentListInfo &ConstraintArgs) {
1338 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1339 ConstraintArgs.addArgument(TL.getArgLoc(I));
1340 },
1341 EllipsisLoc);
1342 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1343 !ImmediatelyDeclaredConstraint.isUsable())
1344 return true;
1345
1346 NewConstrainedParm->setPlaceholderTypeConstraint(
1347 ImmediatelyDeclaredConstraint.get());
1348 return false;
1349}
1350
1352 SourceLocation Loc) {
1353 if (TSI->getType()->isUndeducedType()) {
1354 // C++17 [temp.dep.expr]p3:
1355 // An id-expression is type-dependent if it contains
1356 // - an identifier associated by name lookup with a non-type
1357 // template-parameter declared with a type that contains a
1358 // placeholder type (7.1.7.4),
1360 if (!NewTSI)
1361 return QualType();
1362 TSI = NewTSI;
1363 }
1364
1365 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1366}
1367
1369 if (T->isDependentType())
1370 return false;
1371
1372 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1373 return true;
1374
1375 if (T->isStructuralType())
1376 return false;
1377
1378 // Structural types are required to be object types or lvalue references.
1379 if (T->isRValueReferenceType()) {
1380 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1381 return true;
1382 }
1383
1384 // Don't mention structural types in our diagnostic prior to C++20. Also,
1385 // there's not much more we can say about non-scalar non-class types --
1386 // because we can't see functions or arrays here, those can only be language
1387 // extensions.
1388 if (!getLangOpts().CPlusPlus20 ||
1389 (!T->isScalarType() && !T->isRecordType())) {
1390 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1391 return true;
1392 }
1393
1394 // Structural types are required to be literal types.
1395 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1396 return true;
1397
1398 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1399
1400 // Drill down into the reason why the class is non-structural.
1401 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1402 // All members are required to be public and non-mutable, and can't be of
1403 // rvalue reference type. Check these conditions first to prefer a "local"
1404 // reason over a more distant one.
1405 for (const FieldDecl *FD : RD->fields()) {
1406 if (FD->getAccess() != AS_public) {
1407 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1408 return true;
1409 }
1410 if (FD->isMutable()) {
1411 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1412 return true;
1413 }
1414 if (FD->getType()->isRValueReferenceType()) {
1415 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1416 << T;
1417 return true;
1418 }
1419 }
1420
1421 // All bases are required to be public.
1422 for (const auto &BaseSpec : RD->bases()) {
1423 if (BaseSpec.getAccessSpecifier() != AS_public) {
1424 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1425 << T << 1;
1426 return true;
1427 }
1428 }
1429
1430 // All subobjects are required to be of structural types.
1431 SourceLocation SubLoc;
1432 QualType SubType;
1433 int Kind = -1;
1434
1435 for (const FieldDecl *FD : RD->fields()) {
1436 QualType T = Context.getBaseElementType(FD->getType());
1437 if (!T->isStructuralType()) {
1438 SubLoc = FD->getLocation();
1439 SubType = T;
1440 Kind = 0;
1441 break;
1442 }
1443 }
1444
1445 if (Kind == -1) {
1446 for (const auto &BaseSpec : RD->bases()) {
1447 QualType T = BaseSpec.getType();
1448 if (!T->isStructuralType()) {
1449 SubLoc = BaseSpec.getBaseTypeLoc();
1450 SubType = T;
1451 Kind = 1;
1452 break;
1453 }
1454 }
1455 }
1456
1457 assert(Kind != -1 && "couldn't find reason why type is not structural");
1458 Diag(SubLoc, diag::note_not_structural_subobject)
1459 << T << Kind << SubType;
1460 T = SubType;
1461 RD = T->getAsCXXRecordDecl();
1462 }
1463
1464 return true;
1465}
1466
1468 SourceLocation Loc) {
1469 // We don't allow variably-modified types as the type of non-type template
1470 // parameters.
1471 if (T->isVariablyModifiedType()) {
1472 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1473 << T;
1474 return QualType();
1475 }
1476
1477 if (T->isBlockPointerType()) {
1478 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1479 return QualType();
1480 }
1481
1482 // C++ [temp.param]p4:
1483 //
1484 // A non-type template-parameter shall have one of the following
1485 // (optionally cv-qualified) types:
1486 //
1487 // -- integral or enumeration type,
1488 if (T->isIntegralOrEnumerationType() ||
1489 // -- pointer to object or pointer to function,
1490 T->isPointerType() ||
1491 // -- lvalue reference to object or lvalue reference to function,
1492 T->isLValueReferenceType() ||
1493 // -- pointer to member,
1494 T->isMemberPointerType() ||
1495 // -- std::nullptr_t, or
1496 T->isNullPtrType() ||
1497 // -- a type that contains a placeholder type.
1498 T->isUndeducedType()) {
1499 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1500 // are ignored when determining its type.
1501 return T.getUnqualifiedType();
1502 }
1503
1504 // C++ [temp.param]p8:
1505 //
1506 // A non-type template-parameter of type "array of T" or
1507 // "function returning T" is adjusted to be of type "pointer to
1508 // T" or "pointer to function returning T", respectively.
1509 if (T->isArrayType() || T->isFunctionType())
1510 return Context.getDecayedType(T);
1511
1512 // If T is a dependent type, we can't do the check now, so we
1513 // assume that it is well-formed. Note that stripping off the
1514 // qualifiers here is not really correct if T turns out to be
1515 // an array type, but we'll recompute the type everywhere it's
1516 // used during instantiation, so that should be OK. (Using the
1517 // qualified type is equally wrong.)
1518 if (T->isDependentType())
1519 return T.getUnqualifiedType();
1520
1521 // C++20 [temp.param]p6:
1522 // -- a structural type
1523 if (RequireStructuralType(T, Loc))
1524 return QualType();
1525
1526 if (!getLangOpts().CPlusPlus20) {
1527 // FIXME: Consider allowing structural types as an extension in C++17. (In
1528 // earlier language modes, the template argument evaluation rules are too
1529 // inflexible.)
1530 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1531 return QualType();
1532 }
1533
1534 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1535 return T.getUnqualifiedType();
1536}
1537
1539 unsigned Depth,
1540 unsigned Position,
1541 SourceLocation EqualLoc,
1542 Expr *Default) {
1544
1545 // Check that we have valid decl-specifiers specified.
1546 auto CheckValidDeclSpecifiers = [this, &D] {
1547 // C++ [temp.param]
1548 // p1
1549 // template-parameter:
1550 // ...
1551 // parameter-declaration
1552 // p2
1553 // ... A storage class shall not be specified in a template-parameter
1554 // declaration.
1555 // [dcl.typedef]p1:
1556 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1557 // of a parameter-declaration
1558 const DeclSpec &DS = D.getDeclSpec();
1559 auto EmitDiag = [this](SourceLocation Loc) {
1560 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1562 };
1564 EmitDiag(DS.getStorageClassSpecLoc());
1565
1567 EmitDiag(DS.getThreadStorageClassSpecLoc());
1568
1569 // [dcl.inline]p1:
1570 // The inline specifier can be applied only to the declaration or
1571 // definition of a variable or function.
1572
1573 if (DS.isInlineSpecified())
1574 EmitDiag(DS.getInlineSpecLoc());
1575
1576 // [dcl.constexpr]p1:
1577 // The constexpr specifier shall be applied only to the definition of a
1578 // variable or variable template or the declaration of a function or
1579 // function template.
1580
1581 if (DS.hasConstexprSpecifier())
1582 EmitDiag(DS.getConstexprSpecLoc());
1583
1584 // [dcl.fct.spec]p1:
1585 // Function-specifiers can be used only in function declarations.
1586
1587 if (DS.isVirtualSpecified())
1588 EmitDiag(DS.getVirtualSpecLoc());
1589
1590 if (DS.hasExplicitSpecifier())
1591 EmitDiag(DS.getExplicitSpecLoc());
1592
1593 if (DS.isNoreturnSpecified())
1594 EmitDiag(DS.getNoreturnSpecLoc());
1595 };
1596
1597 CheckValidDeclSpecifiers();
1598
1599 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1600 if (isa<AutoType>(T))
1602 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1603 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1604
1605 assert(S->isTemplateParamScope() &&
1606 "Non-type template parameter not in template parameter scope!");
1607 bool Invalid = false;
1608
1610 if (T.isNull()) {
1611 T = Context.IntTy; // Recover with an 'int' type.
1612 Invalid = true;
1613 }
1614
1616
1617 const IdentifierInfo *ParamName = D.getIdentifier();
1618 bool IsParameterPack = D.hasEllipsis();
1620 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1621 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1622 TInfo);
1623 Param->setAccess(AS_public);
1624
1626 if (TL.isConstrained()) {
1627 if (D.getEllipsisLoc().isInvalid() &&
1628 T->containsUnexpandedParameterPack()) {
1629 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1630 for (auto &Loc :
1631 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1634 }
1635 if (!Invalid &&
1636 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1637 Invalid = true;
1638 }
1639
1640 if (Invalid)
1641 Param->setInvalidDecl();
1642
1643 if (Param->isParameterPack())
1644 if (auto *CSI = getEnclosingLambdaOrBlock())
1645 CSI->LocalPacks.push_back(Param);
1646
1647 if (ParamName) {
1649 ParamName);
1650
1651 // Add the template parameter into the current scope.
1652 S->AddDecl(Param);
1653 IdResolver.AddDecl(Param);
1654 }
1655
1656 // C++0x [temp.param]p9:
1657 // A default template-argument may be specified for any kind of
1658 // template-parameter that is not a template parameter pack.
1659 if (Default && IsParameterPack) {
1660 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1661 Default = nullptr;
1662 }
1663
1664 // Check the well-formedness of the default template argument, if provided.
1665 if (Default) {
1666 // Check for unexpanded parameter packs.
1668 return Param;
1669
1670 Param->setDefaultArgument(
1672 TemplateArgument(Default, /*IsCanonical=*/false),
1673 QualType(), SourceLocation()));
1674 }
1675
1676 return Param;
1677}
1678
1679/// ActOnTemplateTemplateParameter - Called when a C++ template template
1680/// parameter (e.g. T in template <template <typename> class T> class array)
1681/// has been parsed. S is the current scope.
1683 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1684 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1685 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1686 unsigned Position, SourceLocation EqualLoc,
1688 assert(S->isTemplateParamScope() &&
1689 "Template template parameter not in template parameter scope!");
1690
1691 bool IsParameterPack = EllipsisLoc.isValid();
1692
1693 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1694 if (Params->size() == 0) {
1695 Diag(Loc, diag::err_template_template_parm_no_parms)
1696 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1697
1698 // Recover as if there was a type template parameter pack.
1699 SmallVector<NamedDecl *, 4> ParamDecls;
1700 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1701 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1702 Depth + 1, 0, /*Id=*/nullptr,
1703 /*Typename=*/false, /*ParameterPack=*/true));
1705 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1706 Params->getRAngleLoc(), Params->getRequiresClause());
1707 }
1708
1709 bool Invalid = false;
1711 Params,
1712 /*OldParams=*/nullptr,
1713 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1714 Invalid = true;
1715
1716 // Construct the parameter object.
1718 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1719 IsParameterPack, Name, Kind, Typename, Params);
1720 Param->setAccess(AS_public);
1721
1722 if (Param->isParameterPack())
1723 if (auto *LSI = getEnclosingLambdaOrBlock())
1724 LSI->LocalPacks.push_back(Param);
1725
1726 // If the template template parameter has a name, then link the identifier
1727 // into the scope and lookup mechanisms.
1728 if (Name) {
1729 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1730
1731 S->AddDecl(Param);
1732 IdResolver.AddDecl(Param);
1733 }
1734
1735 if (Invalid)
1736 Param->setInvalidDecl();
1737
1738 // C++0x [temp.param]p9:
1739 // A default template-argument may be specified for any kind of
1740 // template-parameter that is not a template parameter pack.
1741 if (IsParameterPack && !Default.isInvalid()) {
1742 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1744 }
1745
1746 if (!Default.isInvalid()) {
1747 // Check only that we have a template template argument. We don't want to
1748 // try to check well-formedness now, because our template template parameter
1749 // might have dependent types in its template parameters, which we wouldn't
1750 // be able to match now.
1751 //
1752 // If none of the template template parameter's template arguments mention
1753 // other template parameters, we could actually perform more checking here.
1754 // However, it isn't worth doing.
1756 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1757 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1758 << DefaultArg.getSourceRange();
1759 return Param;
1760 }
1761
1762 TemplateName Name =
1765 if (Template &&
1767 return Param;
1768 }
1769
1770 // Check for unexpanded parameter packs.
1772 DefaultArg.getArgument().getAsTemplate(),
1774 return Param;
1775
1776 Param->setDefaultArgument(Context, DefaultArg);
1777 }
1778
1779 return Param;
1780}
1781
1782namespace {
1783class ConstraintRefersToContainingTemplateChecker
1785 using inherited = ConstDynamicRecursiveASTVisitor;
1786 bool Result = false;
1787 const FunctionDecl *Friend = nullptr;
1788 unsigned TemplateDepth = 0;
1789
1790 // Check a record-decl that we've seen to see if it is a lexical parent of the
1791 // Friend, likely because it was referred to without its template arguments.
1792 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1793 CheckingRD = CheckingRD->getMostRecentDecl();
1794 if (!CheckingRD->isTemplated())
1795 return true;
1796
1797 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1798 DC && !DC->isFileContext(); DC = DC->getParent())
1799 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1800 if (CheckingRD == RD->getMostRecentDecl()) {
1801 Result = true;
1802 return false;
1803 }
1804
1805 return true;
1806 }
1807
1808 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1809 if (D->getDepth() < TemplateDepth)
1810 Result = true;
1811
1812 // Necessary because the type of the NTTP might be what refers to the parent
1813 // constriant.
1814 return TraverseType(D->getType());
1815 }
1816
1817public:
1818 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1819 unsigned TemplateDepth)
1820 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1821
1822 bool getResult() const { return Result; }
1823
1824 // This should be the only template parm type that we have to deal with.
1825 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1826 // FunctionParmPackExpr are all partially substituted, which cannot happen
1827 // with concepts at this point in translation.
1828 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1829 if (Type->getDecl()->getDepth() < TemplateDepth) {
1830 Result = true;
1831 return false;
1832 }
1833 return true;
1834 }
1835
1836 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1837 return TraverseDecl(E->getDecl());
1838 }
1839
1840 bool TraverseTypedefType(const TypedefType *TT,
1841 bool /*TraverseQualifier*/) override {
1842 return TraverseType(TT->desugar());
1843 }
1844
1845 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1846 // We don't care about TypeLocs. So traverse Types instead.
1847 return TraverseType(TL.getType(), TraverseQualifier);
1848 }
1849
1850 bool VisitTagType(const TagType *T) override {
1851 return TraverseDecl(T->getDecl());
1852 }
1853
1854 bool TraverseDecl(const Decl *D) override {
1855 assert(D);
1856 // FIXME : This is possibly an incomplete list, but it is unclear what other
1857 // Decl kinds could be used to refer to the template parameters. This is a
1858 // best guess so far based on examples currently available, but the
1859 // unreachable should catch future instances/cases.
1860 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1861 return TraverseType(TD->getUnderlyingType());
1862 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1863 return CheckNonTypeTemplateParmDecl(NTTPD);
1864 if (auto *VD = dyn_cast<ValueDecl>(D))
1865 return TraverseType(VD->getType());
1866 if (isa<TemplateDecl>(D))
1867 return true;
1868 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1869 return CheckIfContainingRecord(RD);
1870
1872 // No direct types to visit here I believe.
1873 } else
1874 llvm_unreachable("Don't know how to handle this declaration type yet");
1875 return true;
1876 }
1877};
1878} // namespace
1879
1881 const FunctionDecl *Friend, unsigned TemplateDepth,
1882 const Expr *Constraint) {
1883 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1884 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1885 Checker.TraverseStmt(Constraint);
1886 return Checker.getResult();
1887}
1888
1891 SourceLocation ExportLoc,
1892 SourceLocation TemplateLoc,
1893 SourceLocation LAngleLoc,
1894 ArrayRef<NamedDecl *> Params,
1895 SourceLocation RAngleLoc,
1896 Expr *RequiresClause) {
1897 if (ExportLoc.isValid())
1898 Diag(ExportLoc, diag::warn_template_export_unsupported);
1899
1900 for (NamedDecl *P : Params)
1902
1903 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1904 llvm::ArrayRef(Params), RAngleLoc,
1905 RequiresClause);
1906}
1907
1909 const CXXScopeSpec &SS) {
1910 if (SS.isSet())
1911 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1912}
1913
1914// Returns the template parameter list with all default template argument
1915// information.
1917 // Make sure we get the template parameter list from the most
1918 // recent declaration, since that is the only one that is guaranteed to
1919 // have all the default template argument information.
1920 Decl *D = TD->getMostRecentDecl();
1921 // C++11 N3337 [temp.param]p12:
1922 // A default template argument shall not be specified in a friend class
1923 // template declaration.
1924 //
1925 // Skip past friend *declarations* because they are not supposed to contain
1926 // default template arguments. Moreover, these declarations may introduce
1927 // template parameters living in different template depths than the
1928 // corresponding template parameters in TD, causing unmatched constraint
1929 // substitution.
1930 //
1931 // FIXME: Diagnose such cases within a class template:
1932 // template <class T>
1933 // struct S {
1934 // template <class = void> friend struct C;
1935 // };
1936 // template struct S<int>;
1938 D->getPreviousDecl())
1939 D = D->getPreviousDecl();
1940 return cast<TemplateDecl>(D)->getTemplateParameters();
1941}
1942
1944 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1945 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1946 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1947 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1948 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1949 TemplateParameterList **OuterTemplateParamLists,
1950 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1951 assert(TemplateParams && TemplateParams->size() > 0 &&
1952 "No template parameters");
1953 assert(TUK != TagUseKind::Reference &&
1954 "Can only declare or define class templates");
1955 bool Invalid = false;
1956
1957 // Check that we can declare a template here.
1958 if (CheckTemplateDeclScope(S, TemplateParams))
1959 return true;
1960
1962 assert(Kind != TagTypeKind::Enum &&
1963 "can't build template of enumerated type");
1964
1965 // There is no such thing as an unnamed class template.
1966 if (!Name) {
1967 Diag(KWLoc, diag::err_template_unnamed_class);
1968 return true;
1969 }
1970
1971 // Find any previous declaration with this name. For a friend with no
1972 // scope explicitly specified, we only look for tag declarations (per
1973 // C++11 [basic.lookup.elab]p2).
1974 DeclContext *SemanticContext;
1975 LookupResult Previous(*this, Name, NameLoc,
1976 (SS.isEmpty() && TUK == TagUseKind::Friend)
1980 if (SS.isNotEmpty() && !SS.isInvalid()) {
1981 SemanticContext = computeDeclContext(SS, true);
1982 if (!SemanticContext) {
1983 Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
1984 << SS.getScopeRep() << SS.getRange();
1985 return true;
1986 }
1987
1988 if (RequireCompleteDeclContext(SS, SemanticContext))
1989 return true;
1990
1991 // If we're adding a template to a dependent context, we may need to
1992 // rebuilding some of the types used within the template parameter list,
1993 // now that we know what the current instantiation is.
1994 if (SemanticContext->isDependentContext()) {
1995 ContextRAII SavedContext(*this, SemanticContext);
1997 Invalid = true;
1998 }
1999
2000 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2001 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2002 /*TemplateId=*/nullptr,
2003 IsMemberSpecialization))
2004 return true;
2005
2006 LookupQualifiedName(Previous, SemanticContext);
2007 } else {
2008 SemanticContext = CurContext;
2009
2010 // C++14 [class.mem]p14:
2011 // If T is the name of a class, then each of the following shall have a
2012 // name different from T:
2013 // -- every member template of class T
2014 if (TUK != TagUseKind::Friend &&
2015 DiagnoseClassNameShadow(SemanticContext,
2016 DeclarationNameInfo(Name, NameLoc)))
2017 return true;
2018
2019 LookupName(Previous, S);
2020 }
2021
2022 if (Previous.isAmbiguous())
2023 return true;
2024
2025 // Let the template parameter scope enter the lookup chain of the current
2026 // class template. For example, given
2027 //
2028 // namespace ns {
2029 // template <class> bool Param = false;
2030 // template <class T> struct N;
2031 // }
2032 //
2033 // template <class Param> struct ns::N { void foo(Param); };
2034 //
2035 // When we reference Param inside the function parameter list, our name lookup
2036 // chain for it should be like:
2037 // FunctionScope foo
2038 // -> RecordScope N
2039 // -> TemplateParamScope (where we will find Param)
2040 // -> NamespaceScope ns
2041 //
2042 // See also CppLookupName().
2043 if (S->isTemplateParamScope())
2044 EnterTemplatedContext(S, SemanticContext);
2045
2046 NamedDecl *PrevDecl = nullptr;
2047 if (Previous.begin() != Previous.end())
2048 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2049
2050 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2051 // Maybe we will complain about the shadowed template parameter.
2052 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2053 // Just pretend that we didn't see the previous declaration.
2054 PrevDecl = nullptr;
2055 }
2056
2057 // If there is a previous declaration with the same name, check
2058 // whether this is a valid redeclaration.
2059 ClassTemplateDecl *PrevClassTemplate =
2060 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2061
2062 // We may have found the injected-class-name of a class template,
2063 // class template partial specialization, or class template specialization.
2064 // In these cases, grab the template that is being defined or specialized.
2065 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2066 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2067 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2068 PrevClassTemplate
2069 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2070 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2071 PrevClassTemplate
2073 ->getSpecializedTemplate();
2074 }
2075 }
2076
2077 if (TUK == TagUseKind::Friend) {
2078 // C++ [namespace.memdef]p3:
2079 // [...] When looking for a prior declaration of a class or a function
2080 // declared as a friend, and when the name of the friend class or
2081 // function is neither a qualified name nor a template-id, scopes outside
2082 // the innermost enclosing namespace scope are not considered.
2083 if (!SS.isSet()) {
2084 DeclContext *OutermostContext = CurContext;
2085 while (!OutermostContext->isFileContext())
2086 OutermostContext = OutermostContext->getLookupParent();
2087
2088 if (PrevDecl &&
2089 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2090 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2091 SemanticContext = PrevDecl->getDeclContext();
2092 } else {
2093 // Declarations in outer scopes don't matter. However, the outermost
2094 // context we computed is the semantic context for our new
2095 // declaration.
2096 PrevDecl = PrevClassTemplate = nullptr;
2097 SemanticContext = OutermostContext;
2098
2099 // Check that the chosen semantic context doesn't already contain a
2100 // declaration of this name as a non-tag type.
2102 DeclContext *LookupContext = SemanticContext;
2103 while (LookupContext->isTransparentContext())
2104 LookupContext = LookupContext->getLookupParent();
2105 LookupQualifiedName(Previous, LookupContext);
2106
2107 if (Previous.isAmbiguous())
2108 return true;
2109
2110 if (Previous.begin() != Previous.end())
2111 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2112 }
2113 }
2114 } else if (PrevDecl &&
2115 !isTagRedeclarationInScope(Previous.getRepresentativeDecl(),
2116 SemanticContext, S, SS.isValid()))
2117 PrevDecl = PrevClassTemplate = nullptr;
2118
2119 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2120 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2121 if (SS.isEmpty() &&
2122 !(PrevClassTemplate &&
2123 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2124 SemanticContext->getRedeclContext()))) {
2125 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2126 Diag(Shadow->getTargetDecl()->getLocation(),
2127 diag::note_using_decl_target);
2128 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2129 // Recover by ignoring the old declaration.
2130 PrevDecl = PrevClassTemplate = nullptr;
2131 }
2132 }
2133
2134 if (PrevClassTemplate) {
2135 // Ensure that the template parameter lists are compatible. Skip this check
2136 // for a friend in a dependent context: the template parameter list itself
2137 // could be dependent.
2138 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2140 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2141 : CurContext,
2142 CurContext, KWLoc),
2143 TemplateParams, PrevClassTemplate,
2144 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2146 return true;
2147
2148 // C++ [temp.class]p4:
2149 // In a redeclaration, partial specialization, explicit
2150 // specialization or explicit instantiation of a class template,
2151 // the class-key shall agree in kind with the original class
2152 // template declaration (7.1.5.3).
2153 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2155 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2156 Diag(KWLoc, diag::err_use_with_wrong_tag)
2157 << Name
2158 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2159 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2160 Kind = PrevRecordDecl->getTagKind();
2161 }
2162
2163 // Check for redefinition of this class template.
2164 if (TUK == TagUseKind::Definition) {
2165 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2166 // If we have a prior definition that is not visible, treat this as
2167 // simply making that previous definition visible.
2168 NamedDecl *Hidden = nullptr;
2169 bool HiddenDefVisible = false;
2170 if (SkipBody &&
2171 isRedefinitionAllowedFor(Def, NameLoc, &Hidden, HiddenDefVisible)) {
2172 SkipBody->ShouldSkip = true;
2173 SkipBody->Previous = Def;
2174 if (!HiddenDefVisible && Hidden) {
2175 auto *Tmpl =
2176 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2177 assert(Tmpl && "original definition of a class template is not a "
2178 "class template?");
2181 }
2182 } else {
2183 Diag(NameLoc, diag::err_redefinition) << Name;
2184 Diag(Def->getLocation(), diag::note_previous_definition);
2185 // FIXME: Would it make sense to try to "forget" the previous
2186 // definition, as part of error recovery?
2187 return true;
2188 }
2189 }
2190 }
2191 } else if (PrevDecl) {
2192 // C++ [temp]p5:
2193 // A class template shall not have the same name as any other
2194 // template, class, function, object, enumeration, enumerator,
2195 // namespace, or type in the same scope (3.3), except as specified
2196 // in (14.5.4).
2197 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2198 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2199 return true;
2200 }
2201
2202 // Check the template parameter list of this declaration, possibly
2203 // merging in the template parameter list from the previous class
2204 // template declaration. Skip this check for a friend in a dependent
2205 // context, because the template parameter list might be dependent.
2206 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2208 TemplateParams,
2209 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2210 : nullptr,
2211 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2212 SemanticContext->isDependentContext())
2215 : TPC_Other,
2216 SkipBody))
2217 Invalid = true;
2218
2219 if (SS.isSet()) {
2220 // If the name of the template was qualified, we must be defining the
2221 // template out-of-line.
2222 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2223 return Diag(NameLoc, TUK == TagUseKind::Friend
2224 ? diag::err_friend_decl_does_not_match
2225 : diag::err_member_decl_does_not_match)
2226 << Name << SemanticContext << /*IsDefinition*/ true
2227 << SS.getRange();
2228 }
2229
2230 // If this is a templated friend in a dependent context we should not put it
2231 // on the redecl chain. In some cases, the templated friend can be the most
2232 // recent declaration tricking the template instantiator to make substitutions
2233 // there.
2234 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2235 bool ShouldAddRedecl =
2236 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2237
2239 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2240 PrevClassTemplate && ShouldAddRedecl
2241 ? PrevClassTemplate->getTemplatedDecl()
2242 : nullptr);
2243 SetNestedNameSpecifier(*this, NewClass, SS);
2244 if (NumOuterTemplateParamLists > 0)
2246 Context,
2247 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2248
2249 // Add alignment attributes if necessary; these attributes are checked when
2250 // the ASTContext lays out the structure.
2251 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2252 if (LangOpts.HLSL)
2253 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2256 }
2257
2258 ClassTemplateDecl *NewTemplate
2259 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2260 DeclarationName(Name), TemplateParams,
2261 NewClass);
2262
2263 if (ShouldAddRedecl)
2264 NewTemplate->setPreviousDecl(PrevClassTemplate);
2265
2266 NewClass->setDescribedClassTemplate(NewTemplate);
2267
2268 if (ModulePrivateLoc.isValid())
2269 NewTemplate->setModulePrivate();
2270
2271 if (IsMemberSpecialization) {
2272 assert(PrevClassTemplate &&
2273 "Member specialization without a primary template?");
2274 NewTemplate->setMemberSpecialization();
2275 }
2276
2277 // Set the access specifier.
2278 if (!Invalid && TUK != TagUseKind::Friend &&
2279 NewTemplate->getDeclContext()->isRecord())
2280 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2281
2282 // Set the lexical context of these templates
2284 NewTemplate->setLexicalDeclContext(CurContext);
2285
2286 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2287 NewClass->startDefinition();
2288
2289 ProcessDeclAttributeList(S, NewClass, Attr);
2290
2291 if (PrevClassTemplate) {
2292 mergeDeclAttributes(NewTemplate, PrevClassTemplate);
2293 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2294 }
2295
2299
2300 if (TUK != TagUseKind::Friend) {
2301 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2302 Scope *Outer = S;
2303 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2304 Outer = Outer->getParent();
2305 PushOnScopeChains(NewTemplate, Outer);
2306 } else {
2307 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2308 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2309 NewClass->setAccess(PrevClassTemplate->getAccess());
2310 }
2311
2312 NewTemplate->setObjectOfFriendDecl();
2313
2314 // Friend templates are visible in fairly strange ways.
2315 if (!CurContext->isDependentContext()) {
2316 DeclContext *DC = SemanticContext->getRedeclContext();
2317 DC->makeDeclVisibleInContext(NewTemplate);
2318 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2319 PushOnScopeChains(NewTemplate, EnclosingScope,
2320 /* AddToContext = */ false);
2321 }
2322
2324 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2325 Friend->setAccess(AS_public);
2326 CurContext->addDecl(Friend);
2327 }
2328
2329 if (PrevClassTemplate)
2330 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2331
2332 if (Invalid) {
2333 NewTemplate->setInvalidDecl();
2334 NewClass->setInvalidDecl();
2335 }
2336
2337 ActOnDocumentableDecl(NewTemplate);
2338
2339 if (SkipBody && SkipBody->ShouldSkip)
2340 return SkipBody->Previous;
2341
2342 return NewTemplate;
2343}
2344
2345/// Diagnose the presence of a default template argument on a
2346/// template parameter, which is ill-formed in certain contexts.
2347///
2348/// \returns true if the default template argument should be dropped.
2351 SourceLocation ParamLoc,
2352 SourceRange DefArgRange) {
2353 switch (TPC) {
2354 case Sema::TPC_Other:
2356 return false;
2357
2360 // C++ [temp.param]p9:
2361 // A default template-argument shall not be specified in a
2362 // function template declaration or a function template
2363 // definition [...]
2364 // If a friend function template declaration specifies a default
2365 // template-argument, that declaration shall be a definition and shall be
2366 // the only declaration of the function template in the translation unit.
2367 // (C++98/03 doesn't have this wording; see DR226).
2368 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2369 << DefArgRange;
2370 return false;
2371
2373 // C++0x [temp.param]p9:
2374 // A default template-argument shall not be specified in the
2375 // template-parameter-lists of the definition of a member of a
2376 // class template that appears outside of the member's class.
2377 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2378 << DefArgRange;
2379 return true;
2380
2383 // C++ [temp.param]p9:
2384 // A default template-argument shall not be specified in a
2385 // friend template declaration.
2386 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2387 << DefArgRange;
2388 return true;
2389
2390 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2391 // for friend function templates if there is only a single
2392 // declaration (and it is a definition). Strange!
2393 }
2394
2395 llvm_unreachable("Invalid TemplateParamListContext!");
2396}
2397
2398/// Check for unexpanded parameter packs within the template parameters
2399/// of a template template parameter, recursively.
2402 // A template template parameter which is a parameter pack is also a pack
2403 // expansion.
2404 if (TTP->isParameterPack())
2405 return false;
2406
2408 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2409 NamedDecl *P = Params->getParam(I);
2410 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2411 if (!TTP->isParameterPack())
2412 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2413 if (TC->hasExplicitTemplateArgs())
2414 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2417 return true;
2418 continue;
2419 }
2420
2421 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2422 if (!NTTP->isParameterPack() &&
2423 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2424 NTTP->getTypeSourceInfo(),
2426 return true;
2427
2428 continue;
2429 }
2430
2431 if (TemplateTemplateParmDecl *InnerTTP
2432 = dyn_cast<TemplateTemplateParmDecl>(P))
2433 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2434 return true;
2435 }
2436
2437 return false;
2438}
2439
2441 TemplateParameterList *OldParams,
2443 SkipBodyInfo *SkipBody) {
2444 bool Invalid = false;
2445
2446 // C++ [temp.param]p10:
2447 // The set of default template-arguments available for use with a
2448 // template declaration or definition is obtained by merging the
2449 // default arguments from the definition (if in scope) and all
2450 // declarations in scope in the same way default function
2451 // arguments are (8.3.6).
2452 bool SawDefaultArgument = false;
2453 SourceLocation PreviousDefaultArgLoc;
2454
2455 // Dummy initialization to avoid warnings.
2456 TemplateParameterList::iterator OldParam = NewParams->end();
2457 if (OldParams)
2458 OldParam = OldParams->begin();
2459
2460 bool RemoveDefaultArguments = false;
2461 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2462 NewParamEnd = NewParams->end();
2463 NewParam != NewParamEnd; ++NewParam) {
2464 // Whether we've seen a duplicate default argument in the same translation
2465 // unit.
2466 bool RedundantDefaultArg = false;
2467 // Whether we've found inconsis inconsitent default arguments in different
2468 // translation unit.
2469 bool InconsistentDefaultArg = false;
2470 // The name of the module which contains the inconsistent default argument.
2471 std::string PrevModuleName;
2472
2473 SourceLocation OldDefaultLoc;
2474 SourceLocation NewDefaultLoc;
2475
2476 // Variable used to diagnose missing default arguments
2477 bool MissingDefaultArg = false;
2478
2479 // Variable used to diagnose non-final parameter packs
2480 bool SawParameterPack = false;
2481
2482 if (TemplateTypeParmDecl *NewTypeParm
2483 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2484 // Check the presence of a default argument here.
2485 if (NewTypeParm->hasDefaultArgument() &&
2487 *this, TPC, NewTypeParm->getLocation(),
2488 NewTypeParm->getDefaultArgument().getSourceRange()))
2489 NewTypeParm->removeDefaultArgument();
2490
2491 // Merge default arguments for template type parameters.
2492 TemplateTypeParmDecl *OldTypeParm
2493 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2494 if (NewTypeParm->isParameterPack()) {
2495 assert(!NewTypeParm->hasDefaultArgument() &&
2496 "Parameter packs can't have a default argument!");
2497 SawParameterPack = true;
2498 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2499 NewTypeParm->hasDefaultArgument() &&
2500 (!SkipBody || !SkipBody->ShouldSkip)) {
2501 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2502 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2503 SawDefaultArgument = true;
2504
2505 if (!OldTypeParm->getOwningModule())
2506 RedundantDefaultArg = true;
2507 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2508 NewTypeParm)) {
2509 InconsistentDefaultArg = true;
2510 PrevModuleName =
2512 }
2513 PreviousDefaultArgLoc = NewDefaultLoc;
2514 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2515 // Merge the default argument from the old declaration to the
2516 // new declaration.
2517 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2518 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2519 } else if (NewTypeParm->hasDefaultArgument()) {
2520 SawDefaultArgument = true;
2521 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2522 } else if (SawDefaultArgument)
2523 MissingDefaultArg = true;
2524 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2525 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2526 // Check for unexpanded parameter packs, except in a template template
2527 // parameter pack, as in those any unexpanded packs should be expanded
2528 // along with the parameter itself.
2530 !NewNonTypeParm->isParameterPack() &&
2531 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2532 NewNonTypeParm->getTypeSourceInfo(),
2534 Invalid = true;
2535 continue;
2536 }
2537
2538 // Check the presence of a default argument here.
2539 if (NewNonTypeParm->hasDefaultArgument() &&
2541 *this, TPC, NewNonTypeParm->getLocation(),
2542 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2543 NewNonTypeParm->removeDefaultArgument();
2544 }
2545
2546 // Merge default arguments for non-type template parameters
2547 NonTypeTemplateParmDecl *OldNonTypeParm
2548 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2549 if (NewNonTypeParm->isParameterPack()) {
2550 assert(!NewNonTypeParm->hasDefaultArgument() &&
2551 "Parameter packs can't have a default argument!");
2552 if (!NewNonTypeParm->isPackExpansion())
2553 SawParameterPack = true;
2554 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2555 NewNonTypeParm->hasDefaultArgument() &&
2556 (!SkipBody || !SkipBody->ShouldSkip)) {
2557 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2558 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2559 SawDefaultArgument = true;
2560 if (!OldNonTypeParm->getOwningModule())
2561 RedundantDefaultArg = true;
2562 else if (!getASTContext().isSameDefaultTemplateArgument(
2563 OldNonTypeParm, NewNonTypeParm)) {
2564 InconsistentDefaultArg = true;
2565 PrevModuleName =
2566 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2567 }
2568 PreviousDefaultArgLoc = NewDefaultLoc;
2569 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2570 // Merge the default argument from the old declaration to the
2571 // new declaration.
2572 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2573 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2574 } else if (NewNonTypeParm->hasDefaultArgument()) {
2575 SawDefaultArgument = true;
2576 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2577 } else if (SawDefaultArgument)
2578 MissingDefaultArg = true;
2579 } else {
2580 TemplateTemplateParmDecl *NewTemplateParm
2581 = cast<TemplateTemplateParmDecl>(*NewParam);
2582
2583 // Check for unexpanded parameter packs, recursively.
2584 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2585 Invalid = true;
2586 continue;
2587 }
2588
2589 // Check the presence of a default argument here.
2590 if (NewTemplateParm->hasDefaultArgument() &&
2592 NewTemplateParm->getLocation(),
2593 NewTemplateParm->getDefaultArgument().getSourceRange()))
2594 NewTemplateParm->removeDefaultArgument();
2595
2596 // Merge default arguments for template template parameters
2597 TemplateTemplateParmDecl *OldTemplateParm
2598 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2599 if (NewTemplateParm->isParameterPack()) {
2600 assert(!NewTemplateParm->hasDefaultArgument() &&
2601 "Parameter packs can't have a default argument!");
2602 if (!NewTemplateParm->isPackExpansion())
2603 SawParameterPack = true;
2604 } else if (OldTemplateParm &&
2605 hasVisibleDefaultArgument(OldTemplateParm) &&
2606 NewTemplateParm->hasDefaultArgument() &&
2607 (!SkipBody || !SkipBody->ShouldSkip)) {
2608 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2609 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2610 SawDefaultArgument = true;
2611 if (!OldTemplateParm->getOwningModule())
2612 RedundantDefaultArg = true;
2613 else if (!getASTContext().isSameDefaultTemplateArgument(
2614 OldTemplateParm, NewTemplateParm)) {
2615 InconsistentDefaultArg = true;
2616 PrevModuleName =
2617 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2618 }
2619 PreviousDefaultArgLoc = NewDefaultLoc;
2620 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2621 // Merge the default argument from the old declaration to the
2622 // new declaration.
2623 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2624 PreviousDefaultArgLoc
2625 = OldTemplateParm->getDefaultArgument().getLocation();
2626 } else if (NewTemplateParm->hasDefaultArgument()) {
2627 SawDefaultArgument = true;
2628 PreviousDefaultArgLoc
2629 = NewTemplateParm->getDefaultArgument().getLocation();
2630 } else if (SawDefaultArgument)
2631 MissingDefaultArg = true;
2632 }
2633
2634 // C++11 [temp.param]p11:
2635 // If a template parameter of a primary class template or alias template
2636 // is a template parameter pack, it shall be the last template parameter.
2637 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2638 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2639 Diag((*NewParam)->getLocation(),
2640 diag::err_template_param_pack_must_be_last_template_parameter);
2641 Invalid = true;
2642 }
2643
2644 // [basic.def.odr]/13:
2645 // There can be more than one definition of a
2646 // ...
2647 // default template argument
2648 // ...
2649 // in a program provided that each definition appears in a different
2650 // translation unit and the definitions satisfy the [same-meaning
2651 // criteria of the ODR].
2652 //
2653 // Simply, the design of modules allows the definition of template default
2654 // argument to be repeated across translation unit. Note that the ODR is
2655 // checked elsewhere. But it is still not allowed to repeat template default
2656 // argument in the same translation unit.
2657 if (RedundantDefaultArg) {
2658 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2659 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2660 Invalid = true;
2661 } else if (InconsistentDefaultArg) {
2662 // We could only diagnose about the case that the OldParam is imported.
2663 // The case NewParam is imported should be handled in ASTReader.
2664 Diag(NewDefaultLoc,
2665 diag::err_template_param_default_arg_inconsistent_redefinition);
2666 Diag(OldDefaultLoc,
2667 diag::note_template_param_prev_default_arg_in_other_module)
2668 << PrevModuleName;
2669 Invalid = true;
2670 } else if (MissingDefaultArg &&
2671 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2672 TPC == TPC_FriendClassTemplate)) {
2673 // C++ 23[temp.param]p14:
2674 // If a template-parameter of a class template, variable template, or
2675 // alias template has a default template argument, each subsequent
2676 // template-parameter shall either have a default template argument
2677 // supplied or be a template parameter pack.
2678 Diag((*NewParam)->getLocation(),
2679 diag::err_template_param_default_arg_missing);
2680 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2681 Invalid = true;
2682 RemoveDefaultArguments = true;
2683 }
2684
2685 // If we have an old template parameter list that we're merging
2686 // in, move on to the next parameter.
2687 if (OldParams)
2688 ++OldParam;
2689 }
2690
2691 // We were missing some default arguments at the end of the list, so remove
2692 // all of the default arguments.
2693 if (RemoveDefaultArguments) {
2694 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2695 NewParamEnd = NewParams->end();
2696 NewParam != NewParamEnd; ++NewParam) {
2697 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2698 TTP->removeDefaultArgument();
2699 else if (NonTypeTemplateParmDecl *NTTP
2700 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2701 NTTP->removeDefaultArgument();
2702 else
2703 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2704 }
2705 }
2706
2707 return Invalid;
2708}
2709
2710namespace {
2711
2712/// A class which looks for a use of a certain level of template
2713/// parameter.
2714struct DependencyChecker : DynamicRecursiveASTVisitor {
2715 unsigned Depth;
2716
2717 // Whether we're looking for a use of a template parameter that makes the
2718 // overall construct type-dependent / a dependent type. This is strictly
2719 // best-effort for now; we may fail to match at all for a dependent type
2720 // in some cases if this is set.
2721 bool IgnoreNonTypeDependent;
2722
2723 bool Match;
2724 SourceLocation MatchLoc;
2725
2726 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2727 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2728 Match(false) {}
2729
2730 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2731 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2732 NamedDecl *ND = Params->getParam(0);
2733 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2734 Depth = PD->getDepth();
2735 } else if (NonTypeTemplateParmDecl *PD =
2736 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2737 Depth = PD->getDepth();
2738 } else {
2739 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2740 }
2741 }
2742
2743 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2744 if (ParmDepth >= Depth) {
2745 Match = true;
2746 MatchLoc = Loc;
2747 return true;
2748 }
2749 return false;
2750 }
2751
2752 bool TraverseStmt(Stmt *S) override {
2753 // Prune out non-type-dependent expressions if requested. This can
2754 // sometimes result in us failing to find a template parameter reference
2755 // (if a value-dependent expression creates a dependent type), but this
2756 // mode is best-effort only.
2757 if (auto *E = dyn_cast_or_null<Expr>(S))
2758 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2759 return true;
2761 }
2762
2763 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2764 if (IgnoreNonTypeDependent && !TL.isNull() &&
2765 !TL.getType()->isDependentType())
2766 return true;
2767 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2768 }
2769
2770 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2771 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2772 }
2773
2774 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2775 // For a best-effort search, keep looking until we find a location.
2776 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2777 }
2778
2779 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2780 if (TemplateTemplateParmDecl *PD =
2781 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2782 if (Matches(PD->getDepth()))
2783 return false;
2785 TraverseQualifier);
2786 }
2787
2788 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2789 if (NonTypeTemplateParmDecl *PD =
2790 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2791 if (Matches(PD->getDepth(), E->getExprLoc()))
2792 return false;
2793 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2794 }
2795
2796 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2797 if (Matches(E->getParameter()->getDepth(), E->getExprLoc()))
2798 return false;
2799 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(E);
2800 }
2801
2802 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2803 return TraverseType(T->getReplacementType());
2804 }
2805
2806 bool VisitSubstTemplateTypeParmPackType(
2807 SubstTemplateTypeParmPackType *T) override {
2808 return TraverseTemplateArgument(T->getArgumentPack());
2809 }
2810
2811 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2812 bool TraverseQualifier) override {
2813 // An InjectedClassNameType will never have a dependent template name,
2814 // so no need to traverse it.
2815 return TraverseTemplateArguments(
2816 T->getTemplateArgs(T->getDecl()->getASTContext()));
2817 }
2818};
2819} // end anonymous namespace
2820
2821/// Determines whether a given type depends on the given parameter
2822/// list.
2823static bool
2825 if (!Params->size())
2826 return false;
2827
2828 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2829 Checker.TraverseType(T);
2830 return Checker.Match;
2831}
2832
2833// Find the source range corresponding to the named type in the given
2834// nested-name-specifier, if any.
2836 QualType T,
2837 const CXXScopeSpec &SS) {
2839 for (;;) {
2842 break;
2843 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2844 return NNSLoc.castAsTypeLoc().getSourceRange();
2845 // FIXME: This will always be empty.
2846 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2847 }
2848
2849 return SourceRange();
2850}
2851
2853 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2854 TemplateIdAnnotation *TemplateId,
2855 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2856 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2857 IsMemberSpecialization = false;
2858 Invalid = false;
2859
2860 // The sequence of nested types to which we will match up the template
2861 // parameter lists. We first build this list by starting with the type named
2862 // by the nested-name-specifier and walking out until we run out of types.
2863 SmallVector<QualType, 4> NestedTypes;
2864 QualType T;
2865 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2866 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2867 if (CXXRecordDecl *Record =
2868 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2869 T = Context.getCanonicalTagType(Record);
2870 else
2871 T = QualType(Qualifier.getAsType(), 0);
2872 }
2873
2874 // If we found an explicit specialization that prevents us from needing
2875 // 'template<>' headers, this will be set to the location of that
2876 // explicit specialization.
2877 SourceLocation ExplicitSpecLoc;
2878
2879 while (!T.isNull()) {
2880 NestedTypes.push_back(T);
2881
2882 // Retrieve the parent of a record type.
2883 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2884 // If this type is an explicit specialization, we're done.
2886 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2888 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2889 ExplicitSpecLoc = Spec->getLocation();
2890 break;
2891 }
2892 } else if (Record->getTemplateSpecializationKind()
2894 ExplicitSpecLoc = Record->getLocation();
2895 break;
2896 }
2897
2898 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2899 T = Context.getTypeDeclType(Parent);
2900 else
2901 T = QualType();
2902 continue;
2903 }
2904
2905 if (const TemplateSpecializationType *TST
2906 = T->getAs<TemplateSpecializationType>()) {
2907 TemplateName Name = TST->getTemplateName();
2908 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2909 // Look one step prior in a dependent template specialization type.
2910 if (NestedNameSpecifier NNS = DTS->getQualifier();
2912 T = QualType(NNS.getAsType(), 0);
2913 else
2914 T = QualType();
2915 continue;
2916 }
2917 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2918 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2919 T = Context.getTypeDeclType(Parent);
2920 else
2921 T = QualType();
2922 continue;
2923 }
2924 }
2925
2926 // Look one step prior in a dependent name type.
2927 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2928 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2930 T = QualType(NNS.getAsType(), 0);
2931 else
2932 T = QualType();
2933 continue;
2934 }
2935
2936 // Retrieve the parent of an enumeration type.
2937 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2938 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2939 // check here.
2940 EnumDecl *Enum = EnumT->getDecl();
2941
2942 // Get to the parent type.
2943 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2944 T = Context.getCanonicalTypeDeclType(Parent);
2945 else
2946 T = QualType();
2947 continue;
2948 }
2949
2950 T = QualType();
2951 }
2952 // Reverse the nested types list, since we want to traverse from the outermost
2953 // to the innermost while checking template-parameter-lists.
2954 std::reverse(NestedTypes.begin(), NestedTypes.end());
2955
2956 // C++0x [temp.expl.spec]p17:
2957 // A member or a member template may be nested within many
2958 // enclosing class templates. In an explicit specialization for
2959 // such a member, the member declaration shall be preceded by a
2960 // template<> for each enclosing class template that is
2961 // explicitly specialized.
2962 bool SawNonEmptyTemplateParameterList = false;
2963
2964 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2965 if (SawNonEmptyTemplateParameterList) {
2966 if (!SuppressDiagnostic)
2967 Diag(DeclLoc, diag::err_specialize_member_of_template)
2968 << !Recovery << Range;
2969 Invalid = true;
2970 IsMemberSpecialization = false;
2971 return true;
2972 }
2973
2974 return false;
2975 };
2976
2977 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2978 // Check that we can have an explicit specialization here.
2979 if (CheckExplicitSpecialization(Range, true))
2980 return true;
2981
2982 // We don't have a template header, but we should.
2983 SourceLocation ExpectedTemplateLoc;
2984 if (!ParamLists.empty())
2985 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2986 else
2987 ExpectedTemplateLoc = DeclStartLoc;
2988
2989 if (!SuppressDiagnostic)
2990 Diag(DeclLoc, diag::err_template_spec_needs_header)
2991 << Range
2992 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2993 return false;
2994 };
2995
2996 unsigned ParamIdx = 0;
2997 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2998 ++TypeIdx) {
2999 T = NestedTypes[TypeIdx];
3000
3001 // Whether we expect a 'template<>' header.
3002 bool NeedEmptyTemplateHeader = false;
3003
3004 // Whether we expect a template header with parameters.
3005 bool NeedNonemptyTemplateHeader = false;
3006
3007 // For a dependent type, the set of template parameters that we
3008 // expect to see.
3009 TemplateParameterList *ExpectedTemplateParams = nullptr;
3010
3011 // C++0x [temp.expl.spec]p15:
3012 // A member or a member template may be nested within many enclosing
3013 // class templates. In an explicit specialization for such a member, the
3014 // member declaration shall be preceded by a template<> for each
3015 // enclosing class template that is explicitly specialized.
3016 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3018 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3019 ExpectedTemplateParams = Partial->getTemplateParameters();
3020 NeedNonemptyTemplateHeader = true;
3021 } else if (Record->isDependentType()) {
3022 if (Record->getDescribedClassTemplate()) {
3023 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3024 ->getTemplateParameters();
3025 NeedNonemptyTemplateHeader = true;
3026 }
3027 } else if (ClassTemplateSpecializationDecl *Spec
3028 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3029 // C++0x [temp.expl.spec]p4:
3030 // Members of an explicitly specialized class template are defined
3031 // in the same manner as members of normal classes, and not using
3032 // the template<> syntax.
3033 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3034 NeedEmptyTemplateHeader = true;
3035 else
3036 continue;
3037 } else if (Record->getTemplateSpecializationKind()) {
3038 if (Record->getTemplateSpecializationKind()
3040 TypeIdx == NumTypes - 1)
3041 IsMemberSpecialization = true;
3042
3043 continue;
3044 }
3045 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3046 TemplateName Name = TST->getTemplateName();
3047 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3048 ExpectedTemplateParams = Template->getTemplateParameters();
3049 NeedNonemptyTemplateHeader = true;
3050 } else if (Name.getAsDependentTemplateName()) {
3051 NeedNonemptyTemplateHeader = true;
3052 } else if (Name.getAsDeducedTemplateName()) {
3053 // FIXME: We actually could/should check the template arguments here
3054 // against the corresponding template parameter list.
3055 NeedNonemptyTemplateHeader = false;
3056 }
3057 }
3058
3059 // C++ [temp.expl.spec]p16:
3060 // In an explicit specialization declaration for a member of a class
3061 // template or a member template that appears in namespace scope, the
3062 // member template and some of its enclosing class templates may remain
3063 // unspecialized, except that the declaration shall not explicitly
3064 // specialize a class member template if its enclosing class templates
3065 // are not explicitly specialized as well.
3066 if (ParamIdx < ParamLists.size()) {
3067 if (ParamLists[ParamIdx]->size() == 0) {
3068 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3069 false))
3070 return nullptr;
3071 } else
3072 SawNonEmptyTemplateParameterList = true;
3073 }
3074
3075 if (NeedEmptyTemplateHeader) {
3076 // If we're on the last of the types, and we need a 'template<>' header
3077 // here, then it's a member specialization.
3078 if (TypeIdx == NumTypes - 1)
3079 IsMemberSpecialization = true;
3080
3081 if (ParamIdx < ParamLists.size()) {
3082 if (ParamLists[ParamIdx]->size() > 0) {
3083 // The header has template parameters when it shouldn't. Complain.
3084 if (!SuppressDiagnostic)
3085 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3086 diag::err_template_param_list_matches_nontemplate)
3087 << T
3088 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3089 ParamLists[ParamIdx]->getRAngleLoc())
3091 Invalid = true;
3092 return nullptr;
3093 }
3094
3095 // Consume this template header.
3096 ++ParamIdx;
3097 continue;
3098 }
3099
3100 if (!IsFriend)
3101 if (DiagnoseMissingExplicitSpecialization(
3103 return nullptr;
3104
3105 continue;
3106 }
3107
3108 if (NeedNonemptyTemplateHeader) {
3109 // In friend declarations we can have template-ids which don't
3110 // depend on the corresponding template parameter lists. But
3111 // assume that empty parameter lists are supposed to match this
3112 // template-id.
3113 if (IsFriend && T->isDependentType()) {
3114 if (ParamIdx < ParamLists.size() &&
3115 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3116 ExpectedTemplateParams = nullptr;
3117 else
3118 continue;
3119 }
3120
3121 if (ParamIdx < ParamLists.size()) {
3122 // Check the template parameter list, if we can.
3123 if (ExpectedTemplateParams &&
3125 ExpectedTemplateParams,
3126 !SuppressDiagnostic, TPL_TemplateMatch))
3127 Invalid = true;
3128
3129 if (!Invalid &&
3130 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3132 Invalid = true;
3133
3134 ++ParamIdx;
3135 continue;
3136 }
3137
3138 if (!SuppressDiagnostic)
3139 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3140 << T
3142 Invalid = true;
3143 continue;
3144 }
3145 }
3146
3147 // If there were at least as many template-ids as there were template
3148 // parameter lists, then there are no template parameter lists remaining for
3149 // the declaration itself.
3150 if (ParamIdx >= ParamLists.size()) {
3151 if (TemplateId && !IsFriend) {
3152 // We don't have a template header for the declaration itself, but we
3153 // should.
3154 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3155 TemplateId->RAngleLoc));
3156
3157 // Fabricate an empty template parameter list for the invented header.
3159 SourceLocation(), {},
3160 SourceLocation(), nullptr);
3161 }
3162
3163 return nullptr;
3164 }
3165
3166 // If there were too many template parameter lists, complain about that now.
3167 if (ParamIdx < ParamLists.size() - 1) {
3168 bool HasAnyExplicitSpecHeader = false;
3169 bool AllExplicitSpecHeaders = true;
3170 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3171 if (ParamLists[I]->size() == 0)
3172 HasAnyExplicitSpecHeader = true;
3173 else
3174 AllExplicitSpecHeaders = false;
3175 }
3176
3177 if (!SuppressDiagnostic)
3178 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3179 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3180 : diag::err_template_spec_extra_headers)
3181 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3182 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3183
3184 // If there was a specialization somewhere, such that 'template<>' is
3185 // not required, and there were any 'template<>' headers, note where the
3186 // specialization occurred.
3187 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3188 !SuppressDiagnostic)
3189 Diag(ExplicitSpecLoc,
3190 diag::note_explicit_template_spec_does_not_need_header)
3191 << NestedTypes.back();
3192
3193 // We have a template parameter list with no corresponding scope, which
3194 // means that the resulting template declaration can't be instantiated
3195 // properly (we'll end up with dependent nodes when we shouldn't).
3196 if (!AllExplicitSpecHeaders)
3197 Invalid = true;
3198 }
3199
3200 // C++ [temp.expl.spec]p16:
3201 // In an explicit specialization declaration for a member of a class
3202 // template or a member template that ap- pears in namespace scope, the
3203 // member template and some of its enclosing class templates may remain
3204 // unspecialized, except that the declaration shall not explicitly
3205 // specialize a class member template if its en- closing class templates
3206 // are not explicitly specialized as well.
3207 if (ParamLists.back()->size() == 0 &&
3208 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3209 false))
3210 return nullptr;
3211
3212 // Return the last template parameter list, which corresponds to the
3213 // entity being declared.
3214 return ParamLists.back();
3215}
3216
3218 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3219 Diag(Template->getLocation(), diag::note_template_declared_here)
3221 ? 0
3223 ? 1
3225 ? 2
3227 << Template->getDeclName();
3228 return;
3229 }
3230
3232 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3233 IEnd = OST->end();
3234 I != IEnd; ++I)
3235 Diag((*I)->getLocation(), diag::note_template_declared_here)
3236 << 0 << (*I)->getDeclName();
3237
3238 return;
3239 }
3240}
3241
3243 TemplateName BaseTemplate,
3244 SourceLocation TemplateLoc,
3246 auto lookUpCommonType = [&](TemplateArgument T1,
3247 TemplateArgument T2) -> QualType {
3248 // Don't bother looking for other specializations if both types are
3249 // builtins - users aren't allowed to specialize for them
3250 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3251 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3252 {T1, T2});
3253
3257 Args.addArgument(TemplateArgumentLoc(
3258 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3259
3260 EnterExpressionEvaluationContext UnevaluatedContext(
3262 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3264
3265 QualType BaseTemplateInst = S.CheckTemplateIdType(
3266 Keyword, BaseTemplate, TemplateLoc, Args,
3267 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3268
3269 if (SFINAE.hasErrorOccurred())
3270 return QualType();
3271
3272 return BaseTemplateInst;
3273 };
3274
3275 // Note A: For the common_type trait applied to a template parameter pack T of
3276 // types, the member type shall be either defined or not present as follows:
3277 switch (Ts.size()) {
3278
3279 // If sizeof...(T) is zero, there shall be no member type.
3280 case 0:
3281 return QualType();
3282
3283 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3284 // pack T. The member typedef-name type shall denote the same type, if any, as
3285 // common_type_t<T0, T0>; otherwise there shall be no member type.
3286 case 1:
3287 return lookUpCommonType(Ts[0], Ts[0]);
3288
3289 // If sizeof...(T) is two, let the first and second types constituting T be
3290 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3291 // as decay_t<T1> and decay_t<T2>, respectively.
3292 case 2: {
3293 QualType T1 = Ts[0].getAsType();
3294 QualType T2 = Ts[1].getAsType();
3295 QualType D1 = S.BuiltinDecay(T1, {});
3296 QualType D2 = S.BuiltinDecay(T2, {});
3297
3298 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3299 // the same type, if any, as common_type_t<D1, D2>.
3300 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3301 return lookUpCommonType(D1, D2);
3302
3303 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3304 // denotes a valid type, let C denote that type.
3305 {
3306 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3307 EnterExpressionEvaluationContext UnevaluatedContext(
3309 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3311
3312 // false
3314 VK_PRValue);
3315 ExprResult Cond = &CondExpr;
3316
3317 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3318 if (ConstRefQual) {
3319 D1.addConst();
3320 D2.addConst();
3321 }
3322
3323 // declval<D1>()
3324 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3325 ExprResult LHS = &LHSExpr;
3326
3327 // declval<D2>()
3328 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3329 ExprResult RHS = &RHSExpr;
3330
3333
3334 // decltype(false ? declval<D1>() : declval<D2>())
3336 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3337
3338 if (Result.isNull() || SFINAE.hasErrorOccurred())
3339 return QualType();
3340
3341 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3342 return S.BuiltinDecay(Result, TemplateLoc);
3343 };
3344
3345 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3346 return Res;
3347
3348 // Let:
3349 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3350 // COND-RES(X, Y) be
3351 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3352
3353 // C++20 only
3354 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3355 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3356 if (!S.Context.getLangOpts().CPlusPlus20)
3357 return QualType();
3358 return CheckConditionalOperands(true);
3359 }
3360 }
3361
3362 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3363 // denote the first, second, and (pack of) remaining types constituting T. Let
3364 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3365 // a type C, the member typedef-name type shall denote the same type, if any,
3366 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3367 default: {
3368 QualType Result = Ts.front().getAsType();
3369 for (auto T : llvm::drop_begin(Ts)) {
3370 Result = lookUpCommonType(Result, T.getAsType());
3371 if (Result.isNull())
3372 return QualType();
3373 }
3374 return Result;
3375 }
3376 }
3377}
3378
3379static bool isInVkNamespace(const RecordType *RT) {
3380 DeclContext *DC = RT->getDecl()->getDeclContext();
3381 if (!DC)
3382 return false;
3383
3384 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3385 if (!ND)
3386 return false;
3387
3388 return ND->getQualifiedNameAsString() == "hlsl::vk";
3389}
3390
3391static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3392 QualType OperandArg,
3393 SourceLocation Loc) {
3394 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3395 bool Literal = false;
3396 SourceLocation LiteralLoc;
3397 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3398 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3399 assert(SpecDecl);
3400
3401 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3402 QualType ConstantType = LiteralArgs[0].getAsType();
3403 RT = ConstantType->getAsCanonical<RecordType>();
3404 Literal = true;
3405 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3406 }
3407
3408 if (RT && isInVkNamespace(RT) &&
3409 RT->getDecl()->getName() == "integral_constant") {
3410 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3411 assert(SpecDecl);
3412
3413 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3414
3415 QualType ConstantType = ConstantArgs[0].getAsType();
3416 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3417
3418 if (Literal)
3419 return SpirvOperand::createLiteral(Value);
3420 return SpirvOperand::createConstant(ConstantType, Value);
3421 } else if (Literal) {
3422 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3423 return SpirvOperand();
3424 }
3425 }
3426 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3427 diag::err_call_incomplete_argument))
3428 return SpirvOperand();
3429 return SpirvOperand::createType(OperandArg);
3430}
3431
3433 ArrayRef<TemplateArgument> InputArgs) {
3434 // FIXME: cache mangling globally?
3435 std::unique_ptr<MangleContext> MC(Context.createMangleContext());
3437 InputArgs.size());
3438 llvm::transform(InputArgs, SortedArgs.begin(),
3439 [&](const TemplateArgument &Arg) {
3440 assert(Arg.getKind() == TemplateArgument::Type);
3441 std::string MangledName;
3442 llvm::raw_string_ostream OS(MangledName);
3443 MC->mangleCanonicalTypeName(Arg.getAsType(), OS);
3444 return std::pair<std::string, TemplateArgument>(
3445 std::move(MangledName), Arg);
3446 });
3447 llvm::stable_sort(SortedArgs, llvm::less_first());
3448
3449 auto OutArgs = llvm::to_vector(llvm::make_second_range(SortedArgs));
3450 return Context.getSubstBuiltinTemplatePack(
3451 TemplateArgument::CreatePackCopy(Context, OutArgs));
3452}
3453
3456 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3457 TemplateArgumentListInfo &TemplateArgs) {
3458 ASTContext &Context = SemaRef.getASTContext();
3459
3460 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3461 "Builtin template arguments do not match its parameters");
3462
3463 switch (BTD->getBuiltinTemplateKind()) {
3464 case BTK__make_integer_seq: {
3465 // Specializations of __make_integer_seq<S, T, N> are treated like
3466 // S<T, 0, ..., N-1>.
3467
3468 QualType OrigType = Converted[1].getAsType();
3469 // C++14 [inteseq.intseq]p1:
3470 // T shall be an integer type.
3471 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3472 SemaRef.Diag(TemplateArgs[1].getLocation(),
3473 diag::err_integer_sequence_integral_element_type);
3474 return QualType();
3475 }
3476
3477 TemplateArgument NumArgsArg = Converted[2];
3478 if (NumArgsArg.isDependent())
3479 return QualType();
3480
3481 TemplateArgumentListInfo SyntheticTemplateArgs;
3482 // The type argument, wrapped in substitution sugar, gets reused as the
3483 // first template argument in the synthetic template argument list.
3484 SyntheticTemplateArgs.addArgument(
3487 OrigType, TemplateArgs[1].getLocation())));
3488
3489 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3490 // Expand N into 0 ... N-1.
3491 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3492 I < NumArgs; ++I) {
3493 TemplateArgument TA(Context, I, OrigType);
3494 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3495 TA, OrigType, TemplateArgs[2].getLocation()));
3496 }
3497 } else {
3498 // C++14 [inteseq.make]p1:
3499 // If N is negative the program is ill-formed.
3500 SemaRef.Diag(TemplateArgs[2].getLocation(),
3501 diag::err_integer_sequence_negative_length);
3502 return QualType();
3503 }
3504
3505 // The first template argument will be reused as the template decl that
3506 // our synthetic template arguments will be applied to.
3507 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3508 TemplateLoc, SyntheticTemplateArgs,
3509 /*Scope=*/nullptr,
3510 /*ForNestedNameSpecifier=*/false);
3511 }
3512
3513 case BTK__type_pack_element: {
3514 // Specializations of
3515 // __type_pack_element<Index, T_1, ..., T_N>
3516 // are treated like T_Index.
3517 assert(Converted.size() == 2 &&
3518 "__type_pack_element should be given an index and a parameter pack");
3519
3520 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3521 if (IndexArg.isDependent() || Ts.isDependent())
3522 return QualType();
3523
3524 llvm::APSInt Index = IndexArg.getAsIntegral();
3525 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3526 "type std::size_t, and hence be non-negative");
3527 // If the Index is out of bounds, the program is ill-formed.
3528 if (Index >= Ts.pack_size()) {
3529 SemaRef.Diag(TemplateArgs[0].getLocation(),
3530 diag::err_type_pack_element_out_of_bounds);
3531 return QualType();
3532 }
3533
3534 // We simply return the type at index `Index`.
3535 int64_t N = Index.getExtValue();
3536 return Ts.getPackAsArray()[N].getAsType();
3537 }
3538
3539 case BTK__builtin_common_type: {
3540 assert(Converted.size() == 4);
3541 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3542 return QualType();
3543
3544 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3545 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3546 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3547 TemplateLoc, Ts);
3548 !CT.isNull()) {
3552 CT, TemplateArgs[1].getLocation())));
3553 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3554 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3555 TAs, /*Scope=*/nullptr,
3556 /*ForNestedNameSpecifier=*/false);
3557 }
3558 QualType HasNoTypeMember = Converted[2].getAsType();
3559 return HasNoTypeMember;
3560 }
3561
3562 case BTK__hlsl_spirv_type: {
3563 assert(Converted.size() == 4);
3564
3565 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3566 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3567 }
3568
3569 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3570 return QualType();
3571
3572 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3573 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3574 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3575
3576 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3577
3579
3580 for (auto &OperandTA : OperandArgs) {
3581 QualType OperandArg = OperandTA.getAsType();
3582 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3583 TemplateArgs[3].getLocation());
3584 if (!Operand.isValid())
3585 return QualType();
3586 Operands.push_back(Operand);
3587 }
3588
3589 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3590 }
3591 case BTK__builtin_dedup_pack: {
3592 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3593 "a parameter pack");
3594 TemplateArgument Ts = Converted[0];
3595 // Delay the computation until we can compute the final result. We choose
3596 // not to remove the duplicates upfront before substitution to keep the code
3597 // simple.
3598 if (Ts.isDependent())
3599 return QualType();
3600 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3602 llvm::SmallDenseSet<QualType> Seen;
3603 // Synthesize a new template argument list, removing duplicates.
3604 for (auto T : Ts.getPackAsArray()) {
3605 assert(T.getKind() == clang::TemplateArgument::Type);
3606 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3607 continue;
3608 OutArgs.push_back(T);
3609 }
3610 return Context.getSubstBuiltinTemplatePack(
3611 TemplateArgument::CreatePackCopy(Context, OutArgs));
3612 }
3613 case BTK__builtin_sort_pack: {
3614 assert(Converted.size() == 1 &&
3615 "__builtin_sort_pack should be given a parameter pack");
3616 TemplateArgument Ts = Converted[0];
3617 if (Ts.isDependent())
3618 return QualType();
3619 assert(Ts.getKind() == TemplateArgument::Pack);
3620 return sortBuiltinTemplatePack(Context, Ts.getPackAsArray());
3621 }
3622 }
3623 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3624}
3625
3626/// Determine whether this alias template is "enable_if_t".
3627/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3629 return AliasTemplate->getName() == "enable_if_t" ||
3630 AliasTemplate->getName() == "__enable_if_t";
3631}
3632
3633/// Collect all of the separable terms in the given condition, which
3634/// might be a conjunction.
3635///
3636/// FIXME: The right answer is to convert the logical expression into
3637/// disjunctive normal form, so we can find the first failed term
3638/// within each possible clause.
3639static void collectConjunctionTerms(Expr *Clause,
3640 SmallVectorImpl<Expr *> &Terms) {
3641 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3642 if (BinOp->getOpcode() == BO_LAnd) {
3643 collectConjunctionTerms(BinOp->getLHS(), Terms);
3644 collectConjunctionTerms(BinOp->getRHS(), Terms);
3645 return;
3646 }
3647 }
3648
3649 Terms.push_back(Clause);
3650}
3651
3652// The ranges-v3 library uses an odd pattern of a top-level "||" with
3653// a left-hand side that is value-dependent but never true. Identify
3654// the idiom and ignore that term.
3656 // Top-level '||'.
3657 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3658 if (!BinOp) return Cond;
3659
3660 if (BinOp->getOpcode() != BO_LOr) return Cond;
3661
3662 // With an inner '==' that has a literal on the right-hand side.
3663 Expr *LHS = BinOp->getLHS();
3664 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3665 if (!InnerBinOp) return Cond;
3666
3667 if (InnerBinOp->getOpcode() != BO_EQ ||
3668 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3669 return Cond;
3670
3671 // If the inner binary operation came from a macro expansion named
3672 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3673 // of the '||', which is the real, user-provided condition.
3674 SourceLocation Loc = InnerBinOp->getExprLoc();
3675 if (!Loc.isMacroID()) return Cond;
3676
3677 StringRef MacroName = PP.getImmediateMacroName(Loc);
3678 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3679 return BinOp->getRHS();
3680
3681 return Cond;
3682}
3683
3684namespace {
3685
3686// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3687// within failing boolean expression, such as substituting template parameters
3688// for actual types.
3689class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3690public:
3691 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3692 : Policy(P) {}
3693
3694 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3695 const auto *DR = dyn_cast<DeclRefExpr>(E);
3696 if (DR && DR->getQualifier()) {
3697 // If this is a qualified name, expand the template arguments in nested
3698 // qualifiers.
3699 DR->getQualifier().print(OS, Policy, true);
3700 // Then print the decl itself.
3701 const ValueDecl *VD = DR->getDecl();
3702 OS << *VD;
3703 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3704 // This is a template variable, print the expanded template arguments.
3705 printTemplateArgumentList(
3706 OS, IV->getTemplateArgs().asArray(), Policy,
3707 IV->getSpecializedTemplate()->getTemplateParameters());
3708 }
3709 return true;
3710 }
3711 return false;
3712 }
3713
3714private:
3715 const PrintingPolicy Policy;
3716};
3717
3718} // end anonymous namespace
3719
3720std::pair<Expr *, std::string>
3722 Cond = lookThroughRangesV3Condition(PP, Cond);
3723
3724 // Separate out all of the terms in a conjunction.
3726 collectConjunctionTerms(Cond, Terms);
3727
3728 // Determine which term failed.
3729 Expr *FailedCond = nullptr;
3730 for (Expr *Term : Terms) {
3731 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3732
3733 // Literals are uninteresting.
3734 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3735 isa<IntegerLiteral>(TermAsWritten))
3736 continue;
3737
3738 // The initialization of the parameter from the argument is
3739 // a constant-evaluated context.
3742
3743 bool Succeeded;
3744 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3745 !Succeeded) {
3746 FailedCond = TermAsWritten;
3747 break;
3748 }
3749 }
3750 if (!FailedCond)
3751 FailedCond = Cond->IgnoreParenImpCasts();
3752
3753 std::string Description;
3754 {
3755 llvm::raw_string_ostream Out(Description);
3757 Policy.PrintAsCanonical = true;
3758 FailedBooleanConditionPrinterHelper Helper(Policy);
3759 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3760 }
3761 return { FailedCond, Description };
3762}
3763
3764static TemplateName
3766 const AssumedTemplateStorage *ATN,
3767 SourceLocation NameLoc) {
3768 // We assumed this undeclared identifier to be an (ADL-only) function
3769 // template name, but it was used in a context where a type was required.
3770 // Try to typo-correct it now.
3771 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3772 struct CandidateCallback : CorrectionCandidateCallback {
3773 bool ValidateCandidate(const TypoCorrection &TC) override {
3774 return TC.getCorrectionDecl() &&
3776 }
3777 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3778 return std::make_unique<CandidateCallback>(*this);
3779 }
3780 } FilterCCC;
3781
3782 TypoCorrection Corrected =
3783 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3784 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3785 if (Corrected && Corrected.getFoundDecl()) {
3786 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3787 << ATN->getDeclName());
3789 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3791 }
3792
3793 return TemplateName();
3794}
3795
3797 TemplateName Name,
3798 SourceLocation TemplateLoc,
3799 TemplateArgumentListInfo &TemplateArgs,
3800 Scope *Scope, bool ForNestedNameSpecifier) {
3801 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3802
3803 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3804 if (!Template) {
3805 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3806 Template = S->getParameterPack();
3807 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3808 Template = PI->getParameterPack();
3809 if (!Template)
3810 Template = PI->getPattern().getAsTemplateDecl();
3811 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3812 if (DTN->getName().getIdentifier())
3813 // When building a template-id where the template-name is dependent,
3814 // assume the template is a type template. Either our assumption is
3815 // correct, or the code is ill-formed and will be diagnosed when the
3816 // dependent name is substituted.
3817 return Context.getTemplateSpecializationType(Keyword, Name,
3818 TemplateArgs.arguments(),
3819 /*CanonicalArgs=*/{});
3820 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3822 *this, Scope, ATN, TemplateLoc);
3823 CorrectedName.isNull()) {
3824 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3825 return QualType();
3826 } else {
3827 Name = CorrectedName;
3828 Template = Name.getAsTemplateDecl();
3829 }
3830 }
3831 }
3832 if (!Template ||
3834 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3835 if (ForNestedNameSpecifier)
3836 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3837 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3838 else
3839 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3841 return QualType();
3842 }
3843
3844 // Check that the template argument list is well-formed for this
3845 // template.
3847 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3848 DefaultArgs, /*PartialTemplateArgs=*/false,
3849 CTAI,
3850 /*UpdateArgsWithConversions=*/true))
3851 return QualType();
3852
3853 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3854 // and there are no diagnsotics currently implemented for TemplateDecls,
3855 // so avoid doing it for now.
3856 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3857
3858 QualType CanonType;
3859
3861 // We might have a substituted template template parameter pack. If so,
3862 // build a template specialization type for it.
3864 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3865
3866 // C++0x [dcl.type.elab]p2:
3867 // If the identifier resolves to a typedef-name or the simple-template-id
3868 // resolves to an alias template specialization, the
3869 // elaborated-type-specifier is ill-formed.
3872 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3875 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3876 }
3877
3878 // Find the canonical type for this type alias template specialization.
3879 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3880
3881 // Diagnose uses of the pattern of this template.
3882 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3883 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3884
3885 if (Pattern->isInvalidDecl())
3886 return QualType();
3887
3888 // Only substitute for the innermost template argument list.
3889 MultiLevelTemplateArgumentList TemplateArgLists;
3891 /*Final=*/true);
3892 TemplateArgLists.addOuterRetainedLevels(
3893 AliasTemplate->getTemplateParameters()->getDepth());
3894
3896
3897 // FIXME: The TemplateArgs passed here are not used for the context note,
3898 // nor they should, because this note will be pointing to the specialization
3899 // anyway. These arguments are needed for a hack for instantiating lambdas
3900 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3901 // arguments will be used for collating the template arguments needed to
3902 // instantiate the lambda.
3903 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3904 /*Entity=*/AliasTemplate,
3905 /*TemplateArgs=*/CTAI.SugaredConverted);
3906 if (Inst.isInvalid())
3907 return QualType();
3908
3909 std::optional<ContextRAII> SavedContext;
3910 if (!AliasTemplate->getDeclContext()->isFileContext())
3911 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3912
3913 // FIXME: Preserve the pattern's type source information during substitution
3914 // while respecting underlying type changes made by mode attributes.
3915 CanonType =
3916 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3917 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3918 if (CanonType.isNull()) {
3919 // If this was enable_if and we failed to find the nested type
3920 // within enable_if in a SFINAE context, dig out the specific
3921 // enable_if condition that failed and present that instead.
3923 if (SFINAETrap *Trap = getSFINAEContext();
3924 TemplateDeductionInfo *DeductionInfo =
3925 Trap ? Trap->getDeductionInfo() : nullptr) {
3926 if (DeductionInfo->hasSFINAEDiagnostic() &&
3927 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3928 diag::err_typename_nested_not_found_enable_if &&
3929 TemplateArgs[0].getArgument().getKind() ==
3931 Expr *FailedCond;
3932 std::string FailedDescription;
3933 std::tie(FailedCond, FailedDescription) =
3934 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3935
3936 // Remove the old SFINAE diagnostic.
3937 PartialDiagnosticAt OldDiag =
3939 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3940
3941 // Add a new SFINAE diagnostic specifying which condition
3942 // failed.
3943 DeductionInfo->addSFINAEDiagnostic(
3944 OldDiag.first,
3945 PDiag(diag::err_typename_nested_not_found_requirement)
3946 << FailedDescription << FailedCond->getSourceRange());
3947 }
3948 }
3949 }
3950
3951 return QualType();
3952 }
3953 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3954 CanonType = checkBuiltinTemplateIdType(
3955 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3956 } else if (Name.isDependent() ||
3957 TemplateSpecializationType::anyDependentTemplateArguments(
3958 TemplateArgs, CTAI.CanonicalConverted)) {
3959 // This class template specialization is a dependent
3960 // type. Therefore, its canonical type is another class template
3961 // specialization type that contains all of the converted
3962 // arguments in canonical form. This ensures that, e.g., A<T> and
3963 // A<T, T> have identical types when A is declared as:
3964 //
3965 // template<typename T, typename U = T> struct A;
3966 CanonType = Context.getCanonicalTemplateSpecializationType(
3968 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3969 CTAI.CanonicalConverted);
3970 assert(CanonType->isCanonicalUnqualified());
3971
3972 // This might work out to be a current instantiation, in which
3973 // case the canonical type needs to be the InjectedClassNameType.
3974 //
3975 // TODO: in theory this could be a simple hashtable lookup; most
3976 // changes to CurContext don't change the set of current
3977 // instantiations.
3979 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3980 // If we get out to a namespace, we're done.
3981 if (Ctx->isFileContext()) break;
3982
3983 // If this isn't a record, keep looking.
3984 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3985 if (!Record) continue;
3986
3987 // Look for one of the two cases with InjectedClassNameTypes
3988 // and check whether it's the same template.
3990 !Record->getDescribedClassTemplate())
3991 continue;
3992
3993 // Fetch the injected class name type and check whether its
3994 // injected type is equal to the type we just built.
3995 CanQualType ICNT = Context.getCanonicalTagType(Record);
3996 CanQualType Injected =
3997 Record->getCanonicalTemplateSpecializationType(Context);
3998
3999 if (CanonType != Injected)
4000 continue;
4001
4002 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
4003 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
4004
4005 // If so, the canonical type of this TST is the injected
4006 // class name type of the record we just found.
4007 CanonType = ICNT;
4008 break;
4009 }
4010 }
4011 } else if (ClassTemplateDecl *ClassTemplate =
4012 dyn_cast<ClassTemplateDecl>(Template)) {
4013 // Find the class template specialization declaration that
4014 // corresponds to these arguments.
4015 llvm::FoldingSetInsertToken InsertToken;
4017 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4018 if (!Decl) {
4019 // This is the first time we have referenced this class template
4020 // specialization. Create the canonical declaration and add it to
4021 // the set of specializations.
4023 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4024 ClassTemplate->getDeclContext(),
4025 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4026 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
4027 CTAI.StrictPackMatch, nullptr);
4028 ClassTemplate->AddSpecialization(Decl, InsertToken);
4029 if (ClassTemplate->isOutOfLine())
4030 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4031 }
4032
4033 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4034 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4035 NonSFINAEContext _(*this);
4036 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4037 if (!Inst.isInvalid()) {
4039 CTAI.CanonicalConverted,
4040 /*Final=*/false);
4041 InstantiateAttrsForDecl(TemplateArgLists,
4042 ClassTemplate->getTemplatedDecl(), Decl);
4043 }
4044 }
4045
4046 // Diagnose uses of this specialization.
4047 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4048 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4049
4050 CanonType = Context.getCanonicalTagType(Decl);
4051 assert(isa<RecordType>(CanonType) &&
4052 "type of non-dependent specialization is not a RecordType");
4053 } else {
4054 llvm_unreachable("Unhandled template kind");
4055 }
4056
4057 // Build the fully-sugared type for this class template
4058 // specialization, which refers back to the class template
4059 // specialization we created or found.
4060 return Context.getTemplateSpecializationType(
4061 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4062 CanonType);
4063}
4064
4066 TemplateNameKind &TNK,
4067 SourceLocation NameLoc,
4068 IdentifierInfo *&II) {
4069 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4070
4071 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4072 assert(ATN && "not an assumed template name");
4073 II = ATN->getDeclName().getAsIdentifierInfo();
4074
4075 if (TemplateName Name =
4076 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4077 !Name.isNull()) {
4078 // Resolved to a type template name.
4079 ParsedName = TemplateTy::make(Name);
4080 TNK = TNK_Type_template;
4081 }
4082}
4083
4085 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4086 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4087 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4088 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4089 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4090 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4091 ImplicitTypenameContext AllowImplicitTypename) {
4092 if (SS.isInvalid())
4093 return true;
4094
4095 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4096 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4097
4098 // C++ [temp.res]p3:
4099 // A qualified-id that refers to a type and in which the
4100 // nested-name-specifier depends on a template-parameter (14.6.2)
4101 // shall be prefixed by the keyword typename to indicate that the
4102 // qualified-id denotes a type, forming an
4103 // elaborated-type-specifier (7.1.5.3).
4104 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4105 // C++2a relaxes some of those restrictions in [temp.res]p5.
4106 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4107 SS.getScopeRep(), TemplateII);
4109 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4110 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4111 << NNS;
4112 if (!getLangOpts().CPlusPlus20)
4113 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4114 } else
4115 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4116
4117 // FIXME: This is not quite correct recovery as we don't transform SS
4118 // into the corresponding dependent form (and we don't diagnose missing
4119 // 'template' keywords within SS as a result).
4120 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4121 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4122 TemplateArgsIn, RAngleLoc);
4123 }
4124
4125 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4126 // it's not actually allowed to be used as a type in most cases. Because
4127 // we annotate it before we know whether it's valid, we have to check for
4128 // this case here.
4129 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4130 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4131 Diag(TemplateIILoc,
4132 TemplateKWLoc.isInvalid()
4133 ? diag::err_out_of_line_qualified_id_type_names_constructor
4134 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4135 << TemplateII << 0 /*injected-class-name used as template name*/
4136 << 1 /*if any keyword was present, it was 'template'*/;
4137 }
4138 }
4139
4140 // Translate the parser's template argument list in our AST format.
4141 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4142 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4143
4145 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4146 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4147 if (SpecTy.isNull())
4148 return true;
4149
4150 // Build type-source information.
4151 TypeLocBuilder TLB;
4152 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4153 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4154 TemplateIILoc, TemplateArgs);
4155 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4156}
4157
4159 TypeSpecifierType TagSpec,
4160 SourceLocation TagLoc,
4161 CXXScopeSpec &SS,
4162 SourceLocation TemplateKWLoc,
4163 TemplateTy TemplateD,
4164 SourceLocation TemplateLoc,
4165 SourceLocation LAngleLoc,
4166 ASTTemplateArgsPtr TemplateArgsIn,
4167 SourceLocation RAngleLoc) {
4168 if (SS.isInvalid())
4169 return TypeResult(true);
4170
4171 // Translate the parser's template argument list in our AST format.
4172 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4173 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4174
4175 // Determine the tag kind
4179
4181 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4182 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4183 if (Result.isNull())
4184 return TypeResult(true);
4185
4186 // Check the tag kind
4187 if (const RecordType *RT = Result->getAs<RecordType>()) {
4188 RecordDecl *D = RT->getDecl();
4189
4190 IdentifierInfo *Id = D->getIdentifier();
4191 assert(Id && "templated class must have an identifier");
4192
4194 TagLoc, Id)) {
4195 Diag(TagLoc, diag::err_use_with_wrong_tag)
4196 << Result
4198 Diag(D->getLocation(), diag::note_previous_use);
4199 }
4200 }
4201
4202 // Provide source-location information for the template specialization.
4203 TypeLocBuilder TLB;
4205 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4206 TemplateArgs);
4208}
4209
4210static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4211 NamedDecl *PrevDecl,
4212 SourceLocation Loc,
4214
4216
4218 unsigned Depth,
4219 unsigned Index) {
4220 switch (Arg.getKind()) {
4228 return false;
4229
4231 QualType Type = Arg.getAsType();
4232 const TemplateTypeParmType *TPT =
4233 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4234 return TPT && !Type.hasQualifiers() &&
4235 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4236 }
4237
4239 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4240 if (!DRE || !DRE->getDecl())
4241 return false;
4242 const NonTypeTemplateParmDecl *NTTP =
4243 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4244 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4245 }
4246
4248 const TemplateTemplateParmDecl *TTP =
4249 dyn_cast_or_null<TemplateTemplateParmDecl>(
4251 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4252 }
4253 llvm_unreachable("unexpected kind of template argument");
4254}
4255
4257 TemplateParameterList *SpecParams,
4259 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4260 return false;
4261
4262 unsigned Depth = Params->getDepth();
4263
4264 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4265 TemplateArgument Arg = Args[I];
4266
4267 // If the parameter is a pack expansion, the argument must be a pack
4268 // whose only element is a pack expansion.
4269 if (Params->getParam(I)->isParameterPack()) {
4270 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4271 !Arg.pack_begin()->isPackExpansion())
4272 return false;
4273 Arg = Arg.pack_begin()->getPackExpansionPattern();
4274 }
4275
4276 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4277 return false;
4278
4279 // For NTTPs further specialization is allowed via deduced types, so
4280 // we need to make sure to only reject here if primary template and
4281 // specialization use the same type for the NTTP.
4282 if (auto *SpecNTTP =
4283 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4284 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4285 if (!NTTP || NTTP->getType().getCanonicalType() !=
4286 SpecNTTP->getType().getCanonicalType())
4287 return false;
4288 }
4289 }
4290
4291 return true;
4292}
4293
4294template<typename PartialSpecDecl>
4295static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4296 if (Partial->getDeclContext()->isDependentContext())
4297 return;
4298
4299 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4300 // for non-substitution-failure issues?
4301 TemplateDeductionInfo Info(Partial->getLocation());
4302 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4303 return;
4304
4305 auto *Template = Partial->getSpecializedTemplate();
4306 S.Diag(Partial->getLocation(),
4307 diag::ext_partial_spec_not_more_specialized_than_primary)
4309
4310 if (Info.hasSFINAEDiagnostic()) {
4314 SmallString<128> SFINAEArgString;
4315 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4316 S.Diag(Diag.first,
4317 diag::note_partial_spec_not_more_specialized_than_primary)
4318 << SFINAEArgString;
4319 }
4320
4322 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4323 Template->getAssociatedConstraints(TemplateAC);
4324 Partial->getAssociatedConstraints(PartialAC);
4326 TemplateAC);
4327}
4328
4329static void
4331 const llvm::SmallBitVector &DeducibleParams) {
4332 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4333 if (!DeducibleParams[I]) {
4334 NamedDecl *Param = TemplateParams->getParam(I);
4335 if (Param->getDeclName())
4336 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4337 << Param->getDeclName();
4338 else
4339 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4340 << "(anonymous)";
4341 }
4342 }
4343}
4344
4345
4346template<typename PartialSpecDecl>
4348 PartialSpecDecl *Partial) {
4349 // C++1z [temp.class.spec]p8: (DR1495)
4350 // - The specialization shall be more specialized than the primary
4351 // template (14.5.5.2).
4353
4354 // C++ [temp.class.spec]p8: (DR1315)
4355 // - Each template-parameter shall appear at least once in the
4356 // template-id outside a non-deduced context.
4357 // C++1z [temp.class.spec.match]p3 (P0127R2)
4358 // If the template arguments of a partial specialization cannot be
4359 // deduced because of the structure of its template-parameter-list
4360 // and the template-id, the program is ill-formed.
4361 auto *TemplateParams = Partial->getTemplateParameters();
4362 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4363 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4364 TemplateParams->getDepth(), DeducibleParams);
4365
4366 if (!DeducibleParams.all()) {
4367 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4368 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4370 << (NumNonDeducible > 1)
4371 << SourceRange(Partial->getLocation(),
4372 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4373 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4374 }
4375}
4376
4381
4386
4388 // C++1z [temp.param]p11:
4389 // A template parameter of a deduction guide template that does not have a
4390 // default-argument shall be deducible from the parameter-type-list of the
4391 // deduction guide template.
4392 auto *TemplateParams = TD->getTemplateParameters();
4393 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4394 MarkDeducedTemplateParameters(TD, DeducibleParams);
4395 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4396 // A parameter pack is deducible (to an empty pack).
4397 auto *Param = TemplateParams->getParam(I);
4398 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4399 DeducibleParams[I] = true;
4400 }
4401
4402 if (!DeducibleParams.all()) {
4403 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4404 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4405 << (NumNonDeducible > 1);
4406 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4407 }
4408}
4409
4412 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4414 // D must be variable template id.
4416 "Variable template specialization is declared with a template id.");
4417
4418 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4419 TemplateArgumentListInfo TemplateArgs =
4420 makeTemplateArgumentListInfo(*this, *TemplateId);
4421 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4422 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4423 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4424
4425 TemplateName Name = TemplateId->Template.get();
4426
4427 // The template-id must name a variable template.
4429 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4430 if (!VarTemplate) {
4431 NamedDecl *FnTemplate;
4432 if (auto *OTS = Name.getAsOverloadedTemplate())
4433 FnTemplate = *OTS->begin();
4434 else
4435 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4436 if (FnTemplate)
4437 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4438 << FnTemplate->getDeclName();
4439 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4441 }
4442
4443 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4444 auto Message = DSA->getMessage();
4445 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4446 << VarTemplate << !Message.empty() << Message;
4447 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4448 }
4449
4450 // Check for unexpanded parameter packs in any of the template arguments.
4451 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4452 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4456 return true;
4457
4458 // Check that the template argument list is well-formed for this
4459 // template.
4461 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4462 /*DefaultArgs=*/{},
4463 /*PartialTemplateArgs=*/false, CTAI,
4464 /*UpdateArgsWithConversions=*/true))
4465 return true;
4466
4467 // Find the variable template (partial) specialization declaration that
4468 // corresponds to these arguments.
4471 TemplateArgs.size(),
4472 CTAI.CanonicalConverted))
4473 return true;
4474
4475 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4476 // we also do them during instantiation.
4477 if (!Name.isDependent() &&
4478 !TemplateSpecializationType::anyDependentTemplateArguments(
4479 TemplateArgs, CTAI.CanonicalConverted)) {
4480 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4481 << VarTemplate->getDeclName();
4483 }
4484
4485 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4486 TemplateParams, CTAI.CanonicalConverted) &&
4487 (!Context.getLangOpts().CPlusPlus20 ||
4488 !TemplateParams->hasAssociatedConstraints())) {
4489 // C++ [temp.class.spec]p9b3:
4490 //
4491 // -- The argument list of the specialization shall not be identical
4492 // to the implicit argument list of the primary template.
4493 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4494 << /*variable template*/ 1
4495 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4496 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4497 // FIXME: Recover from this by treating the declaration as a
4498 // redeclaration of the primary template.
4499 return true;
4500 }
4501 }
4502
4503 llvm::FoldingSetInsertToken InsertToken;
4504 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4505
4507 PrevDecl = VarTemplate->findPartialSpecialization(
4508 CTAI.CanonicalConverted, TemplateParams, InsertToken);
4509 else
4510 PrevDecl =
4511 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4512
4514
4515 // Check whether we can declare a variable template specialization in
4516 // the current scope.
4517 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4518 TemplateNameLoc,
4520 return true;
4521
4522 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4523 // Since the only prior variable template specialization with these
4524 // arguments was referenced but not declared, reuse that
4525 // declaration node as our own, updating its source location and
4526 // the list of outer template parameters to reflect our new declaration.
4527 Specialization = PrevDecl;
4528 Specialization->setLocation(TemplateNameLoc);
4529 PrevDecl = nullptr;
4530 } else if (IsPartialSpecialization) {
4531 // Create a new class template partial specialization declaration node.
4533 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4536 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4537 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4538 SC, CTAI.CanonicalConverted);
4539 Partial->setTemplateArgsAsWritten(TemplateArgs);
4540
4541 if (!PrevPartial)
4542 VarTemplate->AddPartialSpecialization(Partial, InsertToken);
4543 Specialization = Partial;
4544
4546 } else {
4547 // Create a new class template specialization declaration node for
4548 // this explicit specialization or friend declaration.
4550 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4551 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4552 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4553
4554 if (!PrevDecl)
4555 VarTemplate->AddSpecialization(Specialization, InsertToken);
4556 }
4557
4558 // C++ [temp.expl.spec]p6:
4559 // If a template, a member template or the member of a class template is
4560 // explicitly specialized then that specialization shall be declared
4561 // before the first use of that specialization that would cause an implicit
4562 // instantiation to take place, in every translation unit in which such a
4563 // use occurs; no diagnostic is required.
4564 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4565 bool Okay = false;
4566 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4567 // Is there any previous explicit specialization declaration?
4569 Okay = true;
4570 break;
4571 }
4572 }
4573
4574 if (!Okay) {
4575 SourceRange Range(TemplateNameLoc, RAngleLoc);
4576 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4577 << Name << Range;
4578
4579 Diag(PrevDecl->getPointOfInstantiation(),
4580 diag::note_instantiation_required_here)
4581 << (PrevDecl->getTemplateSpecializationKind() !=
4583 return true;
4584 }
4585 }
4586
4587 Specialization->setLexicalDeclContext(CurContext);
4588
4589 // Add the specialization into its lexical context, so that it can
4590 // be seen when iterating through the list of declarations in that
4591 // context. However, specializations are not found by name lookup.
4592 CurContext->addDecl(Specialization);
4593
4594 // Note that this is an explicit specialization.
4595 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4596
4597 Previous.clear();
4598 if (PrevDecl)
4599 Previous.addDecl(PrevDecl);
4600 else if (Specialization->isStaticDataMember() &&
4601 Specialization->isOutOfLine())
4602 Specialization->setAccess(VarTemplate->getAccess());
4603
4604 return Specialization;
4605}
4606
4607namespace {
4608/// A partial specialization whose template arguments have matched
4609/// a given template-id.
4610struct PartialSpecMatchResult {
4613};
4614
4615// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4616// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4617static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4618 if (Var->getName() != "format_kind" ||
4619 !Var->getDeclContext()->isStdNamespace())
4620 return false;
4621
4622 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4623 // release in which users can access std::format_kind.
4624 // We can use 20250520 as the final date, see the following commits.
4625 // GCC releases/gcc-15 branch:
4626 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4627 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4628 // GCC master branch:
4629 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4630 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4631 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4632}
4633} // end anonymous namespace
4634
4637 SourceLocation TemplateNameLoc,
4638 const TemplateArgumentListInfo &TemplateArgs,
4639 bool SetWrittenArgs) {
4640 assert(Template && "A variable template id without template?");
4641
4642 // Check that the template argument list is well-formed for this template.
4645 Template, TemplateNameLoc,
4646 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4647 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4648 /*UpdateArgsWithConversions=*/true))
4649 return true;
4650
4651 // Produce a placeholder value if the specialization is dependent.
4652 if (Template->getDeclContext()->isDependentContext() ||
4653 TemplateSpecializationType::anyDependentTemplateArguments(
4654 TemplateArgs, CTAI.CanonicalConverted)) {
4655 if (ParsingInitForAutoVars.empty())
4656 return DeclResult();
4657
4658 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4659 const TemplateArgument &Arg2) {
4660 return Context.isSameTemplateArgument(Arg1, Arg2);
4661 };
4662
4663 if (VarDecl *Var = Template->getTemplatedDecl();
4664 ParsingInitForAutoVars.count(Var) &&
4665 // See comments on this function definition
4666 !IsLibstdcxxStdFormatKind(PP, Var) &&
4667 llvm::equal(
4668 CTAI.CanonicalConverted,
4669 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4670 IsSameTemplateArg)) {
4671 Diag(TemplateNameLoc,
4672 diag::err_auto_variable_cannot_appear_in_own_initializer)
4673 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4674 return true;
4675 }
4676
4678 Template->getPartialSpecializations(PartialSpecs);
4679 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4680 if (ParsingInitForAutoVars.count(Partial) &&
4681 llvm::equal(CTAI.CanonicalConverted,
4682 Partial->getTemplateArgs().asArray(),
4683 IsSameTemplateArg)) {
4684 Diag(TemplateNameLoc,
4685 diag::err_auto_variable_cannot_appear_in_own_initializer)
4686 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4687 << Partial->getType();
4688 return true;
4689 }
4690
4691 return DeclResult();
4692 }
4693
4694 // Find the variable template specialization declaration that
4695 // corresponds to these arguments.
4696 llvm::FoldingSetInsertToken InsertToken;
4698 Template->findSpecialization(CTAI.CanonicalConverted, InsertToken)) {
4699 checkSpecializationReachability(TemplateNameLoc, Spec);
4700 if (Spec->getType()->isUndeducedType()) {
4701 if (ParsingInitForAutoVars.count(Spec))
4702 Diag(TemplateNameLoc,
4703 diag::err_auto_variable_cannot_appear_in_own_initializer)
4704 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4705 << Spec->getType();
4706 else
4707 // We are substituting the initializer of this variable template
4708 // specialization.
4709 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4710 << Spec << Spec->getType();
4711
4712 return true;
4713 }
4714 // If we already have a variable template specialization, return it.
4715 return Spec;
4716 }
4717
4718 // This is the first time we have referenced this variable template
4719 // specialization. Create the canonical declaration and add it to
4720 // the set of specializations, based on the closest partial specialization
4721 // that it represents. That is,
4722 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4723 const TemplateArgumentList *PartialSpecArgs = nullptr;
4724 bool AmbiguousPartialSpec = false;
4725 typedef PartialSpecMatchResult MatchResult;
4727 SourceLocation PointOfInstantiation = TemplateNameLoc;
4728 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4729 /*ForTakingAddress=*/false);
4730
4731 // 1. Attempt to find the closest partial specialization that this
4732 // specializes, if any.
4733 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4734 // Perhaps better after unification of DeduceTemplateArguments() and
4735 // getMoreSpecializedPartialSpecialization().
4737 Template->getPartialSpecializations(PartialSpecs);
4738
4739 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4740 // C++ [temp.spec.partial.member]p2:
4741 // If the primary member template is explicitly specialized for a given
4742 // (implicit) specialization of the enclosing class template, the partial
4743 // specializations of the member template are ignored for this
4744 // specialization of the enclosing class template. If a partial
4745 // specialization of the member template is explicitly specialized for a
4746 // given (implicit) specialization of the enclosing class template, the
4747 // primary member template and its other partial specializations are still
4748 // considered for this specialization of the enclosing class template.
4749 if (Template->isMemberSpecialization() &&
4750 !Partial->isMemberSpecialization())
4751 continue;
4752
4753 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4754
4756 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4758 // Store the failed-deduction information for use in diagnostics, later.
4759 // TODO: Actually use the failed-deduction info?
4760 FailedCandidates.addCandidate().set(
4763 (void)Result;
4764 } else {
4765 Matched.push_back(PartialSpecMatchResult());
4766 Matched.back().Partial = cast<VarTemplatePartialSpecializationDecl>(
4767 Partial->getCanonicalDecl());
4768 Matched.back().Args = Info.takeSugared();
4769 }
4770 }
4771
4772 if (Matched.size() >= 1) {
4773 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4774 if (Matched.size() == 1) {
4775 // -- If exactly one matching specialization is found, the
4776 // instantiation is generated from that specialization.
4777 // We don't need to do anything for this.
4778 } else {
4779 // -- If more than one matching specialization is found, the
4780 // partial order rules (14.5.4.2) are used to determine
4781 // whether one of the specializations is more specialized
4782 // than the others. If none of the specializations is more
4783 // specialized than all of the other matching
4784 // specializations, then the use of the variable template is
4785 // ambiguous and the program is ill-formed.
4786 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4787 PEnd = Matched.end();
4788 P != PEnd; ++P) {
4789 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4790 PointOfInstantiation) ==
4791 P->Partial)
4792 Best = P;
4793 }
4794
4795 // Determine if the best partial specialization is more specialized than
4796 // the others.
4797 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4798 PEnd = Matched.end();
4799 P != PEnd; ++P) {
4801 P->Partial, Best->Partial,
4802 PointOfInstantiation) != Best->Partial) {
4803 AmbiguousPartialSpec = true;
4804 break;
4805 }
4806 }
4807 }
4808
4809 // Instantiate using the best variable template partial specialization.
4810 InstantiationPattern = Best->Partial;
4811 PartialSpecArgs = Best->Args;
4812 } else {
4813 // -- If no match is found, the instantiation is generated
4814 // from the primary template.
4815 // InstantiationPattern = Template->getTemplatedDecl();
4816 }
4817
4818 // 2. Create the canonical declaration.
4819 // Note that we do not instantiate a definition until we see an odr-use
4820 // in DoMarkVarDeclReferenced().
4821 // FIXME: LateAttrs et al.?
4822 if (AmbiguousPartialSpec) {
4823 // Partial ordering did not produce a clear winner. Complain.
4824 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4825 << Template;
4826 // Print the matching partial specializations.
4827 for (MatchResult P : Matched)
4828 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4829 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4830 *P.Args);
4831 return true;
4832 }
4833
4835 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4836 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4837 if (!Decl)
4838 return true;
4839 if (SetWrittenArgs)
4840 Decl->setTemplateArgsAsWritten(TemplateArgs);
4841
4843 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4844 Decl->setInstantiationOf(D, PartialSpecArgs);
4845
4846 checkSpecializationReachability(TemplateNameLoc, Decl);
4847
4848 assert(Decl && "No variable template specialization?");
4849 return Decl;
4850}
4851
4853 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4854 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4855 const TemplateArgumentListInfo *TemplateArgs) {
4856
4857 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4858 *TemplateArgs, /*SetWrittenArgs=*/false);
4859 if (Decl.isInvalid())
4860 return ExprError();
4861
4862 if (!Decl.get())
4863 return ExprResult();
4864
4865 VarDecl *Var = cast<VarDecl>(Decl.get());
4868 NameInfo.getLoc());
4869
4870 // Build an ordinary singleton decl ref.
4871 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4872}
4873
4875 const DeclarationNameInfo &NameInfo, TemplateName Template,
4876 const TemplateArgumentListInfo *TemplateArgs) {
4878 Template.getAsTemplateTemplateParmDecl();
4879 assert(Parameter && "A variable template id without template?");
4880
4881 if (Parameter->templateParameterKind() !=
4883 Parameter->templateParameterKind() !=
4885 return ExprResult();
4886
4887 // Check that the template argument list is well-formed for this template.
4890 Parameter, /*Template kw loc=*/{},
4891 // FIXME: TemplateArgs will not be modified because
4892 // UpdateArgsWithConversions is false, however, we should
4893 // CheckTemplateArgumentList to be const-correct.
4894 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4895 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4896 /*UpdateArgsWithConversions=*/false))
4897 return true;
4898
4900 *TemplateArgs);
4901}
4902
4904 SourceLocation Loc) {
4905 Diag(Loc, diag::err_template_missing_args)
4906 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4907 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4908 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4909 }
4910}
4911
4913 bool TemplateKeyword,
4914 TemplateDecl *TD,
4915 SourceLocation Loc) {
4916 TemplateName Name = Context.getQualifiedTemplateName(
4917 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4919}
4920
4922 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4923 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4924 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4925 bool DoCheckConstraintSatisfaction) {
4926 assert(NamedConcept && "A concept template id without a template?");
4927
4928 if (NamedConcept->isInvalidDecl())
4929 return ExprError();
4930
4933 NamedConcept, ConceptNameInfo.getLoc(),
4934 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4935 /*DefaultArgs=*/{},
4936 /*PartialTemplateArgs=*/false, CTAI,
4937 /*UpdateArgsWithConversions=*/false))
4938 return ExprError();
4939
4940 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4941
4942 // There's a bug with CTAI.CanonicalConverted.
4943 // If the template argument contains a DependentDecltypeType that includes a
4944 // TypeAliasType, and the same written type had occurred previously in the
4945 // source, then the DependentDecltypeType would be canonicalized to that
4946 // previous type which would mess up the substitution.
4947 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4949 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4950 CTAI.SugaredConverted);
4951 ConstraintSatisfaction Satisfaction;
4952 bool AreArgsDependent =
4953 TemplateSpecializationType::anyDependentTemplateArguments(
4954 *TemplateArgs, CTAI.SugaredConverted);
4955 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4956 /*Final=*/false);
4958 Context,
4960 TemplateKWLoc, ConceptNameInfo, FoundDecl, TemplateName(NamedConcept),
4962
4963 bool Error = false;
4964 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4965 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4966 DoCheckConstraintSatisfaction) {
4967
4969
4972
4974 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4975 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4976 TemplateArgs->getRAngleLoc()),
4977 Satisfaction, CL);
4978 Satisfaction.ContainsErrors = Error;
4979 }
4980
4981 if (Error)
4982 return ExprError();
4983
4985 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4986}
4987
4989 SourceLocation TemplateKWLoc,
4990 LookupResult &R,
4991 bool RequiresADL,
4992 const TemplateArgumentListInfo *TemplateArgs) {
4993 // FIXME: Can we do any checking at this point? I guess we could check the
4994 // template arguments that we have against the template name, if the template
4995 // name refers to a single template. That's not a terribly common case,
4996 // though.
4997 // foo<int> could identify a single function unambiguously
4998 // This approach does NOT work, since f<int>(1);
4999 // gets resolved prior to resorting to overload resolution
5000 // i.e., template<class T> void f(double);
5001 // vs template<class T, class U> void f(U);
5002
5003 // These should be filtered out by our callers.
5004 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5005
5006 // Non-function templates require a template argument list.
5007 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5008 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5010 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
5011 return ExprError();
5012 }
5013 }
5014 bool KnownDependent = false;
5015 // In C++1y, check variable template ids.
5016 if (R.getAsSingle<VarTemplateDecl>()) {
5018 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
5019 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5020 if (Res.isInvalid() || Res.isUsable())
5021 return Res;
5022 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
5023 KnownDependent = true;
5024 }
5025
5026 // We don't want lookup warnings at this point.
5027 R.suppressDiagnostics();
5028
5029 if (R.getAsSingle<ConceptDecl>()) {
5030 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5031 R.getRepresentativeDecl(),
5032 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5033 }
5034
5035 // Check variable template ids (C++17) and concept template parameters
5036 // (C++26).
5038 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5039 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5040 assert(TemplateKWLoc.isInvalid() &&
5041 "template keyword in front of a template parameter?");
5043 R.getLookupNameInfo(),
5044 TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5045 }
5046
5047 // Function templates
5049 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5050 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5051 R.begin(), R.end(), KnownDependent,
5052 /*KnownInstantiationDependent=*/false);
5053 // Model the templates with UnresolvedTemplateTy. The expression should then
5054 // either be transformed in an instantiation or be diagnosed in
5055 // CheckPlaceholderExpr.
5056 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5057 !R.getFoundDecl()->getAsFunction())
5058 ULE->setType(Context.UnresolvedTemplateTy);
5059
5060 return ULE;
5061}
5062
5064 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5065 const DeclarationNameInfo &NameInfo,
5066 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5067 assert(TemplateArgs || TemplateKWLoc.isValid());
5068
5069 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5070 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5071 /*EnteringContext=*/false, TemplateKWLoc))
5072 return ExprError();
5073
5074 if (R.isAmbiguous())
5075 return ExprError();
5076
5077 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5078 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5079
5080 if (R.empty()) {
5082 Diag(NameInfo.getLoc(), diag::err_no_member)
5083 << NameInfo.getName() << DC << SS.getRange();
5084 return ExprError();
5085 }
5086
5087 // If necessary, build an implicit class member access.
5088 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5089 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5090 /*S=*/nullptr);
5091
5092 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5093}
5094
5096 CXXScopeSpec &SS,
5097 SourceLocation TemplateKWLoc,
5098 const UnqualifiedId &Name,
5099 ParsedType ObjectType,
5100 bool EnteringContext,
5102 bool AllowInjectedClassName) {
5103 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5104 DiagCompat(TemplateKWLoc, diag_compat::template_outside_of_template)
5105 << FixItHint::CreateRemoval(TemplateKWLoc);
5106
5107 if (SS.isInvalid())
5108 return TNK_Non_template;
5109
5110 // Figure out where isTemplateName is going to look.
5111 DeclContext *LookupCtx = nullptr;
5112 if (SS.isNotEmpty())
5113 LookupCtx = computeDeclContext(SS, EnteringContext);
5114 else if (ObjectType)
5115 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5116
5117 // C++0x [temp.names]p5:
5118 // If a name prefixed by the keyword template is not the name of
5119 // a template, the program is ill-formed. [Note: the keyword
5120 // template may not be applied to non-template members of class
5121 // templates. -end note ] [ Note: as is the case with the
5122 // typename prefix, the template prefix is allowed in cases
5123 // where it is not strictly necessary; i.e., when the
5124 // nested-name-specifier or the expression on the left of the ->
5125 // or . is not dependent on a template-parameter, or the use
5126 // does not appear in the scope of a template. -end note]
5127 //
5128 // Note: C++03 was more strict here, because it banned the use of
5129 // the "template" keyword prior to a template-name that was not a
5130 // dependent name. C++ DR468 relaxed this requirement (the
5131 // "template" keyword is now permitted). We follow the C++0x
5132 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5133 bool MemberOfUnknownSpecialization;
5134 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5135 ObjectType, EnteringContext, Result,
5136 MemberOfUnknownSpecialization);
5137 if (TNK != TNK_Non_template) {
5138 // We resolved this to a (non-dependent) template name. Return it.
5139 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5140 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5142 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5143 // C++14 [class.qual]p2:
5144 // In a lookup in which function names are not ignored and the
5145 // nested-name-specifier nominates a class C, if the name specified
5146 // [...] is the injected-class-name of C, [...] the name is instead
5147 // considered to name the constructor
5148 //
5149 // We don't get here if naming the constructor would be valid, so we
5150 // just reject immediately and recover by treating the
5151 // injected-class-name as naming the template.
5152 Diag(Name.getBeginLoc(),
5153 diag::ext_out_of_line_qualified_id_type_names_constructor)
5154 << Name.Identifier
5155 << 0 /*injected-class-name used as template name*/
5156 << TemplateKWLoc.isValid();
5157 }
5158 return TNK;
5159 }
5160
5161 if (!MemberOfUnknownSpecialization) {
5162 // Didn't find a template name, and the lookup wasn't dependent.
5163 // Do the lookup again to determine if this is a "nothing found" case or
5164 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5165 // need to do this.
5167 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5169 // Tell LookupTemplateName that we require a template so that it diagnoses
5170 // cases where it finds a non-template.
5171 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5172 ? RequiredTemplateKind(TemplateKWLoc)
5174 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5175 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5176 !R.isAmbiguous()) {
5177 if (LookupCtx)
5178 Diag(Name.getBeginLoc(), diag::err_no_member)
5179 << DNI.getName() << LookupCtx << SS.getRange();
5180 else
5181 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5182 << DNI.getName() << SS.getRange();
5183 }
5184 return TNK_Non_template;
5185 }
5186
5187 NestedNameSpecifier Qualifier = SS.getScopeRep();
5188
5189 switch (Name.getKind()) {
5191 Result = TemplateTy::make(Context.getDependentTemplateName(
5192 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5194
5196 Result = TemplateTy::make(Context.getDependentTemplateName(
5197 {Qualifier, Name.OperatorFunctionId.Operator,
5198 TemplateKWLoc.isValid()}));
5199 return TNK_Function_template;
5200
5202 // This is a kind of template name, but can never occur in a dependent
5203 // scope (literal operators can only be declared at namespace scope).
5204 break;
5205
5206 default:
5207 break;
5208 }
5209
5210 // This name cannot possibly name a dependent template. Diagnose this now
5211 // rather than building a dependent template name that can never be valid.
5212 Diag(Name.getBeginLoc(),
5213 diag::err_template_kw_refers_to_dependent_non_template)
5215 << TemplateKWLoc.isValid() << TemplateKWLoc;
5216 return TNK_Non_template;
5217}
5218
5221 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5222 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5223 const TemplateArgument &Arg = AL.getArgument();
5225 TypeSourceInfo *TSI = nullptr;
5226
5227 // Check template type parameter.
5228 switch(Arg.getKind()) {
5230 // C++ [temp.arg.type]p1:
5231 // A template-argument for a template-parameter which is a
5232 // type shall be a type-id.
5233 ArgType = Arg.getAsType();
5234 TSI = AL.getTypeSourceInfo();
5235 break;
5238 // We have a template type parameter but the template argument
5239 // is a template without any arguments.
5240 SourceRange SR = AL.getSourceRange();
5243 return true;
5244 }
5246 // We have a template type parameter but the template argument is an
5247 // expression; see if maybe it is missing the "typename" keyword.
5248 CXXScopeSpec SS;
5249 DeclarationNameInfo NameInfo;
5250 TemplateArgument Pattern = Arg;
5251 if (Pattern.isPackExpansion())
5252 Pattern = Pattern.getPackExpansionPattern();
5253 Expr *E = Pattern.getAsExpr();
5254
5255 if (DependentScopeDeclRefExpr *ArgExpr =
5256 dyn_cast<DependentScopeDeclRefExpr>(E)) {
5257 SS.Adopt(ArgExpr->getQualifierLoc());
5258 NameInfo = ArgExpr->getNameInfo();
5259 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5260 dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5261 if (ArgExpr->isImplicitAccess()) {
5262 SS.Adopt(ArgExpr->getQualifierLoc());
5263 NameInfo = ArgExpr->getMemberNameInfo();
5264 }
5265 }
5266
5267 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5268 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5269 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5270
5271 if (Result.getAsSingle<TypeDecl>() ||
5272 Result.wasNotFoundInCurrentInstantiation()) {
5273 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5274 // Suggest that the user add 'typename' before the NNS.
5276 Diag(Loc, getLangOpts().MSVCCompat
5277 ? diag::ext_ms_template_type_arg_missing_typename
5278 : diag::err_template_arg_must_be_type_suggest)
5279 << FixItHint::CreateInsertion(Loc, "typename ");
5281
5282 // Recover by synthesizing a type using the location information that we
5283 // already have.
5284 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5285 SS.getScopeRep(), II);
5286 TypeLocBuilder TLB;
5288 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5290 TL.setNameLoc(NameInfo.getLoc());
5291 if (Arg.isPackExpansion()) {
5292 ArgType = Context.getPackExpansionType(ArgType, std::nullopt);
5294 TL.setEllipsisLoc(
5295 cast<PackExpansionExpr>(Arg.getAsExpr())->getEllipsisLoc());
5296 }
5297 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5298
5299 // Overwrite our input TemplateArgumentLoc so that we can recover
5300 // properly.
5303
5304 break;
5305 }
5306 }
5307 // fallthrough
5308 [[fallthrough]];
5309 }
5310 default: {
5311 // We allow instantiating a template with template argument packs when
5312 // building deduction guides or mapping constraint template parameters.
5313 if (Arg.getKind() == TemplateArgument::Pack &&
5314 (CodeSynthesisContexts.back().Kind ==
5317 SugaredConverted.push_back(Arg);
5318 CanonicalConverted.push_back(Arg);
5319 return false;
5320 }
5321 // We have a template type parameter but the template argument
5322 // is not a type.
5323 SourceRange SR = AL.getSourceRange();
5324 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5326
5327 return true;
5328 }
5329 }
5330
5331 if (CheckTemplateArgument(TSI))
5332 return true;
5333
5334 // Objective-C ARC:
5335 // If an explicitly-specified template argument type is a lifetime type
5336 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5337 if (getLangOpts().ObjCAutoRefCount &&
5338 ArgType->isObjCLifetimeType() &&
5339 !ArgType.getObjCLifetime()) {
5340 Qualifiers Qs;
5342 ArgType = Context.getQualifiedType(ArgType, Qs);
5343 }
5344
5345 SugaredConverted.push_back(TemplateArgument(ArgType));
5346 CanonicalConverted.push_back(
5347 TemplateArgument(Context.getCanonicalType(ArgType)));
5348 return false;
5349}
5350
5351/// Substitute template arguments into the default template argument for
5352/// the given template type parameter.
5353///
5354/// \param SemaRef the semantic analysis object for which we are performing
5355/// the substitution.
5356///
5357/// \param Template the template that we are synthesizing template arguments
5358/// for.
5359///
5360/// \param TemplateLoc the location of the template name that started the
5361/// template-id we are checking.
5362///
5363/// \param RAngleLoc the location of the right angle bracket ('>') that
5364/// terminates the template-id.
5365///
5366/// \param Param the template template parameter whose default we are
5367/// substituting into.
5368///
5369/// \param Converted the list of template arguments provided for template
5370/// parameters that precede \p Param in the template parameter list.
5371///
5372/// \param Output the resulting substituted template argument.
5373///
5374/// \returns true if an error occurred.
5376 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5377 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5378 ArrayRef<TemplateArgument> SugaredConverted,
5379 ArrayRef<TemplateArgument> CanonicalConverted,
5380 TemplateArgumentLoc &Output) {
5381 Output = Param->getDefaultArgument();
5382
5383 // If the argument type is dependent, instantiate it now based
5384 // on the previously-computed template arguments.
5385 if (Output.getArgument().isInstantiationDependent()) {
5386 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5387 SugaredConverted,
5388 SourceRange(TemplateLoc, RAngleLoc));
5389 if (Inst.isInvalid())
5390 return true;
5391
5392 // Only substitute for the innermost template argument list.
5393 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5394 /*Final=*/true);
5395 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5396 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5397
5398 bool ForLambdaCallOperator = false;
5399 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5400 ForLambdaCallOperator = Rec->isLambda();
5401 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5402 !ForLambdaCallOperator);
5403
5404 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5405 Param->getDefaultArgumentLoc(),
5406 Param->getDeclName()))
5407 return true;
5408 }
5409
5410 return false;
5411}
5412
5413/// Substitute template arguments into the default template argument for
5414/// the given non-type template parameter.
5415///
5416/// \param SemaRef the semantic analysis object for which we are performing
5417/// the substitution.
5418///
5419/// \param Template the template that we are synthesizing template arguments
5420/// for.
5421///
5422/// \param TemplateLoc the location of the template name that started the
5423/// template-id we are checking.
5424///
5425/// \param RAngleLoc the location of the right angle bracket ('>') that
5426/// terminates the template-id.
5427///
5428/// \param Param the non-type template parameter whose default we are
5429/// substituting into.
5430///
5431/// \param Converted the list of template arguments provided for template
5432/// parameters that precede \p Param in the template parameter list.
5433///
5434/// \returns the substituted template argument, or NULL if an error occurred.
5436 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5437 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5438 ArrayRef<TemplateArgument> SugaredConverted,
5439 ArrayRef<TemplateArgument> CanonicalConverted,
5440 TemplateArgumentLoc &Output) {
5441 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5442 SugaredConverted,
5443 SourceRange(TemplateLoc, RAngleLoc));
5444 if (Inst.isInvalid())
5445 return true;
5446
5447 // Only substitute for the innermost template argument list.
5448 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5449 /*Final=*/true);
5450 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5451 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5452
5453 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5454 EnterExpressionEvaluationContext ConstantEvaluated(
5456 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5457 TemplateArgLists, Output);
5458}
5459
5460/// Substitute template arguments into the default template argument for
5461/// the given template template parameter.
5462///
5463/// \param SemaRef the semantic analysis object for which we are performing
5464/// the substitution.
5465///
5466/// \param Template the template that we are synthesizing template arguments
5467/// for.
5468///
5469/// \param TemplateLoc the location of the template name that started the
5470/// template-id we are checking.
5471///
5472/// \param RAngleLoc the location of the right angle bracket ('>') that
5473/// terminates the template-id.
5474///
5475/// \param Param the template template parameter whose default we are
5476/// substituting into.
5477///
5478/// \param Converted the list of template arguments provided for template
5479/// parameters that precede \p Param in the template parameter list.
5480///
5481/// \param QualifierLoc Will be set to the nested-name-specifier (with
5482/// source-location information) that precedes the template name.
5483///
5484/// \returns the substituted template argument, or NULL if an error occurred.
5486 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5487 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5489 ArrayRef<TemplateArgument> SugaredConverted,
5490 ArrayRef<TemplateArgument> CanonicalConverted,
5491 NestedNameSpecifierLoc &QualifierLoc) {
5493 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5494 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5495 if (Inst.isInvalid())
5496 return TemplateName();
5497
5498 // Only substitute for the innermost template argument list.
5499 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5500 /*Final=*/true);
5501 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5502 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5503
5504 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5505
5506 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5507 QualifierLoc = A.getTemplateQualifierLoc();
5508 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5510 A.getTemplateNameLoc(), TemplateArgLists);
5511}
5512
5514 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5515 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5516 ArrayRef<TemplateArgument> SugaredConverted,
5517 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5518 HasDefaultArg = false;
5519
5520 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5521 if (!hasReachableDefaultArgument(TypeParm))
5522 return TemplateArgumentLoc();
5523
5524 HasDefaultArg = true;
5525 TemplateArgumentLoc Output;
5526 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5527 RAngleLoc, TypeParm, SugaredConverted,
5528 CanonicalConverted, Output))
5529 return TemplateArgumentLoc();
5530 return Output;
5531 }
5532
5533 if (NonTypeTemplateParmDecl *NonTypeParm
5534 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5535 if (!hasReachableDefaultArgument(NonTypeParm))
5536 return TemplateArgumentLoc();
5537
5538 HasDefaultArg = true;
5539 TemplateArgumentLoc Output;
5540 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5541 RAngleLoc, NonTypeParm, SugaredConverted,
5542 CanonicalConverted, Output))
5543 return TemplateArgumentLoc();
5544 return Output;
5545 }
5546
5547 TemplateTemplateParmDecl *TempTempParm
5549 if (!hasReachableDefaultArgument(TempTempParm))
5550 return TemplateArgumentLoc();
5551
5552 HasDefaultArg = true;
5553 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5554 NestedNameSpecifierLoc QualifierLoc;
5556 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5557 SugaredConverted, CanonicalConverted, QualifierLoc);
5558 if (TName.isNull())
5559 return TemplateArgumentLoc();
5560
5561 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5562 QualifierLoc, A.getTemplateNameLoc());
5563}
5564
5565/// Convert a template-argument that we parsed as a type into a template, if
5566/// possible. C++ permits injected-class-names to perform dual service as
5567/// template template arguments and as template type arguments.
5570 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5571 if (!TagLoc)
5572 return TemplateArgumentLoc();
5573
5574 // If this type was written as an injected-class-name, it can be used as a
5575 // template template argument.
5576 // If this type was written as an injected-class-name, it may have been
5577 // converted to a RecordType during instantiation. If the RecordType is
5578 // *not* wrapped in a TemplateSpecializationType and denotes a class
5579 // template specialization, it must have come from an injected-class-name.
5580
5581 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5582 if (Name.isNull())
5583 return TemplateArgumentLoc();
5584
5585 return TemplateArgumentLoc(Context, Name,
5586 /*TemplateKWLoc=*/SourceLocation(),
5587 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5588}
5589
5592 SourceLocation TemplateLoc,
5593 SourceLocation RAngleLoc,
5594 unsigned ArgumentPackIndex,
5597 // Check template type parameters.
5598 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5599 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5600 CTAI.CanonicalConverted);
5601
5602 const TemplateArgument &Arg = ArgLoc.getArgument();
5603 // Check non-type template parameters.
5604 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5605 // Do substitution on the type of the non-type template parameter
5606 // with the template arguments we've seen thus far. But if the
5607 // template has a dependent context then we cannot substitute yet.
5608 QualType NTTPType = NTTP->getType();
5609 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5610 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5611
5612 // C++26 [dcl.type.auto.deduct]p3:
5613 // If the placeholder-type-specifier is of the form type-constraint_opt
5614 // auto, [...] If E is a value synthesized for a constant template
5615 // parameter of type decltype(auto) ([temp.func.order]), the declaration
5616 // is ill-formed.
5617 auto isUndeducedAuto = [](QualType T, bool DecltypeAuto) {
5618 const AutoType *AT = T->getContainedAutoType();
5619 return AT && AT->isDecltypeAuto() == DecltypeAuto &&
5620 AT->getDeducedType().isNull();
5621 };
5622 if (CTAI.PartialOrdering &&
5623 isUndeducedAuto(NTTPType, /*DecltypeAuto=*/false) &&
5624 isUndeducedAuto(getTypeOfConstantTemplateParameter(Arg),
5625 /*DecltypeAuto=*/true))
5626 return true;
5627
5628 if (NTTPType->isInstantiationDependentType()) {
5629 // Do substitution on the type of the non-type template parameter.
5630 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5631 CTAI.SugaredConverted,
5632 SourceRange(TemplateLoc, RAngleLoc));
5633 if (Inst.isInvalid())
5634 return true;
5635
5637 /*Final=*/true);
5638 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5639 // If the parameter is a pack expansion, expand this slice of the pack.
5640 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5641 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5642 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5643 NTTP->getDeclName());
5644 } else {
5645 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5646 NTTP->getDeclName());
5647 }
5648
5649 // If that worked, check the non-type template parameter type
5650 // for validity.
5651 if (!NTTPType.isNull())
5652 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5653 NTTP->getLocation());
5654 if (NTTPType.isNull())
5655 return true;
5656 }
5657
5658 auto checkExpr = [&](Expr *E) -> Expr * {
5659 TemplateArgument SugaredResult, CanonicalResult;
5661 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5662 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5663 // If the current template argument causes an error, give up now.
5664 if (Res.isInvalid())
5665 return nullptr;
5666 CTAI.SugaredConverted.push_back(SugaredResult);
5667 CTAI.CanonicalConverted.push_back(CanonicalResult);
5668 return Res.get();
5669 };
5670
5671 switch (Arg.getKind()) {
5673 llvm_unreachable("Should never see a NULL template argument here");
5674
5676 Expr *E = Arg.getAsExpr();
5677 Expr *R = checkExpr(E);
5678 if (!R)
5679 return true;
5680 // If the resulting expression is new, then use it in place of the
5681 // old expression in the template argument.
5682 if (R != E) {
5683 TemplateArgument TA(R, /*IsCanonical=*/false);
5684 ArgLoc = TemplateArgumentLoc(TA, R);
5685 }
5686 break;
5687 }
5688
5689 // As for the converted NTTP kinds, they still might need another
5690 // conversion, as the new corresponding parameter might be different.
5691 // Ideally, we would always perform substitution starting with sugared types
5692 // and never need these, as we would still have expressions. Since these are
5693 // needed so rarely, it's probably a better tradeoff to just convert them
5694 // back to expressions.
5699 // FIXME: StructuralValue is untested here.
5700 ExprResult R =
5702 assert(R.isUsable());
5703 if (!checkExpr(R.get()))
5704 return true;
5705 break;
5706 }
5707
5710 // We were given a template template argument. It may not be ill-formed;
5711 // see below.
5714 // We have a template argument such as \c T::template X, which we
5715 // parsed as a template template argument. However, since we now
5716 // know that we need a non-type template argument, convert this
5717 // template name into an expression.
5718
5719 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5720 ArgLoc.getTemplateNameLoc());
5721
5722 CXXScopeSpec SS;
5723 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5724 // FIXME: the template-template arg was a DependentTemplateName,
5725 // so it was provided with a template keyword. However, its source
5726 // location is not stored in the template argument structure.
5727 SourceLocation TemplateKWLoc;
5729 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5730 nullptr);
5731
5732 // If we parsed the template argument as a pack expansion, create a
5733 // pack expansion expression.
5736 if (E.isInvalid())
5737 return true;
5738 }
5739
5740 TemplateArgument SugaredResult, CanonicalResult;
5742 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5743 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5744 if (E.isInvalid())
5745 return true;
5746
5747 CTAI.SugaredConverted.push_back(SugaredResult);
5748 CTAI.CanonicalConverted.push_back(CanonicalResult);
5749 break;
5750 }
5751
5752 // We have a template argument that actually does refer to a class
5753 // template, alias template, or template template parameter, and
5754 // therefore cannot be a non-type template argument.
5755 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5756 << ArgLoc.getSourceRange();
5758
5759 return true;
5760
5762 // We have a non-type template parameter but the template
5763 // argument is a type.
5764
5765 // C++ [temp.arg]p2:
5766 // In a template-argument, an ambiguity between a type-id and
5767 // an expression is resolved to a type-id, regardless of the
5768 // form of the corresponding template-parameter.
5769 //
5770 // We warn specifically about this case, since it can be rather
5771 // confusing for users.
5772 QualType T = Arg.getAsType();
5773 SourceRange SR = ArgLoc.getSourceRange();
5774 if (T->isFunctionType())
5775 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5776 else
5777 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5779 return true;
5780 }
5781
5783 llvm_unreachable("Caller must expand template argument packs");
5784 }
5785
5786 return false;
5787 }
5788
5789
5790 // Check template template parameters.
5792
5793 TemplateParameterList *Params = TempParm->getTemplateParameters();
5794 if (TempParm->isExpandedParameterPack())
5795 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5796
5797 // Substitute into the template parameter list of the template
5798 // template parameter, since previously-supplied template arguments
5799 // may appear within the template template parameter.
5800 //
5801 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5802 {
5803 // Set up a template instantiation context.
5805 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5806 CTAI.SugaredConverted,
5807 SourceRange(TemplateLoc, RAngleLoc));
5808 if (Inst.isInvalid())
5809 return true;
5810
5811 Params = SubstTemplateParams(
5812 Params, CurContext,
5814 /*Final=*/true),
5815 /*EvaluateConstraints=*/false);
5816 if (!Params)
5817 return true;
5818 }
5819
5820 // C++1z [temp.local]p1: (DR1004)
5821 // When [the injected-class-name] is used [...] as a template-argument for
5822 // a template template-parameter [...] it refers to the class template
5823 // itself.
5824 if (Arg.getKind() == TemplateArgument::Type) {
5826 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5827 if (!ConvertedArg.getArgument().isNull())
5828 ArgLoc = ConvertedArg;
5829 }
5830
5831 switch (Arg.getKind()) {
5833 llvm_unreachable("Should never see a NULL template argument here");
5834
5837 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5838 CTAI.PartialOrdering,
5839 &CTAI.StrictPackMatch))
5840 return true;
5841
5842 CTAI.SugaredConverted.push_back(Arg);
5843 CTAI.CanonicalConverted.push_back(
5844 Context.getCanonicalTemplateArgument(Arg));
5845 break;
5846
5849 auto Kind = 0;
5850 switch (TempParm->templateParameterKind()) {
5852 Kind = 1;
5853 break;
5855 Kind = 2;
5856 break;
5857 default:
5858 break;
5859 }
5860
5861 // We have a template template parameter but the template
5862 // argument does not refer to a template.
5863 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5864 << Kind << getLangOpts().CPlusPlus11;
5865 return true;
5866 }
5867
5872 llvm_unreachable("non-type argument with template template parameter");
5873
5875 llvm_unreachable("Caller must expand template argument packs");
5876 }
5877
5878 return false;
5879}
5880
5881/// Diagnose a missing template argument.
5882template <typename TemplateParmDecl>
5884 TemplateDecl *TD,
5885 const TemplateParmDecl *D) {
5886 // Dig out the most recent declaration of the template parameter; there may be
5887 // declarations of the template that are more recent than TD.
5889 ->getTemplateParameters()
5890 ->getParam(D->getIndex()));
5891
5892 // If there's a default argument that's not reachable, diagnose that we're
5893 // missing a module import.
5895 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5897 D->getDefaultArgumentLoc(), Modules,
5899 /*Recover*/true);
5900 return;
5901 }
5902
5903 // FIXME: If there's a more recent default argument that *is* visible,
5904 // diagnose that it was declared too late.
5905
5907
5908 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5909 << /*not enough args*/0
5911 << TD;
5912 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5913}
5914
5915/// Check that the given template argument list is well-formed
5916/// for specializing the given template.
5918 TemplateDecl *Template, SourceLocation TemplateLoc,
5919 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5920 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5921 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5923 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5924 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5926}
5927
5928/// Check that the given template argument list is well-formed
5929/// for specializing the given template.
5932 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5933 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5934 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5936
5938 *ConstraintsNotSatisfied = false;
5939
5940 // Make a copy of the template arguments for processing. Only make the
5941 // changes at the end when successful in matching the arguments to the
5942 // template.
5943 TemplateArgumentListInfo NewArgs = TemplateArgs;
5944
5945 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5946
5947 // C++23 [temp.arg.general]p1:
5948 // [...] The type and form of each template-argument specified in
5949 // a template-id shall match the type and form specified for the
5950 // corresponding parameter declared by the template in its
5951 // template-parameter-list.
5952 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5953 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5954 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5955 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5956 LocalInstantiationScope InstScope(*this, true);
5957 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5958 ParamEnd = Params->end(),
5959 Param = ParamBegin;
5960 Param != ParamEnd;
5961 /* increment in loop */) {
5962 if (size_t ParamIdx = Param - ParamBegin;
5963 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5964 // All written arguments should have been consumed by this point.
5965 assert(ArgIdx == NumArgs && "bad default argument deduction");
5966 if (ParamIdx == DefaultArgs.StartPos) {
5967 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5968 // Default arguments from a DeducedTemplateName are already converted.
5969 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5970 CTAI.SugaredConverted.push_back(DefArg);
5971 CTAI.CanonicalConverted.push_back(
5972 Context.getCanonicalTemplateArgument(DefArg));
5973 ++Param;
5974 }
5975 continue;
5976 }
5977 }
5978
5979 // If we have an expanded parameter pack, make sure we don't have too
5980 // many arguments.
5981 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5982 if (*Expansions == SugaredArgumentPack.size()) {
5983 // We're done with this parameter pack. Pack up its arguments and add
5984 // them to the list.
5985 CTAI.SugaredConverted.push_back(
5986 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5987 SugaredArgumentPack.clear();
5988
5989 CTAI.CanonicalConverted.push_back(
5990 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5991 CanonicalArgumentPack.clear();
5992
5993 // This argument is assigned to the next parameter.
5994 ++Param;
5995 continue;
5996 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5997 // Not enough arguments for this parameter pack.
5998 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5999 << /*not enough args*/0
6001 << Template;
6003 return true;
6004 }
6005 }
6006
6007 // Check for builtins producing template packs in this context, we do not
6008 // support them yet.
6009 if (const NonTypeTemplateParmDecl *NTTP =
6010 dyn_cast<NonTypeTemplateParmDecl>(*Param);
6011 NTTP && NTTP->isPackExpansion()) {
6012 auto TL = NTTP->getTypeSourceInfo()
6013 ->getTypeLoc()
6016 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
6017 for (const auto &UPP : Unexpanded) {
6018 auto *TST = dyn_cast<const TemplateSpecializationType *>(UPP.first);
6019 if (!TST)
6020 continue;
6021 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
6022 // Expanding a built-in pack in this context is not yet supported.
6023 Diag(TL.getEllipsisLoc(),
6024 diag::err_unsupported_builtin_template_pack_expansion)
6025 << TST->getTemplateName();
6026 return true;
6027 }
6028 }
6029
6030 if (ArgIdx < NumArgs) {
6031 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
6032 bool NonPackParameter =
6033 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
6034 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
6035
6036 if (ArgIsExpansion && CTAI.MatchingTTP) {
6037 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
6038 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
6039 ++Param) {
6040 TemplateArgument &Arg = Args[Param - First];
6041 Arg = ArgLoc.getArgument();
6042 if (!(*Param)->isTemplateParameterPack() ||
6043 getExpandedPackSize(*Param))
6044 Arg = Arg.getPackExpansionPattern();
6045 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
6046 SaveAndRestore _1(CTAI.PartialOrdering, false);
6047 SaveAndRestore _2(CTAI.MatchingTTP, true);
6048 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
6049 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6051 return true;
6052 Arg = NewArgLoc.getArgument();
6053 CTAI.CanonicalConverted.back().setIsDefaulted(
6054 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6055 CTAI.CanonicalConverted,
6056 Params->getDepth()));
6057 }
6058 ArgLoc = TemplateArgumentLoc(
6061 } else {
6062 SaveAndRestore _1(CTAI.PartialOrdering, false);
6063 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6064 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6066 return true;
6067 CTAI.CanonicalConverted.back().setIsDefaulted(
6068 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6069 *Param, CTAI.CanonicalConverted,
6070 Params->getDepth()));
6071 if (ArgIsExpansion && NonPackParameter) {
6072 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6073 // alias template, builtin template, or concept, and it's not part of
6074 // a parameter pack. This can't be canonicalized, so reject it now.
6076 Template)) {
6077 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6079 : 0;
6080 Diag(ArgLoc.getLocation(),
6081 diag::err_template_expansion_into_fixed_list)
6082 << DiagSelect << ArgLoc.getSourceRange();
6084 return true;
6085 }
6086 }
6087 }
6088
6089 // We're now done with this argument.
6090 ++ArgIdx;
6091
6092 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6093 // Directly convert the remaining arguments, because we don't know what
6094 // parameters they'll match up with.
6095
6096 if (!SugaredArgumentPack.empty()) {
6097 // If we were part way through filling in an expanded parameter pack,
6098 // fall back to just producing individual arguments.
6099 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6100 SugaredArgumentPack.begin(),
6101 SugaredArgumentPack.end());
6102 SugaredArgumentPack.clear();
6103
6104 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6105 CanonicalArgumentPack.begin(),
6106 CanonicalArgumentPack.end());
6107 CanonicalArgumentPack.clear();
6108 }
6109
6110 while (ArgIdx < NumArgs) {
6111 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6112 CTAI.SugaredConverted.push_back(Arg);
6113 CTAI.CanonicalConverted.push_back(
6114 Context.getCanonicalTemplateArgument(Arg));
6115 ++ArgIdx;
6116 }
6117
6118 return false;
6119 }
6120
6121 if ((*Param)->isTemplateParameterPack()) {
6122 // The template parameter was a template parameter pack, so take the
6123 // deduced argument and place it on the argument pack. Note that we
6124 // stay on the same template parameter so that we can deduce more
6125 // arguments.
6126 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6127 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6128 } else {
6129 // Move to the next template parameter.
6130 ++Param;
6131 }
6132 continue;
6133 }
6134
6135 // If we're checking a partial template argument list, we're done.
6136 if (PartialTemplateArgs) {
6137 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6138 CTAI.SugaredConverted.push_back(
6139 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6140 CTAI.CanonicalConverted.push_back(
6141 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6142 }
6143 return false;
6144 }
6145
6146 // If we have a template parameter pack with no more corresponding
6147 // arguments, just break out now and we'll fill in the argument pack below.
6148 if ((*Param)->isTemplateParameterPack()) {
6149 assert(!getExpandedPackSize(*Param) &&
6150 "Should have dealt with this already");
6151
6152 // A non-expanded parameter pack before the end of the parameter list
6153 // only occurs for an ill-formed template parameter list, unless we've
6154 // got a partial argument list for a function template, so just bail out.
6155 if (Param + 1 != ParamEnd) {
6156 assert(
6157 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6158 "Concept templates must have parameter packs at the end.");
6159 return true;
6160 }
6161
6162 CTAI.SugaredConverted.push_back(
6163 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6164 SugaredArgumentPack.clear();
6165
6166 CTAI.CanonicalConverted.push_back(
6167 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6168 CanonicalArgumentPack.clear();
6169
6170 ++Param;
6171 continue;
6172 }
6173
6174 // Check whether we have a default argument.
6175 bool HasDefaultArg;
6176
6177 // Retrieve the default template argument from the template
6178 // parameter. For each kind of template parameter, we substitute the
6179 // template arguments provided thus far and any "outer" template arguments
6180 // (when the template parameter was part of a nested template) into
6181 // the default argument.
6183 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6184 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6185
6186 if (Arg.getArgument().isNull()) {
6187 if (!HasDefaultArg) {
6188 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6189 diagnoseMissingArgument(*this, TemplateLoc, Template, TTP);
6190 else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*Param))
6191 diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP);
6192 else
6193 diagnoseMissingArgument(*this, TemplateLoc, Template,
6195 }
6196 return true;
6197 }
6198
6199 // Introduce an instantiation record that describes where we are using
6200 // the default template argument. We're not actually instantiating a
6201 // template here, we just create this object to put a note into the
6202 // context stack.
6203 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6204 CTAI.SugaredConverted,
6205 SourceRange(TemplateLoc, RAngleLoc));
6206 if (Inst.isInvalid())
6207 return true;
6208
6209 SaveAndRestore _1(CTAI.PartialOrdering, false);
6210 SaveAndRestore _2(CTAI.MatchingTTP, false);
6211 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6212 // Check the default template argument.
6213 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6214 CTAI, CTAK_Specified))
6215 return true;
6216
6217 CTAI.SugaredConverted.back().setIsDefaulted(true);
6218 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6219
6220 // Core issue 150 (assumed resolution): if this is a template template
6221 // parameter, keep track of the default template arguments from the
6222 // template definition.
6223 if (isTemplateTemplateParameter)
6224 NewArgs.addArgument(Arg);
6225
6226 // Move to the next template parameter and argument.
6227 ++Param;
6228 ++ArgIdx;
6229 }
6230
6231 // If we're performing a partial argument substitution, allow any trailing
6232 // pack expansions; they might be empty. This can happen even if
6233 // PartialTemplateArgs is false (the list of arguments is complete but
6234 // still dependent).
6235 if (CTAI.MatchingTTP ||
6237 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6238 while (ArgIdx < NumArgs &&
6239 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6240 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6241 CTAI.SugaredConverted.push_back(Arg);
6242 CTAI.CanonicalConverted.push_back(
6243 Context.getCanonicalTemplateArgument(Arg));
6244 }
6245 }
6246
6247 // If we have any leftover arguments, then there were too many arguments.
6248 // Complain and fail.
6249 if (ArgIdx < NumArgs) {
6250 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6251 << /*too many args*/1
6253 << Template
6254 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6256 return true;
6257 }
6258
6259 // No problems found with the new argument list, propagate changes back
6260 // to caller.
6261 if (UpdateArgsWithConversions)
6262 TemplateArgs = std::move(NewArgs);
6263
6264 if (!PartialTemplateArgs) {
6265 // Setup the context/ThisScope for the case where we are needing to
6266 // re-instantiate constraints outside of normal instantiation.
6267 DeclContext *NewContext = Template->getDeclContext();
6268
6269 // If this template is in a template, make sure we extract the templated
6270 // decl.
6271 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6272 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6273 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6274
6275 Qualifiers ThisQuals;
6276 if (const auto *Method =
6277 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6278 ThisQuals = Method->getMethodQualifiers();
6279
6280 ContextRAII Context(*this, NewContext);
6281 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6282
6284 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6285 /*RelativeToPrimary=*/true,
6286 /*Pattern=*/nullptr,
6287 /*ForConceptInstantiation=*/true);
6288 if (!isa<ConceptDecl>(Template) &&
6290 Template, MLTAL,
6291 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6294 return true;
6295 }
6296 }
6297
6298 return false;
6299}
6300
6301namespace {
6302 class UnnamedLocalNoLinkageFinder
6303 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6304 {
6305 Sema &S;
6306 SourceRange SR;
6307
6309
6310 public:
6311 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6312
6313 bool Visit(QualType T) {
6314 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6315 }
6316
6317#define TYPE(Class, Parent) \
6318 bool Visit##Class##Type(const Class##Type *);
6319#define ABSTRACT_TYPE(Class, Parent) \
6320 bool Visit##Class##Type(const Class##Type *) { return false; }
6321#define NON_CANONICAL_TYPE(Class, Parent) \
6322 bool Visit##Class##Type(const Class##Type *) { return false; }
6323#include "clang/AST/TypeNodes.inc"
6324
6325 bool VisitTagDecl(const TagDecl *Tag);
6326 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6327 };
6328} // end anonymous namespace
6329
6330bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6331 return false;
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6335 return Visit(T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6339 return Visit(T->getPointeeType());
6340}
6341
6342bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6343 const BlockPointerType* T) {
6344 return Visit(T->getPointeeType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6348 const LValueReferenceType* T) {
6349 return Visit(T->getPointeeType());
6350}
6351
6352bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6353 const RValueReferenceType* T) {
6354 return Visit(T->getPointeeType());
6355}
6356
6357bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6358 const MemberPointerType *T) {
6359 if (Visit(T->getPointeeType()))
6360 return true;
6361 if (auto *RD = T->getMostRecentCXXRecordDecl())
6362 return VisitTagDecl(RD);
6363 return VisitNestedNameSpecifier(T->getQualifier());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6367 const ConstantArrayType* T) {
6368 return Visit(T->getElementType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6372 const IncompleteArrayType* T) {
6373 return Visit(T->getElementType());
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6377 const VariableArrayType* T) {
6378 return Visit(T->getElementType());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6382 const DependentSizedArrayType* T) {
6383 return Visit(T->getElementType());
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6387 const DependentSizedExtVectorType* T) {
6388 return Visit(T->getElementType());
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6392 const DependentSizedMatrixType *T) {
6393 return Visit(T->getElementType());
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6397 const DependentAddressSpaceType *T) {
6398 return Visit(T->getPointeeType());
6399}
6400
6401bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6402 return Visit(T->getElementType());
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6406 const DependentVectorType *T) {
6407 return Visit(T->getElementType());
6408}
6409
6410bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6411 return Visit(T->getElementType());
6412}
6413
6414bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6415 const ConstantMatrixType *T) {
6416 return Visit(T->getElementType());
6417}
6418
6419bool UnnamedLocalNoLinkageFinder::VisitCooperativeMatrixType(
6420 const CooperativeMatrixType *T) {
6421 return Visit(T->getElementType());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6425 const FunctionProtoType* T) {
6426 for (const auto &A : T->param_types()) {
6427 if (Visit(A))
6428 return true;
6429 }
6430
6431 return Visit(T->getReturnType());
6432}
6433
6434bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6435 const FunctionNoProtoType* T) {
6436 return Visit(T->getReturnType());
6437}
6438
6439bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6440 const UnresolvedUsingType*) {
6441 return false;
6442}
6443
6444bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6445 return false;
6446}
6447
6448bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6449 return Visit(T->getUnmodifiedType());
6450}
6451
6452bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6453 return false;
6454}
6455
6456bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6457 const PackIndexingType *) {
6458 return false;
6459}
6460
6461bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6462 const UnaryTransformType*) {
6463 return false;
6464}
6465
6466bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6467 return Visit(T->getDeducedType());
6468}
6469
6470bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6471 const DeducedTemplateSpecializationType *T) {
6472 return Visit(T->getDeducedType());
6473}
6474
6475bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6476 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6477}
6478
6479bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6480 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6481}
6482
6483bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6484 const TemplateTypeParmType*) {
6485 return false;
6486}
6487
6488bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6489 const SubstTemplateTypeParmPackType *) {
6490 return false;
6491}
6492
6493bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6494 const SubstBuiltinTemplatePackType *) {
6495 return false;
6496}
6497
6498bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6499 const TemplateSpecializationType*) {
6500 return false;
6501}
6502
6503bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6504 const InjectedClassNameType* T) {
6505 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6509 const DependentNameType* T) {
6510 return VisitNestedNameSpecifier(T->getQualifier());
6511}
6512
6513bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6514 const PackExpansionType* T) {
6515 return Visit(T->getPattern());
6516}
6517
6518bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6519 return false;
6520}
6521
6522bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6523 const ObjCInterfaceType *) {
6524 return false;
6525}
6526
6527bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6528 const ObjCObjectPointerType *) {
6529 return false;
6530}
6531
6532bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6533 return Visit(T->getValueType());
6534}
6535
6536bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6537 const OverflowBehaviorType *T) {
6538 return Visit(T->getUnderlyingType());
6539}
6540
6541bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6542 return false;
6543}
6544
6545bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6546 return false;
6547}
6548
6549bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6550 const ArrayParameterType *T) {
6551 return VisitConstantArrayType(T);
6552}
6553
6554bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6555 const DependentBitIntType *T) {
6556 return false;
6557}
6558
6559bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6560 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6561 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6562 ? diag::warn_cxx98_compat_template_arg_local_type
6563 : diag::ext_template_arg_local_type)
6564 << S.Context.getCanonicalTagType(Tag) << SR;
6565 return true;
6566 }
6567
6568 if (!Tag->hasNameForLinkage()) {
6569 S.Diag(SR.getBegin(),
6570 S.getLangOpts().CPlusPlus11 ?
6571 diag::warn_cxx98_compat_template_arg_unnamed_type :
6572 diag::ext_template_arg_unnamed_type) << SR;
6573 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6574 return true;
6575 }
6576
6577 return false;
6578}
6579
6580bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6581 NestedNameSpecifier NNS) {
6582 switch (NNS.getKind()) {
6587 return false;
6589 return Visit(QualType(NNS.getAsType(), 0));
6590 }
6591 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6592}
6593
6594bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6595 const HLSLAttributedResourceType *T) {
6596 if (T->hasContainedType() && Visit(T->getContainedType()))
6597 return true;
6598 return Visit(T->getWrappedType());
6599}
6600
6601bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6602 const HLSLInlineSpirvType *T) {
6603 for (auto &Operand : T->getOperands())
6604 if (Operand.isConstant() && Operand.isLiteral())
6605 if (Visit(Operand.getResultType()))
6606 return true;
6607 return false;
6608}
6609
6611 assert(ArgInfo && "invalid TypeSourceInfo");
6612 QualType Arg = ArgInfo->getType();
6613 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6614 QualType CanonArg = Context.getCanonicalType(Arg);
6615
6616 if (CanonArg->isVariablyModifiedType()) {
6617 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6618 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6619 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6620 }
6621
6622 // C++03 [temp.arg.type]p2:
6623 // A local type, a type with no linkage, an unnamed type or a type
6624 // compounded from any of these types shall not be used as a
6625 // template-argument for a template type-parameter.
6626 //
6627 // C++11 allows these, and even in C++03 we allow them as an extension with
6628 // a warning.
6629 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6630 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6631 (void)Finder.Visit(CanonArg);
6632 }
6633
6634 return false;
6635}
6636
6642
6643/// Determine whether the given template argument is a null pointer
6644/// value of the appropriate type.
6647 QualType ParamType, Expr *Arg,
6648 Decl *Entity = nullptr) {
6649 if (Arg->isValueDependent() || Arg->isTypeDependent())
6650 return NPV_NotNullPointer;
6651
6652 // dllimport'd entities aren't constant but are available inside of template
6653 // arguments.
6654 if (Entity && Entity->hasAttr<DLLImportAttr>())
6655 return NPV_NotNullPointer;
6656
6657 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6658 llvm_unreachable(
6659 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6660
6661 if (!S.getLangOpts().CPlusPlus11)
6662 return NPV_NotNullPointer;
6663
6664 // Determine whether we have a constant expression.
6666 if (ArgRV.isInvalid())
6667 return NPV_Error;
6668 Arg = ArgRV.get();
6669
6670 Expr::EvalResult EvalResult;
6672 EvalResult.Diag = &Notes;
6673 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6674 EvalResult.HasSideEffects) {
6675 SourceLocation DiagLoc = Arg->getExprLoc();
6676
6677 // If our only note is the usual "invalid subexpression" note, just point
6678 // the caret at its location rather than producing an essentially
6679 // redundant note.
6680 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6681 diag::note_invalid_subexpr_in_const_expr) {
6682 DiagLoc = Notes[0].first;
6683 Notes.clear();
6684 }
6685
6686 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6687 << Arg->getType() << Arg->getSourceRange();
6688 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6689 S.Diag(Notes[I].first, Notes[I].second);
6690
6692 return NPV_Error;
6693 }
6694
6695 // C++11 [temp.arg.nontype]p1:
6696 // - an address constant expression of type std::nullptr_t
6697 if (Arg->getType()->isNullPtrType())
6698 return NPV_NullPointer;
6699
6700 // - a constant expression that evaluates to a null pointer value (4.10); or
6701 // - a constant expression that evaluates to a null member pointer value
6702 // (4.11); or
6703 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6704 (EvalResult.Val.isMemberPointer() &&
6705 !EvalResult.Val.getMemberPointerDecl())) {
6706 // If our expression has an appropriate type, we've succeeded.
6707 bool ObjCLifetimeConversion;
6708 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6709 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6710 ObjCLifetimeConversion))
6711 return NPV_NullPointer;
6712
6713 // The types didn't match, but we know we got a null pointer; complain,
6714 // then recover as if the types were correct.
6715 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6716 << Arg->getType() << ParamType << Arg->getSourceRange();
6718 return NPV_NullPointer;
6719 }
6720
6721 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6722 // We found a pointer that isn't null, but doesn't refer to an object.
6723 // We could just return NPV_NotNullPointer, but we can print a better
6724 // message with the information we have here.
6725 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6726 << EvalResult.Val.getAsString(S.Context, ParamType);
6728 return NPV_Error;
6729 }
6730
6731 // If we don't have a null pointer value, but we do have a NULL pointer
6732 // constant, suggest a cast to the appropriate type.
6734 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6735 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6736 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6738 ")");
6740 return NPV_NullPointer;
6741 }
6742
6743 // FIXME: If we ever want to support general, address-constant expressions
6744 // as non-type template arguments, we should return the ExprResult here to
6745 // be interpreted by the caller.
6746 return NPV_NotNullPointer;
6747}
6748
6749/// Checks whether the given template argument is compatible with its
6750/// template parameter.
6751static bool
6753 QualType ParamType, Expr *ArgIn,
6754 Expr *Arg, QualType ArgType) {
6755 bool ObjCLifetimeConversion;
6756 if (ParamType->isPointerType() &&
6757 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6758 S.IsQualificationConversion(ArgType, ParamType, false,
6759 ObjCLifetimeConversion)) {
6760 // For pointer-to-object types, qualification conversions are
6761 // permitted.
6762 } else {
6763 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6764 if (!ParamRef->getPointeeType()->isFunctionType()) {
6765 // C++ [temp.arg.nontype]p5b3:
6766 // For a non-type template-parameter of type reference to
6767 // object, no conversions apply. The type referred to by the
6768 // reference may be more cv-qualified than the (otherwise
6769 // identical) type of the template- argument. The
6770 // template-parameter is bound directly to the
6771 // template-argument, which shall be an lvalue.
6772
6773 // FIXME: Other qualifiers?
6774 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6775 unsigned ArgQuals = ArgType.getCVRQualifiers();
6776
6777 if ((ParamQuals | ArgQuals) != ParamQuals) {
6778 S.Diag(Arg->getBeginLoc(),
6779 diag::err_template_arg_ref_bind_ignores_quals)
6780 << ParamType << Arg->getType() << Arg->getSourceRange();
6782 return true;
6783 }
6784 }
6785 }
6786
6787 // At this point, the template argument refers to an object or
6788 // function with external linkage. We now need to check whether the
6789 // argument and parameter types are compatible.
6790 if (!S.Context.hasSameUnqualifiedType(ArgType,
6791 ParamType.getNonReferenceType())) {
6792 // We can't perform this conversion or binding.
6793 if (ParamType->isReferenceType())
6794 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6795 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6796 else
6797 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6798 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6800 return true;
6801 }
6802 }
6803
6804 return false;
6805}
6806
6807/// Checks whether the given template argument is the address
6808/// of an object or function according to C++ [temp.arg.nontype]p1.
6810 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6811 bool IsSpecified, TemplateArgument &SugaredConverted,
6812 TemplateArgument &CanonicalConverted) {
6813 Expr *Arg = ArgIn;
6814 QualType ArgType = Arg->getType();
6815
6816 bool AddressTaken = false;
6817 SourceLocation AddrOpLoc;
6818 if (S.getLangOpts().MicrosoftExt) {
6819 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6820 // dereference and address-of operators.
6821 Arg = Arg->IgnoreParenCasts();
6822
6823 bool ExtWarnMSTemplateArg = false;
6824 UnaryOperatorKind FirstOpKind;
6825 SourceLocation FirstOpLoc;
6826 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6827 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6828 if (UnOpKind == UO_Deref)
6829 ExtWarnMSTemplateArg = true;
6830 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6831 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6832 if (!AddrOpLoc.isValid()) {
6833 FirstOpKind = UnOpKind;
6834 FirstOpLoc = UnOp->getOperatorLoc();
6835 }
6836 } else
6837 break;
6838 }
6839 if (FirstOpLoc.isValid()) {
6840 if (ExtWarnMSTemplateArg)
6841 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6842 << ArgIn->getSourceRange();
6843
6844 if (FirstOpKind == UO_AddrOf)
6845 AddressTaken = true;
6846 else if (Arg->getType()->isPointerType()) {
6847 // We cannot let pointers get dereferenced here, that is obviously not a
6848 // constant expression.
6849 assert(FirstOpKind == UO_Deref);
6850 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6851 << Arg->getSourceRange();
6852 }
6853 }
6854 } else {
6855 // See through any implicit casts we added to fix the type.
6856 // Also ignore parentheses for deduced template arguments.
6857 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6858
6859 // C++ [temp.arg.nontype]p1:
6860 //
6861 // A template-argument for a non-type, non-template
6862 // template-parameter shall be one of: [...]
6863 //
6864 // -- the address of an object or function with external
6865 // linkage, including function templates and function
6866 // template-ids but excluding non-static class members,
6867 // expressed as & id-expression where the & is optional if
6868 // the name refers to a function or array, or if the
6869 // corresponding template-parameter is a reference; or
6870
6871 // In C++98/03 mode, give an extension warning on any extra parentheses.
6872 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6873 if (IsSpecified) {
6874 bool ExtraParens = false;
6875 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6876 if (!ExtraParens) {
6877 S.DiagCompat(Arg->getBeginLoc(),
6878 diag_compat::template_arg_extra_parens)
6879 << Arg->getSourceRange();
6880 ExtraParens = true;
6881 }
6882
6883 Arg = Parens->getSubExpr();
6884 }
6885 }
6886
6887 while (SubstNonTypeTemplateParmExpr *subst =
6888 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6889 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6890
6891 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6892 if (UnOp->getOpcode() == UO_AddrOf) {
6893 Arg = UnOp->getSubExpr();
6894 AddressTaken = true;
6895 AddrOpLoc = UnOp->getOperatorLoc();
6896 }
6897 }
6898
6899 while (SubstNonTypeTemplateParmExpr *subst =
6900 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6901 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6902 }
6903
6904 ValueDecl *Entity = nullptr;
6905 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6906 Entity = DRE->getDecl();
6907 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6908 Entity = CUE->getGuidDecl();
6909
6910 // If our parameter has pointer type, check for a null template value.
6911 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6912 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6913 Entity)) {
6914 case NPV_NullPointer:
6915 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6916 SugaredConverted = TemplateArgument(ParamType,
6917 /*isNullPtr=*/true);
6918 CanonicalConverted =
6920 /*isNullPtr=*/true);
6921 return false;
6922
6923 case NPV_Error:
6924 return true;
6925
6926 case NPV_NotNullPointer:
6927 break;
6928 }
6929 }
6930
6931 // Stop checking the precise nature of the argument if it is value dependent,
6932 // it should be checked when instantiated.
6933 if (Arg->isValueDependent()) {
6934 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6935 CanonicalConverted =
6936 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6937 return false;
6938 }
6939
6940 if (!Entity) {
6941 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6942 << Arg->getSourceRange();
6944 return true;
6945 }
6946
6947 // Cannot refer to non-static data members
6948 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6949 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6950 << Entity << Arg->getSourceRange();
6952 return true;
6953 }
6954
6955 // Cannot refer to non-static member functions
6956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6957 if (!Method->isStatic()) {
6958 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6959 << Method << Arg->getSourceRange();
6961 return true;
6962 }
6963 }
6964
6965 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6966 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6967 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6968
6969 // A non-type template argument must refer to an object or function.
6970 if (!Func && !Var && !Guid) {
6971 // We found something, but we don't know specifically what it is.
6972 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6973 << Arg->getSourceRange();
6974 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6975 return true;
6976 }
6977
6978 // Address / reference template args must have external linkage in C++98.
6979 if (Entity->getFormalLinkage() == Linkage::Internal) {
6980 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_object_internal)
6981 << !Func << Entity << Arg->getSourceRange();
6982 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6983 << !Func;
6984 } else if (!Entity->hasLinkage()) {
6985 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6986 << !Func << Entity << Arg->getSourceRange();
6987 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6988 << !Func;
6989 return true;
6990 }
6991
6992 if (Var) {
6993 // A value of reference type is not an object.
6994 if (Var->getType()->isReferenceType()) {
6995 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6996 << Var->getType() << Arg->getSourceRange();
6998 return true;
6999 }
7000
7001 // A template argument must have static storage duration.
7002 if (Var->getTLSKind()) {
7003 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
7004 << Arg->getSourceRange();
7005 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7006 return true;
7007 }
7008 }
7009
7010 if (AddressTaken && ParamType->isReferenceType()) {
7011 // If we originally had an address-of operator, but the
7012 // parameter has reference type, complain and (if things look
7013 // like they will work) drop the address-of operator.
7014 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7015 ParamType.getNonReferenceType())) {
7016 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7017 << ParamType;
7019 return true;
7020 }
7021
7022 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7023 << ParamType
7024 << FixItHint::CreateRemoval(AddrOpLoc);
7026
7027 ArgType = Entity->getType();
7028 }
7029
7030 // If the template parameter has pointer type, either we must have taken the
7031 // address or the argument must decay to a pointer.
7032 if (!AddressTaken && ParamType->isPointerType()) {
7033 if (Func) {
7034 // Function-to-pointer decay.
7035 ArgType = S.Context.getPointerType(Func->getType());
7036 } else if (Entity->getType()->isArrayType()) {
7037 // Array-to-pointer decay.
7038 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7039 } else {
7040 // If the template parameter has pointer type but the address of
7041 // this object was not taken, complain and (possibly) recover by
7042 // taking the address of the entity.
7043 ArgType = S.Context.getPointerType(Entity->getType());
7044 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7045 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7046 << ParamType;
7048 return true;
7049 }
7050
7051 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7052 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7053
7055 }
7056 }
7057
7058 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7059 Arg, ArgType))
7060 return true;
7061
7062 // Create the template argument.
7063 SugaredConverted = TemplateArgument(Entity, ParamType);
7064 CanonicalConverted =
7066 S.Context.getCanonicalType(ParamType));
7067 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7068 return false;
7069}
7070
7071/// Checks whether the given template argument is a pointer to
7072/// member constant according to C++ [temp.arg.nontype]p1.
7074 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7075 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7076 bool Invalid = false;
7077
7078 Expr *Arg = ResultArg;
7079 bool ObjCLifetimeConversion;
7080
7081 // C++ [temp.arg.nontype]p1:
7082 //
7083 // A template-argument for a non-type, non-template
7084 // template-parameter shall be one of: [...]
7085 //
7086 // -- a pointer to member expressed as described in 5.3.1.
7087 DeclRefExpr *DRE = nullptr;
7088
7089 // In C++98/03 mode, give an extension warning on any extra parentheses.
7090 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7091 bool ExtraParens = false;
7092 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7093 if (!Invalid && !ExtraParens) {
7094 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7095 << Arg->getSourceRange();
7096 ExtraParens = true;
7097 }
7098
7099 Arg = Parens->getSubExpr();
7100 }
7101
7102 while (SubstNonTypeTemplateParmExpr *subst =
7103 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7104 Arg = subst->getReplacement()->IgnoreImpCasts();
7105
7106 // A pointer-to-member constant written &Class::member.
7107 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7108 if (UnOp->getOpcode() == UO_AddrOf) {
7109 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7110 if (DRE && !DRE->getQualifier())
7111 DRE = nullptr;
7112 }
7113 }
7114 // A constant of pointer-to-member type.
7115 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7116 ValueDecl *VD = DRE->getDecl();
7117 if (VD->getType()->isMemberPointerType()) {
7119 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7120 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7121 CanonicalConverted =
7122 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7123 } else {
7124 SugaredConverted = TemplateArgument(VD, ParamType);
7125 CanonicalConverted =
7127 S.Context.getCanonicalType(ParamType));
7128 }
7129 return Invalid;
7130 }
7131 }
7132
7133 DRE = nullptr;
7134 }
7135
7136 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7137
7138 // Check for a null pointer value.
7139 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7140 Entity)) {
7141 case NPV_Error:
7142 return true;
7143 case NPV_NullPointer:
7144 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7145 SugaredConverted = TemplateArgument(ParamType,
7146 /*isNullPtr*/ true);
7147 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7148 /*isNullPtr*/ true);
7149 return false;
7150 case NPV_NotNullPointer:
7151 break;
7152 }
7153
7154 if (S.IsQualificationConversion(ResultArg->getType(),
7155 ParamType.getNonReferenceType(), false,
7156 ObjCLifetimeConversion)) {
7157 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7158 ResultArg->getValueKind())
7159 .get();
7160 } else if (!S.Context.hasSameUnqualifiedType(
7161 ResultArg->getType(), ParamType.getNonReferenceType())) {
7162 // We can't perform this conversion.
7163 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7164 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7166 return true;
7167 }
7168
7169 if (!DRE)
7170 return S.Diag(Arg->getBeginLoc(),
7171 diag::err_template_arg_not_pointer_to_member_form)
7172 << Arg->getSourceRange();
7173
7174 if (isa<FieldDecl>(DRE->getDecl()) ||
7176 isa<CXXMethodDecl>(DRE->getDecl())) {
7177 assert((isa<FieldDecl>(DRE->getDecl()) ||
7180 ->isImplicitObjectMemberFunction()) &&
7181 "Only non-static member pointers can make it here");
7182
7183 // Okay: this is the address of a non-static member, and therefore
7184 // a member pointer constant.
7185 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7186 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7187 CanonicalConverted =
7188 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7189 } else {
7190 ValueDecl *D = DRE->getDecl();
7191 SugaredConverted = TemplateArgument(D, ParamType);
7192 CanonicalConverted =
7194 S.Context.getCanonicalType(ParamType));
7195 }
7196 return Invalid;
7197 }
7198
7199 // We found something else, but we don't know specifically what it is.
7200 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7201 << Arg->getSourceRange();
7202 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7203 return true;
7204}
7205
7206/// Check a template argument against its corresponding
7207/// non-type template parameter.
7208///
7209/// This routine implements the semantics of C++ [temp.arg.nontype].
7210/// If an error occurred, it returns ExprError(); otherwise, it
7211/// returns the converted template argument. \p ParamType is the
7212/// type of the non-type template parameter after it has been instantiated.
7214 Expr *Arg,
7215 TemplateArgument &SugaredConverted,
7216 TemplateArgument &CanonicalConverted,
7217 bool StrictCheck,
7219 SourceLocation StartLoc = Arg->getBeginLoc();
7220 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7221 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7222 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7223 DeductionArg = NewDeductionArg;
7224 if (ArgPE) {
7225 // Recreate a pack expansion if we unwrapped one.
7226 Arg = new (Context) PackExpansionExpr(
7227 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7228 } else {
7229 Arg = DeductionArg;
7230 }
7231 };
7232
7233 // If the parameter type somehow involves auto, deduce the type now.
7234 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7235 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7236 if (IsDeduced) {
7237 // When checking a deduced template argument, deduce from its type even if
7238 // the type is dependent, in order to check the types of non-type template
7239 // arguments line up properly in partial ordering.
7240 TypeSourceInfo *TSI =
7241 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7243 InitializedEntity Entity =
7246 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7247 Expr *Inits[1] = {DeductionArg};
7248 ParamType =
7250 if (ParamType.isNull())
7251 return ExprError();
7252 } else {
7253 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7254 Param->getTemplateDepth() + 1);
7255 ParamType = QualType();
7257 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7258 /*DependentDeduction=*/true,
7259 // We do not check constraints right now because the
7260 // immediately-declared constraint of the auto type is
7261 // also an associated constraint, and will be checked
7262 // along with the other associated constraints after
7263 // checking the template argument list.
7264 /*IgnoreConstraints=*/true);
7266 ParamType = TSI->getType();
7267 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7269 return ExprError();
7270 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7271 Diag(Arg->getExprLoc(),
7272 diag::err_non_type_template_parm_type_deduction_failure)
7273 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7274 << Arg->getSourceRange();
7276 return ExprError();
7277 }
7278 ParamType = SubstAutoTypeDependent(ParamType);
7279 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7280 }
7281 }
7282 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7283 // an error. The error message normally references the parameter
7284 // declaration, but here we'll pass the argument location because that's
7285 // where the parameter type is deduced.
7286 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7287 if (ParamType.isNull()) {
7289 return ExprError();
7290 }
7291 }
7292
7293 // We should have already dropped all cv-qualifiers by now.
7294 assert(!ParamType.hasQualifiers() &&
7295 "non-type template parameter type cannot be qualified");
7296
7297 // If either the parameter has a dependent type or the argument is
7298 // type-dependent, there's nothing we can check now.
7299 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7300 // Force the argument to the type of the parameter to maintain invariants.
7301 if (!IsDeduced) {
7303 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7304 ParamType->isLValueReferenceType() ? VK_LValue
7305 : ParamType->isRValueReferenceType() ? VK_XValue
7306 : VK_PRValue);
7307 if (E.isInvalid())
7308 return ExprError();
7309 setDeductionArg(E.get());
7310 }
7311 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7312 CanonicalConverted = TemplateArgument(
7313 Context.getCanonicalTemplateArgument(SugaredConverted));
7314 return Arg;
7315 }
7316
7317 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7318 if (CTAK == CTAK_Deduced && !StrictCheck &&
7319 (ParamType->isReferenceType()
7320 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7321 DeductionArg->getType())
7322 : !Context.hasSameUnqualifiedType(ParamType,
7323 DeductionArg->getType()))) {
7324 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7325 // we should actually be checking the type of the template argument in P,
7326 // not the type of the template argument deduced from A, against the
7327 // template parameter type.
7328 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7329 << Arg->getType() << ParamType.getUnqualifiedType();
7331 return ExprError();
7332 }
7333
7334 // If the argument is a pack expansion, we don't know how many times it would
7335 // expand. If we continue checking the argument, this will make the template
7336 // definition ill-formed if it would be ill-formed for any number of
7337 // expansions during instantiation time. When partial ordering or matching
7338 // template template parameters, this is exactly what we want. Otherwise, the
7339 // normal template rules apply: we accept the template if it would be valid
7340 // for any number of expansions (i.e. none).
7341 if (ArgPE && !StrictCheck) {
7342 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7343 CanonicalConverted = TemplateArgument(
7344 Context.getCanonicalTemplateArgument(SugaredConverted));
7345 return Arg;
7346 }
7347
7348 // Avoid making a copy when initializing a template parameter of class type
7349 // from a template parameter object of the same type. This is going beyond
7350 // the standard, but is required for soundness: in
7351 // template<A a> struct X { X *p; X<a> *q; };
7352 // ... we need p and q to have the same type.
7353 //
7354 // Similarly, don't inject a call to a copy constructor when initializing
7355 // from a template parameter of the same type.
7356 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7357 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7358 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7359 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7360 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7361
7362 SugaredConverted = TemplateArgument(TPO, ParamType);
7363 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7364 ParamType.getCanonicalType());
7365 return Arg;
7366 }
7368 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7369 CanonicalConverted =
7370 Context.getCanonicalTemplateArgument(SugaredConverted);
7371 return Arg;
7372 }
7373 }
7374
7375 // The initialization of the parameter from the argument is
7376 // a constant-evaluated context.
7379
7380 bool IsConvertedConstantExpression = true;
7381 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7383 StartLoc, /*DirectInit=*/false, DeductionArg);
7384 Expr *Inits[1] = {DeductionArg};
7385 InitializedEntity Entity =
7387 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7388 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7389 if (Result.isInvalid() || !Result.get())
7390 return ExprError();
7392 if (Result.isInvalid() || !Result.get())
7393 return ExprError();
7394 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7395 /*DiscardedValue=*/false,
7396 /*IsConstexpr=*/true,
7397 /*IsTemplateArgument=*/true)
7398 .get());
7399 IsConvertedConstantExpression = false;
7400 }
7401
7402 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7403 // C++17 [temp.arg.nontype]p1:
7404 // A template-argument for a non-type template parameter shall be
7405 // a converted constant expression of the type of the template-parameter.
7406 APValue Value;
7407 ExprResult ArgResult;
7408 if (IsConvertedConstantExpression) {
7410 DeductionArg, ParamType,
7411 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7412 assert(!ArgResult.isUnset());
7413 if (ArgResult.isInvalid()) {
7415 return ExprError();
7416 }
7417 } else {
7418 ArgResult = DeductionArg;
7419 }
7420
7421 // For a value-dependent argument, CheckConvertedConstantExpression is
7422 // permitted (and expected) to be unable to determine a value.
7423 if (ArgResult.get()->isValueDependent()) {
7424 setDeductionArg(ArgResult.get());
7425 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7426 CanonicalConverted =
7427 Context.getCanonicalTemplateArgument(SugaredConverted);
7428 return Arg;
7429 }
7430
7431 APValue PreNarrowingValue;
7433 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7434 false, PreNarrowingValue);
7435 if (ArgResult.isInvalid())
7436 return ExprError();
7437 setDeductionArg(ArgResult.get());
7438
7439 if (Value.isLValue()) {
7440 APValue::LValueBase Base = Value.getLValueBase();
7441 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7442 // For a non-type template-parameter of pointer or reference type,
7443 // the value of the constant expression shall not refer to
7444 assert(ParamType->isPointerOrReferenceType() ||
7445 ParamType->isNullPtrType());
7446 // -- a temporary object
7447 // -- a string literal
7448 // -- the result of a typeid expression, or
7449 // -- a predefined __func__ variable
7450 if (Base &&
7451 (!VD ||
7453 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7454 << Arg->getSourceRange();
7455 return ExprError();
7456 }
7457
7458 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7459 VD->getType()->isArrayType() &&
7460 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7461 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7462 if (ArgPE) {
7463 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7464 CanonicalConverted =
7465 Context.getCanonicalTemplateArgument(SugaredConverted);
7466 } else {
7467 SugaredConverted = TemplateArgument(VD, ParamType);
7468 CanonicalConverted =
7469 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7470 ParamType.getCanonicalType());
7471 }
7472 return Arg;
7473 }
7474
7475 // -- a subobject [until C++20]
7476 if (!getLangOpts().CPlusPlus20) {
7477 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7478 Value.isLValueOnePastTheEnd()) {
7479 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7480 << Value.getAsString(Context, ParamType);
7481 return ExprError();
7482 }
7483 assert((VD || !ParamType->isReferenceType()) &&
7484 "null reference should not be a constant expression");
7485 assert((!VD || !ParamType->isNullPtrType()) &&
7486 "non-null value of type nullptr_t?");
7487 }
7488 }
7489
7490 if (Value.isAddrLabelDiff())
7491 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7492
7493 if (ArgPE) {
7494 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7495 CanonicalConverted =
7496 Context.getCanonicalTemplateArgument(SugaredConverted);
7497 } else {
7498 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7499 CanonicalConverted =
7501 }
7502 return Arg;
7503 }
7504
7505 // These should have all been handled above using the C++17 rules.
7506 assert(!ArgPE && !StrictCheck);
7507
7508 // C++ [temp.arg.nontype]p5:
7509 // The following conversions are performed on each expression used
7510 // as a non-type template-argument. If a non-type
7511 // template-argument cannot be converted to the type of the
7512 // corresponding template-parameter then the program is
7513 // ill-formed.
7514 if (ParamType->isIntegralOrEnumerationType()) {
7515 // C++11:
7516 // -- for a non-type template-parameter of integral or
7517 // enumeration type, conversions permitted in a converted
7518 // constant expression are applied.
7519 //
7520 // C++98:
7521 // -- for a non-type template-parameter of integral or
7522 // enumeration type, integral promotions (4.5) and integral
7523 // conversions (4.7) are applied.
7524
7525 if (getLangOpts().CPlusPlus11) {
7526 // C++ [temp.arg.nontype]p1:
7527 // A template-argument for a non-type, non-template template-parameter
7528 // shall be one of:
7529 //
7530 // -- for a non-type template-parameter of integral or enumeration
7531 // type, a converted constant expression of the type of the
7532 // template-parameter; or
7533 llvm::APSInt Value;
7535 Arg, ParamType, Value, CCEKind::TemplateArg);
7536 if (ArgResult.isInvalid())
7537 return ExprError();
7538 Arg = ArgResult.get();
7539
7540 // We can't check arbitrary value-dependent arguments.
7541 if (Arg->isValueDependent()) {
7542 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7543 CanonicalConverted =
7544 Context.getCanonicalTemplateArgument(SugaredConverted);
7545 return Arg;
7546 }
7547
7548 // Widen the argument value to sizeof(parameter type). This is almost
7549 // always a no-op, except when the parameter type is bool. In
7550 // that case, this may extend the argument from 1 bit to 8 bits.
7551 QualType IntegerType = ParamType;
7552 if (const auto *ED = IntegerType->getAsEnumDecl())
7553 IntegerType = ED->getIntegerType();
7554 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7555 ? Context.getIntWidth(IntegerType)
7556 : Context.getTypeSize(IntegerType));
7557
7558 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7559 CanonicalConverted =
7560 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7561 return Arg;
7562 }
7563
7564 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7565 if (ArgResult.isInvalid())
7566 return ExprError();
7567 Arg = ArgResult.get();
7568
7569 QualType ArgType = Arg->getType();
7570
7571 // C++ [temp.arg.nontype]p1:
7572 // A template-argument for a non-type, non-template
7573 // template-parameter shall be one of:
7574 //
7575 // -- an integral constant-expression of integral or enumeration
7576 // type; or
7577 // -- the name of a non-type template-parameter; or
7578 llvm::APSInt Value;
7579 if (!ArgType->isIntegralOrEnumerationType()) {
7580 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7581 << ArgType << Arg->getSourceRange();
7583 return ExprError();
7584 }
7585 if (!Arg->isValueDependent()) {
7586 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7587 QualType T;
7588
7589 public:
7590 TmplArgICEDiagnoser(QualType T) : T(T) { }
7591
7592 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7593 SourceLocation Loc) override {
7594 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7595 }
7596 } Diagnoser(ArgType);
7597
7598 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7599 if (!Arg)
7600 return ExprError();
7601 }
7602
7603 // From here on out, all we care about is the unqualified form
7604 // of the argument type.
7605 ArgType = ArgType.getUnqualifiedType();
7606
7607 // Try to convert the argument to the parameter's type.
7608 if (Context.hasSameType(ParamType, ArgType)) {
7609 // Okay: no conversion necessary
7610 } else if (ParamType->isBooleanType()) {
7611 // This is an integral-to-boolean conversion.
7612 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7613 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7614 !ParamType->isEnumeralType()) {
7615 // This is an integral promotion or conversion.
7616 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7617 } else {
7618 // We can't perform this conversion.
7619 Diag(StartLoc, diag::err_template_arg_not_convertible)
7620 << Arg->getType() << ParamType << Arg->getSourceRange();
7622 return ExprError();
7623 }
7624
7625 // Add the value of this argument to the list of converted
7626 // arguments. We use the bitwidth and signedness of the template
7627 // parameter.
7628 if (Arg->isValueDependent()) {
7629 // The argument is value-dependent. Create a new
7630 // TemplateArgument with the converted expression.
7631 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7632 CanonicalConverted =
7633 Context.getCanonicalTemplateArgument(SugaredConverted);
7634 return Arg;
7635 }
7636
7637 QualType IntegerType = ParamType;
7638 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7639 IntegerType = ED->getIntegerType();
7640 }
7641
7642 if (ParamType->isBooleanType()) {
7643 // Value must be zero or one.
7644 Value = Value != 0;
7645 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7646 if (Value.getBitWidth() != AllowedBits)
7647 Value = Value.extOrTrunc(AllowedBits);
7648 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7649 } else {
7650 llvm::APSInt OldValue = Value;
7651
7652 // Coerce the template argument's value to the value it will have
7653 // based on the template parameter's type.
7654 unsigned AllowedBits = IntegerType->isBitIntType()
7655 ? Context.getIntWidth(IntegerType)
7656 : Context.getTypeSize(IntegerType);
7657 if (Value.getBitWidth() != AllowedBits)
7658 Value = Value.extOrTrunc(AllowedBits);
7659 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7660
7661 // Complain if an unsigned parameter received a negative value.
7662 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7663 (OldValue.isSigned() && OldValue.isNegative())) {
7664 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7665 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7666 << Arg->getSourceRange();
7668 }
7669
7670 // Complain if we overflowed the template parameter's type.
7671 unsigned RequiredBits;
7672 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7673 RequiredBits = OldValue.getActiveBits();
7674 else if (OldValue.isUnsigned())
7675 RequiredBits = OldValue.getActiveBits() + 1;
7676 else
7677 RequiredBits = OldValue.getSignificantBits();
7678 if (RequiredBits > AllowedBits) {
7679 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7680 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7681 << Arg->getSourceRange();
7683 }
7684 }
7685
7686 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7687 SugaredConverted = TemplateArgument(Context, Value, T);
7688 CanonicalConverted =
7689 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7690 return Arg;
7691 }
7692
7693 QualType ArgType = Arg->getType();
7694 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7695 bool IsSpecified = CTAK == CTAK_Specified;
7696
7697 // Handle pointer-to-function, reference-to-function, and
7698 // pointer-to-member-function all in (roughly) the same way.
7699 if (// -- For a non-type template-parameter of type pointer to
7700 // function, only the function-to-pointer conversion (4.3) is
7701 // applied. If the template-argument represents a set of
7702 // overloaded functions (or a pointer to such), the matching
7703 // function is selected from the set (13.4).
7704 (ParamType->isPointerType() &&
7705 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7706 // -- For a non-type template-parameter of type reference to
7707 // function, no conversions apply. If the template-argument
7708 // represents a set of overloaded functions, the matching
7709 // function is selected from the set (13.4).
7710 (ParamType->isReferenceType() &&
7711 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7712 // -- For a non-type template-parameter of type pointer to
7713 // member function, no conversions apply. If the
7714 // template-argument represents a set of overloaded member
7715 // functions, the matching member function is selected from
7716 // the set (13.4).
7717 (ParamType->isMemberPointerType() &&
7718 ParamType->castAs<MemberPointerType>()->getPointeeType()
7719 ->isFunctionType())) {
7720
7721 if (Arg->getType() == Context.OverloadTy) {
7722 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7723 true,
7724 FoundResult)) {
7725 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7726 return ExprError();
7727
7728 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7729 if (Res.isInvalid())
7730 return ExprError();
7731 Arg = Res.get();
7732 ArgType = Arg->getType();
7733 } else
7734 return ExprError();
7735 }
7736
7737 if (!ParamType->isMemberPointerType()) {
7739 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7740 CanonicalConverted))
7741 return ExprError();
7742 return Arg;
7743 }
7744
7746 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7747 return ExprError();
7748 return Arg;
7749 }
7750
7751 if (ParamType->isPointerType()) {
7752 // -- for a non-type template-parameter of type pointer to
7753 // object, qualification conversions (4.4) and the
7754 // array-to-pointer conversion (4.2) are applied.
7755 // C++0x also allows a value of std::nullptr_t.
7756 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7757 "Only object pointers allowed here");
7758
7760 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7761 CanonicalConverted))
7762 return ExprError();
7763 return Arg;
7764 }
7765
7766 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7767 // -- For a non-type template-parameter of type reference to
7768 // object, no conversions apply. The type referred to by the
7769 // reference may be more cv-qualified than the (otherwise
7770 // identical) type of the template-argument. The
7771 // template-parameter is bound directly to the
7772 // template-argument, which must be an lvalue.
7773 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7774 "Only object references allowed here");
7775
7776 if (Arg->getType() == Context.OverloadTy) {
7778 ParamRefType->getPointeeType(),
7779 true,
7780 FoundResult)) {
7781 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7782 return ExprError();
7783 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7784 if (Res.isInvalid())
7785 return ExprError();
7786 Arg = Res.get();
7787 ArgType = Arg->getType();
7788 } else
7789 return ExprError();
7790 }
7791
7793 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7794 CanonicalConverted))
7795 return ExprError();
7796 return Arg;
7797 }
7798
7799 // Deal with parameters of type std::nullptr_t.
7800 if (ParamType->isNullPtrType()) {
7801 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7802 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7803 CanonicalConverted =
7804 Context.getCanonicalTemplateArgument(SugaredConverted);
7805 return Arg;
7806 }
7807
7808 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7809 case NPV_NotNullPointer:
7810 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7811 << Arg->getType() << ParamType;
7813 return ExprError();
7814
7815 case NPV_Error:
7816 return ExprError();
7817
7818 case NPV_NullPointer:
7819 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7820 SugaredConverted = TemplateArgument(ParamType,
7821 /*isNullPtr=*/true);
7822 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7823 /*isNullPtr=*/true);
7824 return Arg;
7825 }
7826 }
7827
7828 // -- For a non-type template-parameter of type pointer to data
7829 // member, qualification conversions (4.4) are applied.
7830 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7831
7833 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7834 return ExprError();
7835 return Arg;
7836}
7837
7841
7844 const TemplateArgumentLoc &Arg) {
7845 // C++0x [temp.arg.template]p1:
7846 // A template-argument for a template template-parameter shall be
7847 // the name of a class template or an alias template, expressed as an
7848 // id-expression. When the template-argument names a class template, only
7849 // primary class templates are considered when matching the
7850 // template template argument with the corresponding parameter;
7851 // partial specializations are not considered even if their
7852 // parameter lists match that of the template template parameter.
7853 //
7854
7856 unsigned DiagFoundKind = 0;
7857
7858 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7859 switch (TTP->templateParameterKind()) {
7861 DiagFoundKind = 3;
7862 break;
7864 DiagFoundKind = 2;
7865 break;
7866 default:
7867 DiagFoundKind = 1;
7868 break;
7869 }
7870 Kind = TTP->templateParameterKind();
7871 } else if (isa<ConceptDecl>(Template)) {
7873 DiagFoundKind = 3;
7874 } else if (isa<FunctionTemplateDecl>(Template)) {
7876 DiagFoundKind = 0;
7877 } else if (isa<VarTemplateDecl>(Template)) {
7879 DiagFoundKind = 2;
7880 } else if (isa<ClassTemplateDecl>(Template) ||
7884 DiagFoundKind = 1;
7885 } else {
7886 assert(false && "Unexpected Decl");
7887 }
7888
7889 if (Kind == Param->templateParameterKind()) {
7890 return true;
7891 }
7892
7893 unsigned DiagKind = 0;
7894 switch (Param->templateParameterKind()) {
7896 DiagKind = 2;
7897 break;
7899 DiagKind = 1;
7900 break;
7901 default:
7902 DiagKind = 0;
7903 break;
7904 }
7905 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7906 << DiagKind;
7907 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7908 << DiagFoundKind << Template;
7909 return false;
7910}
7911
7912/// Check a template argument against its corresponding
7913/// template template parameter.
7914///
7915/// This routine implements the semantics of C++ [temp.arg.template].
7916/// It returns true if an error occurred, and false otherwise.
7918 TemplateParameterList *Params,
7920 bool PartialOrdering,
7921 bool *StrictPackMatch) {
7923 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7924 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7925 if (!Template) {
7926 // FIXME: Handle AssumedTemplateNames
7927 // Any dependent template name is fine.
7928 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7929 return false;
7930 }
7931
7932 if (Template->isInvalidDecl())
7933 return true;
7934
7936 return true;
7937 }
7938
7939 // C++1z [temp.arg.template]p3: (DR 150)
7940 // A template-argument matches a template template-parameter P when P
7941 // is at least as specialized as the template-argument A.
7943 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7944 PartialOrdering, StrictPackMatch))
7945 return true;
7946 // P2113
7947 // C++20[temp.func.order]p2
7948 // [...] If both deductions succeed, the partial ordering selects the
7949 // more constrained template (if one exists) as determined below.
7950 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7951 Params->getAssociatedConstraints(ParamsAC);
7952 // C++20[temp.arg.template]p3
7953 // [...] In this comparison, if P is unconstrained, the constraints on A
7954 // are not considered.
7955 if (ParamsAC.empty())
7956 return false;
7957
7958 Template->getAssociatedConstraints(TemplateAC);
7959
7960 bool IsParamAtLeastAsConstrained;
7961 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7962 IsParamAtLeastAsConstrained))
7963 return true;
7964 if (!IsParamAtLeastAsConstrained) {
7965 Diag(Arg.getLocation(),
7966 diag::err_template_template_parameter_not_at_least_as_constrained)
7967 << Template << Param << Arg.getSourceRange();
7968 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7969 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7971 TemplateAC);
7972 return true;
7973 }
7974 return false;
7975}
7976
7978 unsigned HereDiagID,
7979 unsigned ExternalDiagID) {
7980 if (Decl.getLocation().isValid())
7981 return S.Diag(Decl.getLocation(), HereDiagID);
7982
7983 SmallString<128> Str;
7984 llvm::raw_svector_ostream Out(Str);
7986 PP.TerseOutput = 1;
7987 Decl.print(Out, PP);
7988 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7989}
7990
7992 std::optional<SourceRange> ParamRange) {
7994 noteLocation(*this, Decl, diag::note_template_decl_here,
7995 diag::note_template_decl_external);
7996 if (ParamRange && ParamRange->isValid()) {
7997 assert(Decl.getLocation().isValid() &&
7998 "Parameter range has location when Decl does not");
7999 DB << *ParamRange;
8000 }
8001}
8002
8004 noteLocation(*this, Decl, diag::note_template_param_here,
8005 diag::note_template_param_external);
8006}
8007
8008/// Given a non-type template argument that refers to a
8009/// declaration and the type of its corresponding non-type template
8010/// parameter, produce an expression that properly refers to that
8011/// declaration.
8013 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
8014 // C++ [temp.param]p8:
8015 //
8016 // A non-type template-parameter of type "array of T" or
8017 // "function returning T" is adjusted to be of type "pointer to
8018 // T" or "pointer to function returning T", respectively.
8019 if (ParamType->isArrayType())
8020 ParamType = Context.getArrayDecayedType(ParamType);
8021 else if (ParamType->isFunctionType())
8022 ParamType = Context.getPointerType(ParamType);
8023
8024 // For a NULL non-type template argument, return nullptr casted to the
8025 // parameter's type.
8026 if (Arg.getKind() == TemplateArgument::NullPtr) {
8027 return ImpCastExprToType(
8028 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8029 ParamType,
8030 ParamType->getAs<MemberPointerType>()
8031 ? CK_NullToMemberPointer
8032 : CK_NullToPointer);
8033 }
8034 assert(Arg.getKind() == TemplateArgument::Declaration &&
8035 "Only declaration template arguments permitted here");
8036
8037 ValueDecl *VD = Arg.getAsDecl();
8038
8039 CXXScopeSpec SS;
8040 if (ParamType->isMemberPointerType()) {
8041 // If this is a pointer to member, we need to use a qualified name to
8042 // form a suitable pointer-to-member constant.
8043 assert(VD->getDeclContext()->isRecord() &&
8044 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8046 CanQualType ClassType =
8047 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
8048 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
8049 SS.MakeTrivial(Context, Qualifier, Loc);
8050 }
8051
8053 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8054 if (RefExpr.isInvalid())
8055 return ExprError();
8056
8057 // For a pointer, the argument declaration is the pointee. Take its address.
8058 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8059 if (ParamType->isPointerType() && !ElemT.isNull() &&
8060 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8061 // Decay an array argument if we want a pointer to its first element.
8062 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8063 if (RefExpr.isInvalid())
8064 return ExprError();
8065 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8066 // For any other pointer, take the address (or form a pointer-to-member).
8067 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8068 if (RefExpr.isInvalid())
8069 return ExprError();
8070 } else if (ParamType->isRecordType()) {
8071 assert(isa<TemplateParamObjectDecl>(VD) &&
8072 "arg for class template param not a template parameter object");
8073 // No conversions apply in this case.
8074 return RefExpr;
8075 } else {
8076 assert(ParamType->isReferenceType() &&
8077 "unexpected type for decl template argument");
8078 // If the parameter has reference type, wrap it in paretheses so that this
8079 // expression will have the correct type under `decltype`.
8080 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8081 }
8082
8083 // At this point we should have the right value category.
8084 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8085 "value kind mismatch for non-type template argument");
8086
8087 // The type of the template parameter can differ from the type of the
8088 // argument in various ways; convert it now if necessary.
8089 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8090 QualType SrcExprType = RefExpr.get()->getType();
8091 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8092 CastKind CK;
8093 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8094 IsFunctionConversion(SrcExprType, DestExprType)) {
8095 CK = CK_NoOp;
8096 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8097 CK = CK_BitCast;
8098 } else {
8099 // FIXME: Pointers to members can need conversion derived-to-base or
8100 // base-to-derived conversions. We currently don't retain enough
8101 // information to convert properly (we need to track a cast path or
8102 // subobject number in the template argument).
8103 llvm_unreachable(
8104 "unexpected conversion required for non-type template argument");
8105 }
8106 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8107 RefExpr.get()->getValueKind());
8108 }
8109
8110 return RefExpr;
8111}
8112
8113/// Construct a new expression that refers to the given
8114/// integral template argument with the given source-location
8115/// information.
8116///
8117/// This routine takes care of the mapping from an integral template
8118/// argument (which may have any integral type) to the appropriate
8119/// literal value.
8121 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8122 assert(OrigT->isIntegralOrEnumerationType());
8123
8124 // If this is an enum type that we're instantiating, we need to use an integer
8125 // type the same size as the enumerator. We don't want to build an
8126 // IntegerLiteral with enum type. The integer type of an enum type can be of
8127 // any integral type with C++11 enum classes, make sure we create the right
8128 // type of literal for it.
8129 QualType T = OrigT;
8130 if (const auto *ED = OrigT->getAsEnumDecl())
8131 T = ED->getIntegerType();
8132
8133 Expr *E;
8134 if (T->isAnyCharacterType()) {
8136 if (T->isWideCharType())
8138 else if (T->isChar8Type() && S.getLangOpts().Char8)
8140 else if (T->isChar16Type())
8142 else if (T->isChar32Type())
8144 else
8146
8147 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8148 } else if (T->isBooleanType()) {
8149 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8150 } else {
8151 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8152 }
8153
8154 if (OrigT->isEnumeralType()) {
8155 // FIXME: This is a hack. We need a better way to handle substituted
8156 // non-type template parameters.
8157 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8158 nullptr, S.CurFPFeatureOverrides(),
8159 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8160 Loc, Loc);
8161 }
8162
8163 return E;
8164}
8165
8166/// Construct a new reflect expression that refers to the given
8167/// entity with the given source-location of the reflection operator.
8169 SourceLocation CaretCaretLoc) {
8170 // TODO(Reflection): Add support for NamespaceReference, TemplateReference,
8171 // and DeclRefExpr.
8173 S.Context, CaretCaretLoc,
8174 static_cast<TypeSourceInfo *>(
8175 const_cast<void *>(RV.getReflectionOpaqueOperand())));
8176}
8177
8179 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8180 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8181 auto *ILE = new (S.Context)
8182 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8183 ILE->setType(T);
8184 return ILE;
8185 };
8186
8187 switch (Val.getKind()) {
8189 // This cannot occur in a template argument at all.
8190 case APValue::Array:
8191 case APValue::Struct:
8192 case APValue::Union:
8193 // These can only occur within a template parameter object, which is
8194 // represented as a TemplateArgument::Declaration.
8195 llvm_unreachable("unexpected template argument value");
8196
8197 case APValue::Int:
8199 Loc);
8200
8201 case APValue::Float:
8202 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8203 T, Loc);
8204
8207 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8208 Val.getFixedPoint().getScale());
8209
8210 case APValue::ComplexInt: {
8211 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8213 S, ElemT, Val.getComplexIntReal(), Loc),
8215 S, ElemT, Val.getComplexIntImag(), Loc)});
8216 }
8217
8218 case APValue::ComplexFloat: {
8219 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8220 return MakeInitList(
8222 ElemT, Loc),
8224 ElemT, Loc)});
8225 }
8226
8227 case APValue::Vector: {
8228 QualType ElemT = T->castAs<VectorType>()->getElementType();
8230 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8232 S, ElemT, Val.getVectorElt(I), Loc));
8233 return MakeInitList(Elts);
8234 }
8235
8236 case APValue::Matrix:
8237 llvm_unreachable("Matrix template argument expression not yet supported");
8238
8239 case APValue::None:
8241 llvm_unreachable("Unexpected APValue kind.");
8242 case APValue::LValue:
8244 // There isn't necessarily a valid equivalent source-level syntax for
8245 // these; in particular, a naive lowering might violate access control.
8246 // So for now we lower to a ConstantExpr holding the value, wrapped around
8247 // an OpaqueValueExpr.
8248 // FIXME: We should have a better representation for this.
8250 if (T->isReferenceType()) {
8251 T = T->getPointeeType();
8252 VK = VK_LValue;
8253 }
8254 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8255 return ConstantExpr::Create(S.Context, OVE, Val);
8256 }
8258 return BuildExpressionFromReflection(S, Val, Loc).get();
8259 }
8260 llvm_unreachable("Unhandled APValue::ValueKind enum");
8261}
8262
8265 SourceLocation Loc) {
8266 switch (Arg.getKind()) {
8272 llvm_unreachable("not a non-type template argument");
8273
8275 return Arg.getAsExpr();
8276
8280 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8281
8284 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8285
8288 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8289 }
8290 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8291}
8292
8293/// Match two template parameters within template parameter lists.
8295 Sema &S, NamedDecl *New,
8296 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8297 const NamedDecl *OldInstFrom, bool Complain,
8299 // Check the actual kind (type, non-type, template).
8300 if (Old->getKind() != New->getKind()) {
8301 if (Complain) {
8302 unsigned NextDiag = diag::err_template_param_different_kind;
8303 if (TemplateArgLoc.isValid()) {
8304 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8305 NextDiag = diag::note_template_param_different_kind;
8306 }
8307 S.Diag(New->getLocation(), NextDiag)
8308 << (Kind != Sema::TPL_TemplateMatch);
8309 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8310 << (Kind != Sema::TPL_TemplateMatch);
8311 }
8312
8313 return false;
8314 }
8315
8316 // Check that both are parameter packs or neither are parameter packs.
8317 // However, if we are matching a template template argument to a
8318 // template template parameter, the template template parameter can have
8319 // a parameter pack where the template template argument does not.
8320 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8321 if (Complain) {
8322 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8323 if (TemplateArgLoc.isValid()) {
8324 S.Diag(TemplateArgLoc,
8325 diag::err_template_arg_template_params_mismatch);
8326 NextDiag = diag::note_template_parameter_pack_non_pack;
8327 }
8328
8329 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8331 : 2;
8332 S.Diag(New->getLocation(), NextDiag)
8333 << ParamKind << New->isParameterPack();
8334 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8335 << ParamKind << Old->isParameterPack();
8336 }
8337
8338 return false;
8339 }
8340 // For non-type template parameters, check the type of the parameter.
8341 if (NonTypeTemplateParmDecl *OldNTTP =
8342 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8344
8345 // If we are matching a template template argument to a template
8346 // template parameter and one of the non-type template parameter types
8347 // is dependent, then we must wait until template instantiation time
8348 // to actually compare the arguments.
8350 (!OldNTTP->getType()->isDependentType() &&
8351 !NewNTTP->getType()->isDependentType())) {
8352 // C++20 [temp.over.link]p6:
8353 // Two [non-type] template-parameters are equivalent [if] they have
8354 // equivalent types ignoring the use of type-constraints for
8355 // placeholder types
8356 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8357 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8358 if (!S.Context.hasSameType(OldType, NewType)) {
8359 if (Complain) {
8360 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8361 if (TemplateArgLoc.isValid()) {
8362 S.Diag(TemplateArgLoc,
8363 diag::err_template_arg_template_params_mismatch);
8364 NextDiag = diag::note_template_nontype_parm_different_type;
8365 }
8366 S.Diag(NewNTTP->getLocation(), NextDiag)
8367 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8368 S.Diag(OldNTTP->getLocation(),
8369 diag::note_template_nontype_parm_prev_declaration)
8370 << OldNTTP->getType();
8371 }
8372 return false;
8373 }
8374 }
8375 }
8376 // For template template parameters, check the template parameter types.
8377 // The template parameter lists of template template
8378 // parameters must agree.
8379 else if (TemplateTemplateParmDecl *OldTTP =
8380 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8382 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8383 return false;
8385 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8386 OldTTP->getTemplateParameters(), Complain,
8389 : Kind),
8390 TemplateArgLoc))
8391 return false;
8392 }
8393
8397 const Expr *NewC = nullptr, *OldC = nullptr;
8398
8400 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8401 NewC = TC->getImmediatelyDeclaredConstraint();
8402 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8403 OldC = TC->getImmediatelyDeclaredConstraint();
8404 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8405 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8406 ->getPlaceholderTypeConstraint())
8407 NewC = E;
8408 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8409 ->getPlaceholderTypeConstraint())
8410 OldC = E;
8411 } else
8412 llvm_unreachable("unexpected template parameter type");
8413
8414 auto Diagnose = [&] {
8415 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8416 diag::err_template_different_type_constraint);
8417 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8418 diag::note_template_prev_declaration) << /*declaration*/0;
8419 };
8420
8421 if (!NewC != !OldC) {
8422 if (Complain)
8423 Diagnose();
8424 return false;
8425 }
8426
8427 if (NewC) {
8428 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8429 NewC)) {
8430 if (Complain)
8431 Diagnose();
8432 return false;
8433 }
8434 }
8435 }
8436
8437 return true;
8438}
8439
8440/// Diagnose a known arity mismatch when comparing template argument
8441/// lists.
8442static
8447 SourceLocation TemplateArgLoc) {
8448 unsigned NextDiag = diag::err_template_param_list_different_arity;
8449 if (TemplateArgLoc.isValid()) {
8450 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8451 NextDiag = diag::note_template_param_list_different_arity;
8452 }
8453 S.Diag(New->getTemplateLoc(), NextDiag)
8454 << (New->size() > Old->size())
8455 << (Kind != Sema::TPL_TemplateMatch)
8456 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8457 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8458 << (Kind != Sema::TPL_TemplateMatch)
8459 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8460}
8461
8464 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8465 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8466 if (Old->size() != New->size()) {
8467 if (Complain)
8469 TemplateArgLoc);
8470
8471 return false;
8472 }
8473
8474 // C++0x [temp.arg.template]p3:
8475 // A template-argument matches a template template-parameter (call it P)
8476 // when each of the template parameters in the template-parameter-list of
8477 // the template-argument's corresponding class template or alias template
8478 // (call it A) matches the corresponding template parameter in the
8479 // template-parameter-list of P. [...]
8480 TemplateParameterList::iterator NewParm = New->begin();
8481 TemplateParameterList::iterator NewParmEnd = New->end();
8482 for (TemplateParameterList::iterator OldParm = Old->begin(),
8483 OldParmEnd = Old->end();
8484 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8485 if (NewParm == NewParmEnd) {
8486 if (Complain)
8488 TemplateArgLoc);
8489 return false;
8490 }
8491 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8492 OldInstFrom, Complain, Kind,
8493 TemplateArgLoc))
8494 return false;
8495 }
8496
8497 // Make sure we exhausted all of the arguments.
8498 if (NewParm != NewParmEnd) {
8499 if (Complain)
8501 TemplateArgLoc);
8502
8503 return false;
8504 }
8505
8506 if (Kind != TPL_TemplateParamsEquivalent) {
8507 const Expr *NewRC = New->getRequiresClause();
8508 const Expr *OldRC = Old->getRequiresClause();
8509
8510 auto Diagnose = [&] {
8511 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8512 diag::err_template_different_requires_clause);
8513 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8514 diag::note_template_prev_declaration) << /*declaration*/0;
8515 };
8516
8517 if (!NewRC != !OldRC) {
8518 if (Complain)
8519 Diagnose();
8520 return false;
8521 }
8522
8523 if (NewRC) {
8524 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8525 NewRC)) {
8526 if (Complain)
8527 Diagnose();
8528 return false;
8529 }
8530 }
8531 }
8532
8533 return true;
8534}
8535
8536bool
8538 if (!S)
8539 return false;
8540
8541 // Find the nearest enclosing declaration scope.
8542 S = S->getDeclParent();
8543
8544 // C++ [temp.pre]p6: [P2096]
8545 // A template, explicit specialization, or partial specialization shall not
8546 // have C linkage.
8547 DeclContext *Ctx = S->getEntity();
8548 if (Ctx && Ctx->isExternCContext()) {
8549 SourceRange Range =
8550 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8551 ? TemplateParams->getParam(0)->getSourceRange()
8552 : TemplateParams->getSourceRange();
8553 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8554 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8555 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8556 return true;
8557 }
8558 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8559
8560 // C++ [temp]p2:
8561 // A template-declaration can appear only as a namespace scope or
8562 // class scope declaration.
8563 // C++ [temp.expl.spec]p3:
8564 // An explicit specialization may be declared in any scope in which the
8565 // corresponding primary template may be defined.
8566 // C++ [temp.class.spec]p6: [P2096]
8567 // A partial specialization may be declared in any scope in which the
8568 // corresponding primary template may be defined.
8569 if (Ctx) {
8570 if (Ctx->isFileContext())
8571 return false;
8572 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8573 // C++ [temp.mem]p2:
8574 // A local class shall not have member templates.
8575
8576 // Trace the outer context chain, bypassing nested records and OpenMP
8577 // captured regions, to determine if the class in defined inside a
8578 // function or method.
8579 const DeclContext *OutCtx = RD->getDeclContext();
8580 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(OutCtx))
8581 OutCtx = OutCtx->getParent();
8582
8583 if (OutCtx && OutCtx->isFunctionOrMethod())
8584 return Diag(TemplateParams->getTemplateLoc(),
8585 diag::err_template_inside_local_class)
8586 << TemplateParams->getSourceRange();
8587
8588 return false;
8589 }
8590 }
8591
8592 return Diag(TemplateParams->getTemplateLoc(),
8593 diag::err_template_outside_namespace_or_class_scope)
8594 << TemplateParams->getSourceRange();
8595}
8596
8597/// Determine what kind of template specialization the given declaration
8598/// is.
8600 if (!D)
8601 return TSK_Undeclared;
8602
8603 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8604 return Record->getTemplateSpecializationKind();
8605 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8606 return Function->getTemplateSpecializationKind();
8607 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8608 return Var->getTemplateSpecializationKind();
8609
8610 return TSK_Undeclared;
8611}
8612
8613/// Check whether a specialization is well-formed in the current
8614/// context.
8615///
8616/// This routine determines whether a template specialization can be declared
8617/// in the current context (C++ [temp.expl.spec]p2).
8618///
8619/// \param S the semantic analysis object for which this check is being
8620/// performed.
8621///
8622/// \param Specialized the entity being specialized or instantiated, which
8623/// may be a kind of template (class template, function template, etc.) or
8624/// a member of a class template (member function, static data member,
8625/// member class).
8626///
8627/// \param PrevDecl the previous declaration of this entity, if any.
8628///
8629/// \param Loc the location of the explicit specialization or instantiation of
8630/// this entity.
8631///
8632/// \param IsPartialSpecialization whether this is a partial specialization of
8633/// a class template.
8634///
8635/// \returns true if there was an error that we cannot recover from, false
8636/// otherwise.
8638 NamedDecl *Specialized,
8639 NamedDecl *PrevDecl,
8640 SourceLocation Loc,
8642 // Keep these "kind" numbers in sync with the %select statements in the
8643 // various diagnostics emitted by this routine.
8644 int EntityKind = 0;
8645 if (isa<ClassTemplateDecl>(Specialized))
8646 EntityKind = IsPartialSpecialization? 1 : 0;
8647 else if (isa<VarTemplateDecl>(Specialized))
8648 EntityKind = IsPartialSpecialization ? 3 : 2;
8649 else if (isa<FunctionTemplateDecl>(Specialized))
8650 EntityKind = 4;
8651 else if (isa<CXXMethodDecl>(Specialized))
8652 EntityKind = 5;
8653 else if (isa<VarDecl>(Specialized))
8654 EntityKind = 6;
8655 else if (isa<RecordDecl>(Specialized))
8656 EntityKind = 7;
8657 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8658 EntityKind = 8;
8659 else {
8660 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8661 << S.getLangOpts().CPlusPlus11;
8662 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8663 return true;
8664 }
8665
8666 // C++ [temp.expl.spec]p2:
8667 // An explicit specialization may be declared in any scope in which
8668 // the corresponding primary template may be defined.
8670 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8671 << Specialized;
8672 return true;
8673 }
8674
8675 // C++ [temp.class.spec]p6:
8676 // A class template partial specialization may be declared in any
8677 // scope in which the primary template may be defined.
8678 DeclContext *SpecializedContext =
8679 Specialized->getDeclContext()->getRedeclContext();
8681
8682 // Make sure that this redeclaration (or definition) occurs in the same
8683 // scope or an enclosing namespace.
8684 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8685 : DC->Equals(SpecializedContext))) {
8686 if (isa<TranslationUnitDecl>(SpecializedContext))
8687 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8688 << EntityKind << Specialized;
8689 else {
8690 auto *ND = cast<NamedDecl>(SpecializedContext);
8691 int Diag = diag::err_template_spec_redecl_out_of_scope;
8692 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8693 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8694 S.Diag(Loc, Diag) << EntityKind << Specialized
8695 << ND << isa<CXXRecordDecl>(ND);
8696 }
8697
8698 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8699
8700 // Don't allow specializing in the wrong class during error recovery.
8701 // Otherwise, things can go horribly wrong.
8702 if (DC->isRecord())
8703 return true;
8704 }
8705
8706 return false;
8707}
8708
8710 if (!E->isTypeDependent())
8711 return SourceLocation();
8712 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8713 Checker.TraverseStmt(E);
8714 if (Checker.MatchLoc.isInvalid())
8715 return E->getSourceRange();
8716 return Checker.MatchLoc;
8717}
8718
8719static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8720 if (!TL.getType()->isDependentType())
8721 return SourceLocation();
8722 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8723 Checker.TraverseTypeLoc(TL);
8724 if (Checker.MatchLoc.isInvalid())
8725 return TL.getSourceRange();
8726 return Checker.MatchLoc;
8727}
8728
8729/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8730/// that checks non-type template partial specialization arguments.
8732 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8733 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8734 bool HasError = false;
8735 for (unsigned I = 0; I != NumArgs; ++I) {
8736 if (Args[I].getKind() == TemplateArgument::Pack) {
8738 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8739 Args[I].pack_size(), IsDefaultArgument))
8740 return true;
8741
8742 continue;
8743 }
8744
8745 if (Args[I].getKind() != TemplateArgument::Expression)
8746 continue;
8747
8748 Expr *ArgExpr = Args[I].getAsExpr();
8749 if (ArgExpr->containsErrors()) {
8750 HasError = true;
8751 continue;
8752 }
8753
8754 // We can have a pack expansion of any of the bullets below.
8755 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8756 ArgExpr = Expansion->getPattern();
8757
8758 // Strip off any implicit casts we added as part of type checking.
8759 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8760 ArgExpr = ICE->getSubExpr();
8761
8762 // C++ [temp.class.spec]p8:
8763 // A non-type argument is non-specialized if it is the name of a
8764 // non-type parameter. All other non-type arguments are
8765 // specialized.
8766 //
8767 // Below, we check the two conditions that only apply to
8768 // specialized non-type arguments, so skip any non-specialized
8769 // arguments.
8770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8771 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8772 continue;
8773
8774 if (isa<DependentTemplateIdExpr>(ArgExpr))
8775 continue;
8776
8777 // C++ [temp.class.spec]p9:
8778 // Within the argument list of a class template partial
8779 // specialization, the following restrictions apply:
8780 // -- A partially specialized non-type argument expression
8781 // shall not involve a template parameter of the partial
8782 // specialization except when the argument expression is a
8783 // simple identifier.
8784 // -- The type of a template parameter corresponding to a
8785 // specialized non-type argument shall not be dependent on a
8786 // parameter of the specialization.
8787 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8788 // We implement a compromise between the original rules and DR1315:
8789 // -- A specialized non-type template argument shall not be
8790 // type-dependent and the corresponding template parameter
8791 // shall have a non-dependent type.
8792 SourceRange ParamUseRange =
8793 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8794 if (ParamUseRange.isValid()) {
8795 if (IsDefaultArgument) {
8796 S.Diag(TemplateNameLoc,
8797 diag::err_dependent_non_type_arg_in_partial_spec);
8798 S.Diag(ParamUseRange.getBegin(),
8799 diag::note_dependent_non_type_default_arg_in_partial_spec)
8800 << ParamUseRange;
8801 } else {
8802 S.Diag(ParamUseRange.getBegin(),
8803 diag::err_dependent_non_type_arg_in_partial_spec)
8804 << ParamUseRange;
8805 }
8806 return true;
8807 }
8808
8809 ParamUseRange = findTemplateParameter(
8810 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8811 if (ParamUseRange.isValid()) {
8812 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8813 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8814 << Param->getType();
8816 return true;
8817 }
8818 }
8819
8820 return HasError;
8821}
8822
8824 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8825 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8826 // We have to be conservative when checking a template in a dependent
8827 // context.
8828 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8829 return false;
8830
8831 TemplateParameterList *TemplateParams =
8832 PrimaryTemplate->getTemplateParameters();
8833 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8835 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8836 if (!Param)
8837 continue;
8838
8839 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8840 Param, &TemplateArgs[I],
8841 1, I >= NumExplicit))
8842 return true;
8843 }
8844
8845 return false;
8846}
8847
8849 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8850 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8852 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8853 assert(TUK != TagUseKind::Reference && "References are not specializations");
8854
8855 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8856 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8857 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8858
8859 // Find the class template we're specializing
8860 TemplateName Name = TemplateId.Template.get();
8862 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8863
8864 if (!ClassTemplate) {
8865 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8866 << (Name.getAsTemplateDecl() &&
8868 return true;
8869 }
8870
8871 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8872 auto Message = DSA->getMessage();
8873 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8874 << ClassTemplate << !Message.empty() << Message;
8875 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8876 }
8877
8878 if (S->isTemplateParamScope())
8879 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8880
8881 DeclContext *DC = ClassTemplate->getDeclContext();
8882
8883 bool isMemberSpecialization = false;
8884 bool isPartialSpecialization = false;
8885
8886 if (SS.isSet()) {
8887 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8888 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8889 TemplateNameLoc, &TemplateId,
8890 /*IsMemberSpecialization=*/false))
8891 return true;
8892 }
8893
8894 // Check the validity of the template headers that introduce this
8895 // template.
8896 // FIXME: We probably shouldn't complain about these headers for
8897 // friend declarations.
8898 bool Invalid = false;
8899 TemplateParameterList *TemplateParams =
8901 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8902 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8903 if (Invalid)
8904 return true;
8905
8906 // Check that we can declare a template specialization here.
8907 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8908 return true;
8909
8910 if (TemplateParams && DC->isDependentContext()) {
8911 ContextRAII SavedContext(*this, DC);
8913 return true;
8914 }
8915
8916 if (TemplateParams && TemplateParams->size() > 0) {
8917 isPartialSpecialization = true;
8918
8919 if (TUK == TagUseKind::Friend) {
8920 Diag(KWLoc, diag::err_partial_specialization_friend)
8921 << SourceRange(LAngleLoc, RAngleLoc);
8922 return true;
8923 }
8924
8925 // C++ [temp.class.spec]p10:
8926 // The template parameter list of a specialization shall not
8927 // contain default template argument values.
8928 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8929 Decl *Param = TemplateParams->getParam(I);
8930 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8931 if (TTP->hasDefaultArgument()) {
8932 Diag(TTP->getDefaultArgumentLoc(),
8933 diag::err_default_arg_in_partial_spec);
8934 TTP->removeDefaultArgument();
8935 }
8936 } else if (NonTypeTemplateParmDecl *NTTP
8937 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8938 if (NTTP->hasDefaultArgument()) {
8939 Diag(NTTP->getDefaultArgumentLoc(),
8940 diag::err_default_arg_in_partial_spec)
8941 << NTTP->getDefaultArgument().getSourceRange();
8942 NTTP->removeDefaultArgument();
8943 }
8944 } else {
8946 if (TTP->hasDefaultArgument()) {
8948 diag::err_default_arg_in_partial_spec)
8950 TTP->removeDefaultArgument();
8951 }
8952 }
8953 }
8954 } else if (TemplateParams) {
8955 if (TUK == TagUseKind::Friend)
8956 Diag(KWLoc, diag::err_template_spec_friend)
8958 SourceRange(TemplateParams->getTemplateLoc(),
8959 TemplateParams->getRAngleLoc()))
8960 << SourceRange(LAngleLoc, RAngleLoc);
8961 } else {
8962 assert(TUK == TagUseKind::Friend &&
8963 "should have a 'template<>' for this decl");
8964 }
8965
8966 // Check that the specialization uses the same tag kind as the
8967 // original template.
8969 assert(Kind != TagTypeKind::Enum &&
8970 "Invalid enum tag in class template spec!");
8971 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8972 TUK == TagUseKind::Definition, KWLoc,
8973 ClassTemplate->getIdentifier())) {
8974 Diag(KWLoc, diag::err_use_with_wrong_tag)
8975 << ClassTemplate
8977 ClassTemplate->getTemplatedDecl()->getKindName());
8978 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8979 diag::note_previous_use);
8980 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8981 }
8982
8983 // Translate the parser's template argument list in our AST format.
8984 TemplateArgumentListInfo TemplateArgs =
8985 makeTemplateArgumentListInfo(*this, TemplateId);
8986
8987 // Check for unexpanded parameter packs in any of the template arguments.
8988 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8989 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8990 isPartialSpecialization
8993 return true;
8994
8995 // Check that the template argument list is well-formed for this
8996 // template.
8998 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8999 /*DefaultArgs=*/{},
9000 /*PartialTemplateArgs=*/false, CTAI,
9001 /*UpdateArgsWithConversions=*/true))
9002 return true;
9003
9004 // Find the class template (partial) specialization declaration that
9005 // corresponds to these arguments.
9006 if (isPartialSpecialization) {
9008 TemplateArgs.size(),
9009 CTAI.CanonicalConverted))
9010 return true;
9011
9012 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9013 // also do it during instantiation.
9014 if (!Name.isDependent() &&
9015 !TemplateSpecializationType::anyDependentTemplateArguments(
9016 TemplateArgs, CTAI.CanonicalConverted)) {
9017 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9018 << ClassTemplate->getDeclName();
9019 isPartialSpecialization = false;
9020 Invalid = true;
9021 }
9022 }
9023
9024 llvm::FoldingSetInsertToken InsertToken;
9025 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9026
9027 if (isPartialSpecialization)
9028 PrevDecl = ClassTemplate->findPartialSpecialization(
9029 CTAI.CanonicalConverted, TemplateParams, InsertToken);
9030 else
9031 PrevDecl =
9032 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
9033
9035
9036 // Check whether we can declare a class template specialization in
9037 // the current scope.
9038 if (TUK != TagUseKind::Friend &&
9040 TemplateNameLoc,
9041 isPartialSpecialization))
9042 return true;
9043
9044 if (!isPartialSpecialization) {
9045 // Create a new class template specialization declaration node for
9046 // this explicit specialization or friend declaration.
9048 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9049 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
9050 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9052 if (TemplateParameterLists.size() > 0) {
9053 Specialization->setTemplateParameterListsInfo(Context,
9054 TemplateParameterLists);
9055 }
9056
9057 if (!PrevDecl)
9058 ClassTemplate->AddSpecialization(Specialization, InsertToken);
9059 } else {
9061 Context.getCanonicalTemplateSpecializationType(
9063 TemplateName(ClassTemplate->getCanonicalDecl()),
9064 CTAI.CanonicalConverted));
9065 if (Context.hasSameType(
9066 CanonType,
9067 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
9068 (!Context.getLangOpts().CPlusPlus20 ||
9069 !TemplateParams->hasAssociatedConstraints())) {
9070 // C++ [temp.class.spec]p9b3:
9071 //
9072 // -- The argument list of the specialization shall not be identical
9073 // to the implicit argument list of the primary template.
9074 //
9075 // This rule has since been removed, because it's redundant given DR1495,
9076 // but we keep it because it produces better diagnostics and recovery.
9077 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9078 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9079 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9080 return CheckClassTemplate(
9081 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9082 TemplateNameLoc, Attr, TemplateParams, AS_none,
9083 /*ModulePrivateLoc=*/SourceLocation(),
9084 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9085 TemplateParameterLists.data(), isMemberSpecialization);
9086 }
9087
9088 // Create a new class template partial specialization declaration node.
9090 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9093 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9094 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9095 Partial->setTemplateArgsAsWritten(TemplateArgs);
9096 SetNestedNameSpecifier(*this, Partial, SS);
9097 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9099 Context, TemplateParameterLists.drop_back(1));
9100 }
9101
9102 if (!PrevPartial)
9103 ClassTemplate->AddPartialSpecialization(Partial, InsertToken);
9104 Specialization = Partial;
9105
9106 // If we are providing an explicit specialization of a member class
9107 // template specialization, make a note of that.
9108 if (isMemberSpecialization)
9109 Partial->setMemberSpecialization();
9110
9112 }
9113
9114 // C++ [temp.expl.spec]p6:
9115 // If a template, a member template or the member of a class template is
9116 // explicitly specialized then that specialization shall be declared
9117 // before the first use of that specialization that would cause an implicit
9118 // instantiation to take place, in every translation unit in which such a
9119 // use occurs; no diagnostic is required.
9120 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9121 bool Okay = false;
9122 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9123 // Is there any previous explicit specialization declaration?
9125 Okay = true;
9126 break;
9127 }
9128 }
9129
9130 if (!Okay) {
9131 SourceRange Range(TemplateNameLoc, RAngleLoc);
9132 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9133 << Context.getCanonicalTagType(Specialization) << Range;
9134
9135 Diag(PrevDecl->getPointOfInstantiation(),
9136 diag::note_instantiation_required_here)
9137 << (PrevDecl->getTemplateSpecializationKind()
9139 return true;
9140 }
9141 }
9142
9143 // If this is not a friend, note that this is an explicit specialization.
9144 if (TUK != TagUseKind::Friend)
9145 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9146
9147 // Check that this isn't a redefinition of this specialization.
9148 if (TUK == TagUseKind::Definition) {
9149 RecordDecl *Def = Specialization->getDefinition();
9150 NamedDecl *Hidden = nullptr;
9151 bool HiddenDefVisible = false;
9152 if (Def && SkipBody &&
9153 isRedefinitionAllowedFor(Def, TemplateNameLoc, &Hidden,
9154 HiddenDefVisible)) {
9155 SkipBody->ShouldSkip = true;
9156 SkipBody->Previous = Def;
9157 if (!HiddenDefVisible && Hidden)
9159 } else if (Def) {
9160 SourceRange Range(TemplateNameLoc, RAngleLoc);
9161 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9162 Diag(Def->getLocation(), diag::note_previous_definition);
9163 Specialization->setInvalidDecl();
9164 return true;
9165 }
9166 }
9167
9170
9171 // Add alignment attributes if necessary; these attributes are checked when
9172 // the ASTContext lays out the structure.
9173 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9174 if (LangOpts.HLSL)
9175 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9178 }
9179
9180 if (ModulePrivateLoc.isValid())
9181 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9182 << (isPartialSpecialization? 1 : 0)
9183 << FixItHint::CreateRemoval(ModulePrivateLoc);
9184
9185 // C++ [temp.expl.spec]p9:
9186 // A template explicit specialization is in the scope of the
9187 // namespace in which the template was defined.
9188 //
9189 // We actually implement this paragraph where we set the semantic
9190 // context (in the creation of the ClassTemplateSpecializationDecl),
9191 // but we also maintain the lexical context where the actual
9192 // definition occurs.
9193 Specialization->setLexicalDeclContext(CurContext);
9194
9195 // We may be starting the definition of this specialization.
9196 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9197 Specialization->startDefinition();
9198
9199 if (TUK == TagUseKind::Friend) {
9200 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9201 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9202 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9204 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9205 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9206
9207 // Build the fully-sugared type for this class template
9208 // specialization as the user wrote in the specialization
9209 // itself. This means that we'll pretty-print the type retrieved
9210 // from the specialization's declaration the way that the user
9211 // actually wrote the specialization, rather than formatting the
9212 // name based on the "canonical" representation used to store the
9213 // template arguments in the specialization.
9215 TemplateNameLoc,
9216 WrittenTy,
9217 /*FIXME:*/KWLoc);
9218 Friend->setAccess(AS_public);
9219 CurContext->addDecl(Friend);
9220 } else {
9221 // Add the specialization into its lexical context, so that it can
9222 // be seen when iterating through the list of declarations in that
9223 // context. However, specializations are not found by name lookup.
9224 CurContext->addDecl(Specialization);
9225 }
9226
9227 if (SkipBody && SkipBody->ShouldSkip)
9228 return SkipBody->Previous;
9229
9230 Specialization->setInvalidDecl(Invalid);
9232 return Specialization;
9233}
9234
9236 MultiTemplateParamsArg TemplateParameterLists,
9237 Declarator &D) {
9238 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9239 ActOnDocumentableDecl(NewDecl);
9240 return NewDecl;
9241}
9242
9244 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9245 const IdentifierInfo *Name, SourceLocation NameLoc) {
9246 DeclContext *DC = CurContext;
9247
9248 if (!DC->getRedeclContext()->isFileContext()) {
9249 Diag(NameLoc,
9250 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9251 return nullptr;
9252 }
9253
9254 if (TemplateParameterLists.size() > 1) {
9255 Diag(NameLoc, diag::err_concept_extra_headers);
9256 return nullptr;
9257 }
9258
9259 TemplateParameterList *Params = TemplateParameterLists.front();
9260
9261 if (Params->size() == 0) {
9262 Diag(NameLoc, diag::err_concept_no_parameters);
9263 return nullptr;
9264 }
9265
9266 // Ensure that the parameter pack, if present, is the last parameter in the
9267 // template.
9268 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9269 ParamEnd = Params->end();
9270 ParamIt != ParamEnd; ++ParamIt) {
9271 Decl const *Param = *ParamIt;
9272 if (Param->isParameterPack()) {
9273 if (++ParamIt == ParamEnd)
9274 break;
9275 Diag(Param->getLocation(),
9276 diag::err_template_param_pack_must_be_last_template_parameter);
9277 return nullptr;
9278 }
9279 }
9280
9281 ConceptDecl *NewDecl =
9282 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9283
9284 if (NewDecl->hasAssociatedConstraints()) {
9285 // C++2a [temp.concept]p4:
9286 // A concept shall not have associated constraints.
9287 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9288 NewDecl->setInvalidDecl();
9289 }
9290
9291 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9292 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9294 LookupName(Previous, S);
9295 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9296 /*AllowInlineNamespace*/ false);
9297
9298 // We cannot properly handle redeclarations until we parse the constraint
9299 // expression, so only inject the name if we are sure we are not redeclaring a
9300 // symbol
9301 if (Previous.empty())
9302 PushOnScopeChains(NewDecl, S, true);
9303
9304 return NewDecl;
9305}
9306
9308 bool Found = false;
9309 LookupResult::Filter F = R.makeFilter();
9310 while (F.hasNext()) {
9311 NamedDecl *D = F.next();
9312 if (D == C) {
9313 F.erase();
9314 Found = true;
9315 break;
9316 }
9317 }
9318 F.done();
9319 return Found;
9320}
9321
9324 Expr *ConstraintExpr,
9325 const ParsedAttributesView &Attrs) {
9326 assert(!C->hasDefinition() && "Concept already defined");
9327 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9328 C->setInvalidDecl();
9329 return nullptr;
9330 }
9331 C->setDefinition(ConstraintExpr);
9332 ProcessDeclAttributeList(S, C, Attrs);
9333
9334 // Check for conflicting previous declaration.
9335 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9336 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9338 LookupName(Previous, S);
9339 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9340 /*AllowInlineNamespace*/ false);
9341 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9342 bool AddToScope = true;
9343 CheckConceptRedefinition(C, Previous, AddToScope);
9344
9346 if (!WasAlreadyAdded && AddToScope)
9347 PushOnScopeChains(C, S);
9348
9349 return C;
9350}
9351
9353 LookupResult &Previous, bool &AddToScope) {
9354 AddToScope = true;
9355
9356 if (Previous.empty())
9357 return;
9358
9359 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9360 if (!OldConcept) {
9361 auto *Old = Previous.getRepresentativeDecl();
9362 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9363 << NewDecl->getDeclName();
9364 notePreviousDefinition(Old, NewDecl->getLocation());
9365 AddToScope = false;
9366 return;
9367 }
9368 // Check if we can merge with a concept declaration.
9369 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9370 if (!IsSame) {
9371 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9372 << NewDecl->getDeclName();
9373 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9374 AddToScope = false;
9375 return;
9376 }
9377 if (hasReachableDefinition(OldConcept) &&
9378 IsRedefinitionInModule(NewDecl, OldConcept)) {
9379 Diag(NewDecl->getLocation(), diag::err_redefinition)
9380 << NewDecl->getDeclName();
9381 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9382 AddToScope = false;
9383 return;
9384 }
9385 if (!Previous.isSingleResult()) {
9386 // FIXME: we should produce an error in case of ambig and failed lookups.
9387 // Other decls (e.g. namespaces) also have this shortcoming.
9388 return;
9389 }
9390 // We unwrap canonical decl late to check for module visibility.
9391 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9392}
9393
9395 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9396 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9397 Diag(Loc, diag::err_recursive_concept) << CE;
9398 Diag(CE->getLocation(), diag::note_declared_at);
9399 CE->setInvalidDecl();
9400 return true;
9401 }
9402 // Concept template parameters don't have a definition and can't
9403 // be defined recursively.
9404 return false;
9405}
9406
9407/// \brief Strips various properties off an implicit instantiation
9408/// that has just been explicitly specialized.
9409static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9410 if (MinGW || (isa<FunctionDecl>(D) &&
9411 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9412 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9413
9414 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9415 FD->setInlineSpecified(false);
9416}
9417
9418/// Create an ExplicitInstantiationDecl to record source-location info for an
9419/// explicit template instantiation statement, and add it to \p CurContext.
9420///
9421/// For class templates / nested classes, the caller should build a
9422/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9423/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9424///
9425/// For function / variable templates, the caller should pass TypeAsWritten for
9426/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9428 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9429 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9430 NestedNameSpecifierLoc QualifierLoc,
9431 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9432 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9434 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9435 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9436 Context.addExplicitInstantiationDecl(Spec, EID);
9437 CurContext->addDecl(EID);
9438}
9439
9440/// Compute the diagnostic location for an explicit instantiation
9441// declaration or definition.
9442static SourceLocation
9444 SourceLocation PointOfInstantiation) {
9445 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9446 if (EID->getTemplateSpecializationKind() ==
9448 return EID->getTemplateLoc();
9449
9450 // Explicit instantiations following a specialization have no effect and
9451 // hence no PointOfInstantiation. In that case, walk decl backwards
9452 // until a valid name loc is found.
9453 SourceLocation PrevDiagLoc = PointOfInstantiation;
9454 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9455 Prev = Prev->getPreviousDecl()) {
9456 PrevDiagLoc = Prev->getLocation();
9457 }
9458 assert(PrevDiagLoc.isValid() &&
9459 "Explicit instantiation without point of instantiation?");
9460 return PrevDiagLoc;
9461}
9462
9463bool
9466 NamedDecl *PrevDecl,
9468 SourceLocation PrevPointOfInstantiation,
9469 bool &HasNoEffect) {
9470 HasNoEffect = false;
9471
9472 switch (NewTSK) {
9473 case TSK_Undeclared:
9475 assert(
9476 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9477 "previous declaration must be implicit!");
9478 return false;
9479
9481 switch (PrevTSK) {
9482 case TSK_Undeclared:
9484 // Okay, we're just specializing something that is either already
9485 // explicitly specialized or has merely been mentioned without any
9486 // instantiation.
9487 return false;
9488
9490 if (PrevPointOfInstantiation.isInvalid()) {
9491 // The declaration itself has not actually been instantiated, so it is
9492 // still okay to specialize it.
9494 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9495 return false;
9496 }
9497 // Fall through
9498 [[fallthrough]];
9499
9502 assert((PrevTSK == TSK_ImplicitInstantiation ||
9503 PrevPointOfInstantiation.isValid()) &&
9504 "Explicit instantiation without point of instantiation?");
9505
9506 // C++ [temp.expl.spec]p6:
9507 // If a template, a member template or the member of a class template
9508 // is explicitly specialized then that specialization shall be declared
9509 // before the first use of that specialization that would cause an
9510 // implicit instantiation to take place, in every translation unit in
9511 // which such a use occurs; no diagnostic is required.
9512 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9513 // Is there any previous explicit specialization declaration?
9515 return false;
9516 }
9517
9518 Diag(NewLoc, diag::err_specialization_after_instantiation)
9519 << PrevDecl;
9520 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9521 << (PrevTSK != TSK_ImplicitInstantiation);
9522
9523 return true;
9524 }
9525 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9526
9528 switch (PrevTSK) {
9530 // This explicit instantiation declaration is redundant (that's okay).
9531 HasNoEffect = true;
9532 return false;
9533
9534 case TSK_Undeclared:
9536 // We're explicitly instantiating something that may have already been
9537 // implicitly instantiated; that's fine.
9538 return false;
9539
9541 // C++0x [temp.explicit]p4:
9542 // For a given set of template parameters, if an explicit instantiation
9543 // of a template appears after a declaration of an explicit
9544 // specialization for that template, the explicit instantiation has no
9545 // effect.
9546 HasNoEffect = true;
9547 return false;
9548
9550 // C++0x [temp.explicit]p10:
9551 // If an entity is the subject of both an explicit instantiation
9552 // declaration and an explicit instantiation definition in the same
9553 // translation unit, the definition shall follow the declaration.
9554 Diag(NewLoc,
9555 diag::err_explicit_instantiation_declaration_after_definition);
9556
9557 // Explicit instantiations following a specialization have no effect and
9558 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9559 // until a valid name loc is found.
9560 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9561 diag::note_explicit_instantiation_definition_here);
9562 HasNoEffect = true;
9563 return false;
9564 }
9565 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9566
9568 switch (PrevTSK) {
9569 case TSK_Undeclared:
9571 // We're explicitly instantiating something that may have already been
9572 // implicitly instantiated; that's fine.
9573 return false;
9574
9576 // C++ DR 259, C++0x [temp.explicit]p4:
9577 // For a given set of template parameters, if an explicit
9578 // instantiation of a template appears after a declaration of
9579 // an explicit specialization for that template, the explicit
9580 // instantiation has no effect.
9581 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9582 << PrevDecl;
9583 Diag(PrevDecl->getLocation(),
9584 diag::note_previous_template_specialization);
9585 HasNoEffect = true;
9586 return false;
9587
9589 // We're explicitly instantiating a definition for something for which we
9590 // were previously asked to suppress instantiations. That's fine.
9591
9592 // C++0x [temp.explicit]p4:
9593 // For a given set of template parameters, if an explicit instantiation
9594 // of a template appears after a declaration of an explicit
9595 // specialization for that template, the explicit instantiation has no
9596 // effect.
9597 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9598 // Is there any previous explicit specialization declaration?
9600 HasNoEffect = true;
9601 break;
9602 }
9603 }
9604
9605 return false;
9606
9608 // C++0x [temp.spec]p5:
9609 // For a given template and a given set of template-arguments,
9610 // - an explicit instantiation definition shall appear at most once
9611 // in a program,
9612
9613 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9614 Diag(NewLoc, (getLangOpts().MSVCCompat)
9615 ? diag::ext_explicit_instantiation_duplicate
9616 : diag::err_explicit_instantiation_duplicate)
9617 << PrevDecl;
9618 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9619 diag::note_previous_explicit_instantiation);
9620 HasNoEffect = true;
9621 return false;
9622 }
9623 }
9624
9625 llvm_unreachable("Missing specialization/instantiation case?");
9626}
9627
9629 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9631 // Remove anything from Previous that isn't a function template in
9632 // the correct context.
9633 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9634 LookupResult::Filter F = Previous.makeFilter();
9635 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9636 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9637 while (F.hasNext()) {
9638 NamedDecl *D = F.next()->getUnderlyingDecl();
9639 if (!isa<FunctionTemplateDecl>(D)) {
9640 F.erase();
9641 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9642 continue;
9643 }
9644
9645 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9647 F.erase();
9648 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9649 continue;
9650 }
9651 }
9652 F.done();
9653
9654 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9655 if (Previous.empty()) {
9656 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9657 if (IsFriend && FriendQualifier.isDependent() &&
9658 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9659 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9661 Context, Previous.asUnresolvedSet(), ExplicitTemplateArgs);
9662 return false;
9663 }
9664
9665 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9666 << IsFriend;
9667 for (auto &P : DiscardedCandidates)
9668 Diag(P.second->getLocation(),
9669 diag::note_dependent_function_template_spec_discard_reason)
9670 << P.first << IsFriend;
9671 return true;
9672 }
9673
9675 ExplicitTemplateArgs);
9676 return false;
9677}
9678
9680 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9681 LookupResult &Previous, bool QualifiedFriend) {
9682 // The set of function template specializations that could match this
9683 // explicit function template specialization.
9684 UnresolvedSet<8> Candidates;
9685 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9686 /*ForTakingAddress=*/false);
9687
9688 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9689 ConvertedTemplateArgs;
9690
9691 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9692 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9693 I != E; ++I) {
9694 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9695 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9696 // Only consider templates found within the same semantic lookup scope as
9697 // FD.
9698 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9700 continue;
9701
9702 QualType FT = FD->getType();
9703 // C++11 [dcl.constexpr]p8:
9704 // A constexpr specifier for a non-static member function that is not
9705 // a constructor declares that member function to be const.
9706 //
9707 // When matching a constexpr member function template specialization
9708 // against the primary template, we don't yet know whether the
9709 // specialization has an implicit 'const' (because we don't know whether
9710 // it will be a static member function until we know which template it
9711 // specializes). This rule was removed in C++14.
9712 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9713 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9715 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9716 if (OldMD && OldMD->isConst()) {
9717 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9719 EPI.TypeQuals.addConst();
9720 FT = Context.getFunctionType(FPT->getReturnType(),
9721 FPT->getParamTypes(), EPI);
9722 }
9723 }
9724
9726 if (ExplicitTemplateArgs)
9727 Args = *ExplicitTemplateArgs;
9728
9729 // C++ [temp.expl.spec]p11:
9730 // A trailing template-argument can be left unspecified in the
9731 // template-id naming an explicit function template specialization
9732 // provided it can be deduced from the function argument type.
9733 // Perform template argument deduction to determine whether we may be
9734 // specializing this template.
9735 // FIXME: It is somewhat wasteful to build
9736 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9737 FunctionDecl *Specialization = nullptr;
9739 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9740 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9742 // Template argument deduction failed; record why it failed, so
9743 // that we can provide nifty diagnostics.
9744 FailedCandidates.addCandidate().set(
9745 I.getPair(), FunTmpl->getTemplatedDecl(),
9746 MakeDeductionFailureInfo(Context, TDK, Info));
9747 (void)TDK;
9748 continue;
9749 }
9750
9751 // Target attributes are part of the cuda function signature, so
9752 // the deduced template's cuda target must match that of the
9753 // specialization. Given that C++ template deduction does not
9754 // take target attributes into account, we reject candidates
9755 // here that have a different target.
9756 if (LangOpts.CUDA &&
9757 CUDA().IdentifyTarget(Specialization,
9758 /* IgnoreImplicitHDAttr = */ true) !=
9759 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9760 FailedCandidates.addCandidate().set(
9761 I.getPair(), FunTmpl->getTemplatedDecl(),
9764 continue;
9765 }
9766
9767 // Record this candidate.
9768 if (ExplicitTemplateArgs)
9769 ConvertedTemplateArgs[Specialization] = std::move(Args);
9770 Candidates.addDecl(Specialization, I.getAccess());
9771 }
9772 }
9773
9774 // For a qualified friend declaration (with no explicit marker to indicate
9775 // that a template specialization was intended), note all (template and
9776 // non-template) candidates.
9777 if (QualifiedFriend && Candidates.empty()) {
9778 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9779 << FD->getDeclName() << FDLookupContext;
9780 // FIXME: We should form a single candidate list and diagnose all
9781 // candidates at once, to get proper sorting and limiting.
9782 for (auto *OldND : Previous) {
9783 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9784 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9785 }
9786 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9787 return true;
9788 }
9789
9790 // Find the most specialized function template.
9792 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9793 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9794 PDiag(diag::err_function_template_spec_ambiguous)
9795 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9796 PDiag(diag::note_function_template_spec_matched));
9797
9798 if (Result == Candidates.end())
9799 return true;
9800
9801 // Ignore access information; it doesn't figure into redeclaration checking.
9803
9804 if (const auto *PT = Specialization->getPrimaryTemplate();
9805 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9806 auto Message = DSA->getMessage();
9807 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9808 << PT << !Message.empty() << Message;
9809 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9810 }
9811
9812 // C++23 [except.spec]p13:
9813 // An exception specification is considered to be needed when:
9814 // - [...]
9815 // - the exception specification is compared to that of another declaration
9816 // (e.g., an explicit specialization or an overriding virtual function);
9817 // - [...]
9818 //
9819 // The exception specification of a defaulted function is evaluated as
9820 // described above only when needed; similarly, the noexcept-specifier of a
9821 // specialization of a function template or member function of a class
9822 // template is instantiated only when needed.
9823 //
9824 // The standard doesn't specify what the "comparison with another declaration"
9825 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9826 // not state which properties of an explicit specialization must match the
9827 // primary template.
9828 //
9829 // We assume that an explicit specialization must correspond with (per
9830 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9831 // the declaration produced by substitution into the function template.
9832 //
9833 // Since the determination whether two function declarations correspond does
9834 // not consider exception specification, we only need to instantiate it once
9835 // we determine the primary template when comparing types per
9836 // [basic.link]p11.1.
9837 auto *SpecializationFPT =
9838 Specialization->getType()->castAs<FunctionProtoType>();
9839 // If the function has a dependent exception specification, resolve it after
9840 // we have selected the primary template so we can check whether it matches.
9841 if (getLangOpts().CPlusPlus17 &&
9842 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9843 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9844 return true;
9845
9847 = Specialization->getTemplateSpecializationInfo();
9848 assert(SpecInfo && "Function template specialization info missing?");
9849
9850 // Note: do not overwrite location info if previous template
9851 // specialization kind was explicit.
9853 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9854 Specialization->setLocation(FD->getLocation());
9855 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9856 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9857 // function can differ from the template declaration with respect to
9858 // the constexpr specifier.
9859 // FIXME: We need an update record for this AST mutation.
9860 // FIXME: What if there are multiple such prior declarations (for instance,
9861 // from different modules)?
9862 Specialization->setConstexprKind(FD->getConstexprKind());
9863 }
9864
9865 // FIXME: Check if the prior specialization has a point of instantiation.
9866 // If so, we have run afoul of .
9867
9868 // If this is a friend declaration, then we're not really declaring
9869 // an explicit specialization.
9870 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9871
9872 // Check the scope of this explicit specialization.
9873 if (!isFriend &&
9875 Specialization->getPrimaryTemplate(),
9877 false))
9878 return true;
9879
9880 // C++ [temp.expl.spec]p6:
9881 // If a template, a member template or the member of a class template is
9882 // explicitly specialized then that specialization shall be declared
9883 // before the first use of that specialization that would cause an implicit
9884 // instantiation to take place, in every translation unit in which such a
9885 // use occurs; no diagnostic is required.
9886 bool HasNoEffect = false;
9887 if (!isFriend &&
9892 SpecInfo->getPointOfInstantiation(),
9893 HasNoEffect))
9894 return true;
9895
9896 // Mark the prior declaration as an explicit specialization, so that later
9897 // clients know that this is an explicit specialization.
9898 // A dependent friend specialization which has a definition should be treated
9899 // as explicit specialization, despite being invalid.
9900 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9901 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9902 // Since explicit specializations do not inherit '=delete' from their
9903 // primary function template - check if the 'specialization' that was
9904 // implicitly generated (during template argument deduction for partial
9905 // ordering) from the most specialized of all the function templates that
9906 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9907 // first check that it was implicitly generated during template argument
9908 // deduction by making sure it wasn't referenced, and then reset the deleted
9909 // flag to not-deleted, so that we can inherit that information from 'FD'.
9910 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9911 !Specialization->getCanonicalDecl()->isReferenced()) {
9912 // FIXME: This assert will not hold in the presence of modules.
9913 assert(
9914 Specialization->getCanonicalDecl() == Specialization &&
9915 "This must be the only existing declaration of this specialization");
9916 // FIXME: We need an update record for this AST mutation.
9917 Specialization->setDeletedAsWritten(false);
9918 }
9919 // FIXME: We need an update record for this AST mutation.
9922 }
9923
9924 // Turn the given function declaration into a function template
9925 // specialization, with the template arguments from the previous
9926 // specialization.
9927 // Take copies of (semantic and syntactic) template argument lists.
9929 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9930 FD->setFunctionTemplateSpecialization(
9931 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertToken=*/{},
9933 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9934
9935 // A function template specialization inherits the target attributes
9936 // of its template. (We require the attributes explicitly in the
9937 // code to match, but a template may have implicit attributes by
9938 // virtue e.g. of being constexpr, and it passes these implicit
9939 // attributes on to its specializations.)
9940 if (LangOpts.CUDA)
9941 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9942
9943 // The "previous declaration" for this function template specialization is
9944 // the prior function template specialization.
9945 Previous.clear();
9946 Previous.addDecl(Specialization);
9947 return false;
9948}
9949
9950bool
9952 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9953 "Only for non-template members");
9954
9955 // Try to find the member we are instantiating.
9956 NamedDecl *FoundInstantiation = nullptr;
9957 NamedDecl *Instantiation = nullptr;
9958 NamedDecl *InstantiatedFrom = nullptr;
9959 MemberSpecializationInfo *MSInfo = nullptr;
9960
9961 if (Previous.empty()) {
9962 // Nowhere to look anyway.
9963 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9964 UnresolvedSet<8> Candidates;
9965 for (NamedDecl *Candidate : Previous) {
9966 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9967 // Ignore any candidates that aren't member functions.
9968 if (!Method)
9969 continue;
9970
9971 QualType Adjusted = Function->getType();
9972 if (!hasExplicitCallingConv(Adjusted))
9973 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9974 // Ignore any candidates with the wrong type.
9975 // This doesn't handle deduced return types, but both function
9976 // declarations should be undeduced at this point.
9977 // FIXME: The exception specification should probably be ignored when
9978 // comparing the types.
9979 if (!Context.hasSameType(Adjusted, Method->getType()))
9980 continue;
9981
9982 // Ignore any candidates with unsatisfied constraints.
9983 if (ConstraintSatisfaction Satisfaction;
9984 Method->getTrailingRequiresClause() &&
9985 (CheckFunctionConstraints(Method, Satisfaction,
9986 /*UsageLoc=*/Member->getLocation(),
9987 /*ForOverloadResolution=*/true) ||
9988 !Satisfaction.IsSatisfied))
9989 continue;
9990
9991 Candidates.addDecl(Candidate);
9992 }
9993
9994 // If we have no viable candidates left after filtering, we are done.
9995 if (Candidates.empty())
9996 return false;
9997
9998 // Find the function that is more constrained than every other function it
9999 // has been compared to.
10000 UnresolvedSetIterator Best = Candidates.begin();
10001 CXXMethodDecl *BestMethod = nullptr;
10002 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
10003 I != E; ++I) {
10004 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
10005 if (I == Best ||
10006 getMoreConstrainedFunction(Method, BestMethod) == Method) {
10007 Best = I;
10008 BestMethod = Method;
10009 }
10010 }
10011
10012 FoundInstantiation = *Best;
10013 Instantiation = BestMethod;
10014 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
10015 MSInfo = BestMethod->getMemberSpecializationInfo();
10016
10017 // Make sure the best candidate is more constrained than all of the others.
10018 bool Ambiguous = false;
10019 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
10020 I != E; ++I) {
10021 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
10022 if (I != Best &&
10023 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
10024 Ambiguous = true;
10025 break;
10026 }
10027 }
10028
10029 if (Ambiguous) {
10030 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
10031 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10032 for (NamedDecl *Candidate : Candidates) {
10033 Candidate = Candidate->getUnderlyingDecl();
10034 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
10035 << Candidate;
10036 }
10037 return true;
10038 }
10039 } else if (isa<VarDecl>(Member)) {
10040 VarDecl *PrevVar;
10041 if (Previous.isSingleResult() &&
10042 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10043 if (PrevVar->isStaticDataMember()) {
10044 FoundInstantiation = Previous.getRepresentativeDecl();
10045 Instantiation = PrevVar;
10046 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10047 MSInfo = PrevVar->getMemberSpecializationInfo();
10048 }
10049 } else if (isa<RecordDecl>(Member)) {
10050 CXXRecordDecl *PrevRecord;
10051 if (Previous.isSingleResult() &&
10052 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10053 FoundInstantiation = Previous.getRepresentativeDecl();
10054 Instantiation = PrevRecord;
10055 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10056 MSInfo = PrevRecord->getMemberSpecializationInfo();
10057 }
10058 } else if (isa<EnumDecl>(Member)) {
10059 EnumDecl *PrevEnum;
10060 if (Previous.isSingleResult() &&
10061 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10062 FoundInstantiation = Previous.getRepresentativeDecl();
10063 Instantiation = PrevEnum;
10064 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10065 MSInfo = PrevEnum->getMemberSpecializationInfo();
10066 }
10067 }
10068
10069 if (!Instantiation) {
10070 // There is no previous declaration that matches. Since member
10071 // specializations are always out-of-line, the caller will complain about
10072 // this mismatch later.
10073 return false;
10074 }
10075
10076 // A member specialization in a friend declaration isn't really declaring
10077 // an explicit specialization, just identifying a specific (possibly implicit)
10078 // specialization. Don't change the template specialization kind.
10079 //
10080 // FIXME: Is this really valid? Other compilers reject.
10081 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10082 // Preserve instantiation information.
10083 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10084 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10085 cast<CXXMethodDecl>(InstantiatedFrom),
10087 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10088 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10089 cast<CXXRecordDecl>(InstantiatedFrom),
10091 }
10092
10093 Previous.clear();
10094 Previous.addDecl(FoundInstantiation);
10095 return false;
10096 }
10097
10098 // Make sure that this is a specialization of a member.
10099 if (!InstantiatedFrom) {
10100 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10101 << Member;
10102 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10103 return true;
10104 }
10105
10106 // C++ [temp.expl.spec]p6:
10107 // If a template, a member template or the member of a class template is
10108 // explicitly specialized then that specialization shall be declared
10109 // before the first use of that specialization that would cause an implicit
10110 // instantiation to take place, in every translation unit in which such a
10111 // use occurs; no diagnostic is required.
10112 assert(MSInfo && "Member specialization info missing?");
10113
10114 bool HasNoEffect = false;
10117 Instantiation,
10119 MSInfo->getPointOfInstantiation(),
10120 HasNoEffect))
10121 return true;
10122
10123 // Check the scope of this explicit specialization.
10125 InstantiatedFrom,
10126 Instantiation, Member->getLocation(),
10127 false))
10128 return true;
10129
10130 // Note that this member specialization is an "instantiation of" the
10131 // corresponding member of the original template.
10132 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10133 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10134 if (InstantiationFunction->getTemplateSpecializationKind() ==
10136 // Explicit specializations of member functions of class templates do not
10137 // inherit '=delete' from the member function they are specializing.
10138 if (InstantiationFunction->isDeleted()) {
10139 // FIXME: This assert will not hold in the presence of modules.
10140 assert(InstantiationFunction->getCanonicalDecl() ==
10141 InstantiationFunction);
10142 // FIXME: We need an update record for this AST mutation.
10143 InstantiationFunction->setDeletedAsWritten(false);
10144 }
10145 }
10146
10147 MemberFunction->setInstantiationOfMemberFunction(
10149 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10150 MemberVar->setInstantiationOfStaticDataMember(
10151 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10152 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10153 MemberClass->setInstantiationOfMemberClass(
10155 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10156 MemberEnum->setInstantiationOfMemberEnum(
10157 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10158 } else {
10159 llvm_unreachable("unknown member specialization kind");
10160 }
10161
10162 // Save the caller the trouble of having to figure out which declaration
10163 // this specialization matches.
10164 Previous.clear();
10165 Previous.addDecl(FoundInstantiation);
10166 return false;
10167}
10168
10169/// Complete the explicit specialization of a member of a class template by
10170/// updating the instantiated member to be marked as an explicit specialization.
10171///
10172/// \param OrigD The member declaration instantiated from the template.
10173/// \param Loc The location of the explicit specialization of the member.
10174template<typename DeclT>
10175static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10176 SourceLocation Loc) {
10177 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10178 return;
10179
10180 // FIXME: Inform AST mutation listeners of this AST mutation.
10181 // FIXME: If there are multiple in-class declarations of the member (from
10182 // multiple modules, or a declaration and later definition of a member type),
10183 // should we update all of them?
10184 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10185 OrigD->setLocation(Loc);
10186}
10187
10190 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10191 if (Instantiation == Member)
10192 return;
10193
10194 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10195 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10196 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10197 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10198 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10199 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10200 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10201 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10202 else
10203 llvm_unreachable("unknown member specialization kind");
10204}
10205
10206/// Check the scope of an explicit instantiation.
10207///
10208/// \returns true if a serious error occurs, false otherwise.
10210 SourceLocation InstLoc,
10211 bool WasQualifiedName) {
10213 DeclContext *CurContext = S.CurContext->getRedeclContext();
10214
10215 if (CurContext->isRecord()) {
10216 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10217 << D;
10218 return true;
10219 }
10220
10221 // C++11 [temp.explicit]p3:
10222 // An explicit instantiation shall appear in an enclosing namespace of its
10223 // template. If the name declared in the explicit instantiation is an
10224 // unqualified name, the explicit instantiation shall appear in the
10225 // namespace where its template is declared or, if that namespace is inline
10226 // (7.3.1), any namespace from its enclosing namespace set.
10227 //
10228 // This is DR275, which we do not retroactively apply to C++98/03.
10229 if (WasQualifiedName) {
10230 if (CurContext->Encloses(OrigContext))
10231 return false;
10232 } else {
10233 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10234 return false;
10235 }
10236
10237 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10238 if (WasQualifiedName)
10239 S.Diag(InstLoc,
10240 S.getLangOpts().CPlusPlus11?
10241 diag::err_explicit_instantiation_out_of_scope :
10242 diag::warn_explicit_instantiation_out_of_scope_0x)
10243 << D << NS;
10244 else
10245 S.Diag(InstLoc,
10246 S.getLangOpts().CPlusPlus11?
10247 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10248 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10249 << D << NS;
10250 } else
10251 S.Diag(InstLoc,
10252 S.getLangOpts().CPlusPlus11?
10253 diag::err_explicit_instantiation_must_be_global :
10254 diag::warn_explicit_instantiation_must_be_global_0x)
10255 << D;
10256 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10257 return false;
10258}
10259
10260/// Common checks for whether an explicit instantiation of \p D is valid.
10262 SourceLocation InstLoc,
10263 bool WasQualifiedName,
10265 // C++ [temp.explicit]p13:
10266 // An explicit instantiation declaration shall not name a specialization of
10267 // a template with internal linkage.
10270 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10271 return true;
10272 }
10273
10274 // C++11 [temp.explicit]p3: [DR 275]
10275 // An explicit instantiation shall appear in an enclosing namespace of its
10276 // template.
10277 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10278 return true;
10279
10280 return false;
10281}
10282
10283/// Determine whether the given scope specifier has a template-id in it.
10285 // C++11 [temp.explicit]p3:
10286 // If the explicit instantiation is for a member function, a member class
10287 // or a static data member of a class template specialization, the name of
10288 // the class template specialization in the qualified-id for the member
10289 // name shall be a simple-template-id.
10290 //
10291 // C++98 has the same restriction, just worded differently.
10292 for (NestedNameSpecifier NNS = SS.getScopeRep();
10294 /**/) {
10295 const Type *T = NNS.getAsType();
10297 return true;
10298 NNS = T->getPrefix();
10299 }
10300 return false;
10301}
10302
10303/// Make a dllexport or dllimport attr on a class template specialization take
10304/// effect.
10307 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10308 assert(A && "dllExportImportClassTemplateSpecialization called "
10309 "on Def without dllexport or dllimport");
10310
10311 // We reject explicit instantiations in class scope, so there should
10312 // never be any delayed exported classes to worry about.
10313 assert(S.DelayedDllExportClasses.empty() &&
10314 "delayed exports present at explicit instantiation");
10316
10317 // Propagate attribute to base class templates.
10318 for (auto &B : Def->bases()) {
10319 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10320 B.getType()->getAsCXXRecordDecl()))
10322 }
10323
10325}
10326
10328 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10329 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10330 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10331 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10332 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10333 // Find the class template we're specializing
10334 TemplateName Name = TemplateD.get();
10335 TemplateDecl *TD = Name.getAsTemplateDecl();
10336 // Check that the specialization uses the same tag kind as the
10337 // original template.
10339 assert(Kind != TagTypeKind::Enum &&
10340 "Invalid enum tag in class template explicit instantiation!");
10341
10342 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10343
10344 if (!ClassTemplate) {
10345 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10346 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10347 Diag(TD->getLocation(), diag::note_previous_use);
10348 return true;
10349 }
10350
10351 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10352 Kind, /*isDefinition*/false, KWLoc,
10353 ClassTemplate->getIdentifier())) {
10354 Diag(KWLoc, diag::err_use_with_wrong_tag)
10355 << ClassTemplate
10357 ClassTemplate->getTemplatedDecl()->getKindName());
10358 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10359 diag::note_previous_use);
10360 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10361 }
10362
10363 // C++0x [temp.explicit]p2:
10364 // There are two forms of explicit instantiation: an explicit instantiation
10365 // definition and an explicit instantiation declaration. An explicit
10366 // instantiation declaration begins with the extern keyword. [...]
10367 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10370
10372 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10373 // Check for dllexport class template instantiation declarations,
10374 // except for MinGW mode.
10375 for (const ParsedAttr &AL : Attr) {
10376 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10377 Diag(ExternLoc,
10378 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10379 Diag(AL.getLoc(), diag::note_attribute);
10380 break;
10381 }
10382 }
10383
10384 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10385 Diag(ExternLoc,
10386 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10387 Diag(A->getLocation(), diag::note_attribute);
10388 }
10389 }
10390
10391 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10392 // instantiation declarations for most purposes.
10393 bool DLLImportExplicitInstantiationDef = false;
10395 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10396 // Check for dllimport class template instantiation definitions.
10397 bool DLLImport =
10398 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10399 for (const ParsedAttr &AL : Attr) {
10400 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10401 DLLImport = true;
10402 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10403 // dllexport trumps dllimport here.
10404 DLLImport = false;
10405 break;
10406 }
10407 }
10408 if (DLLImport) {
10410 DLLImportExplicitInstantiationDef = true;
10411 }
10412 }
10413
10414 // Translate the parser's template argument list in our AST format.
10415 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10416 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10417
10418 // Check that the template argument list is well-formed for this
10419 // template.
10421 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10422 /*DefaultArgs=*/{}, false, CTAI,
10423 /*UpdateArgsWithConversions=*/true,
10424 /*ConstraintsNotSatisfied=*/nullptr))
10425 return true;
10426
10427 // Find the class template specialization declaration that
10428 // corresponds to these arguments.
10429 llvm::FoldingSetInsertToken InsertToken;
10431 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
10432
10433 TemplateSpecializationKind PrevDecl_TSK
10434 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10435
10436 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10437 Context.getTargetInfo().getTriple().isOSCygMing()) {
10438 // Check for dllexport class template instantiation definitions in MinGW
10439 // mode, if a previous declaration of the instantiation was seen.
10440 for (const ParsedAttr &AL : Attr) {
10441 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10442 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10443 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10444 } else {
10445 Diag(AL.getLoc(),
10446 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10447 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10448 }
10449 break;
10450 }
10451 }
10452 }
10453
10454 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10455 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10456 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10457 return AL.getKind() == ParsedAttr::AT_DLLExport;
10458 })) {
10459 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10460 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10461 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10462 }
10463 }
10464
10465 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10466 SS.isSet(), TSK))
10467 return true;
10468
10470
10471 bool HasNoEffect = false;
10472 if (PrevDecl) {
10473 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10474 PrevDecl, PrevDecl_TSK,
10475 PrevDecl->getPointOfInstantiation(),
10476 HasNoEffect))
10477 return PrevDecl;
10478
10479 // Even though HasNoEffect == true means that this explicit instantiation
10480 // has no effect on semantics, we go on to put its syntax in the AST.
10481
10482 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10483 PrevDecl_TSK == TSK_Undeclared) {
10484 // Since the only prior class template specialization with these
10485 // arguments was referenced but not declared, reuse that
10486 // declaration node as our own, updating the source location
10487 // for the template name to reflect our new declaration.
10488 // (Other source locations will be updated later.)
10489 Specialization = PrevDecl;
10490 Specialization->setLocation(TemplateNameLoc);
10491 PrevDecl = nullptr;
10492 }
10493
10494 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10495 DLLImportExplicitInstantiationDef) {
10496 // The new specialization might add a dllimport attribute.
10497 HasNoEffect = false;
10498 }
10499 }
10500
10501 if (!Specialization) {
10502 // Create a new class template specialization declaration node for
10503 // this explicit specialization.
10505 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10506 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10508
10509 // A MSInheritanceAttr attached to the previous declaration must be
10510 // propagated to the new node prior to instantiation.
10511 if (PrevDecl) {
10512 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10513 auto *Clone = A->clone(getASTContext());
10514 Clone->setInherited(true);
10515 Specialization->addAttr(Clone);
10516 Consumer.AssignInheritanceModel(Specialization);
10517 }
10518 }
10519
10520 if (!HasNoEffect && !PrevDecl) {
10521 // Insert the new specialization.
10522 ClassTemplate->AddSpecialization(Specialization, InsertToken);
10523 }
10524 }
10525
10526 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10527
10528 // Set source locations for keywords.
10529 Specialization->setExternKeywordLoc(ExternLoc);
10530 Specialization->setTemplateKeywordLoc(TemplateLoc);
10531 Specialization->setBraceRange(SourceRange());
10532
10533 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10536
10537 // Add the explicit instantiation into its lexical context. However,
10538 // since explicit instantiations are never found by name lookup, we
10539 // just put it into the declaration context directly.
10540 Specialization->setLexicalDeclContext(CurContext);
10541 CurContext->addDecl(Specialization);
10542
10543 // Syntax is now OK, so return if it has no other effect on semantics.
10544 if (HasNoEffect) {
10545 // Set the template specialization kind.
10546 Specialization->setTemplateSpecializationKind(TSK);
10547
10549 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10550 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10551 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10552 Context.getCanonicalTagType(Specialization));
10554 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10555 TemplateNameLoc, TSI, TSK);
10556 return Specialization;
10557 }
10558
10559 // C++ [temp.explicit]p3:
10560 // A definition of a class template or class member template
10561 // shall be in scope at the point of the explicit instantiation of
10562 // the class template or class member template.
10563 //
10564 // This check comes when we actually try to perform the
10565 // instantiation.
10567 = cast_or_null<ClassTemplateSpecializationDecl>(
10568 Specialization->getDefinition());
10569 if (!Def)
10571 /*Complain=*/true,
10572 CTAI.StrictPackMatch);
10573 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10574 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10575 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10576 }
10577
10578 // Instantiate the members of this class template specialization.
10579 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10580 Specialization->getDefinition());
10581 if (Def) {
10583 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10584 // TSK_ExplicitInstantiationDefinition
10585 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10587 DLLImportExplicitInstantiationDef)) {
10588 // FIXME: Need to notify the ASTMutationListener that we did this.
10590
10591 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10592 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10593 // An explicit instantiation definition can add a dll attribute to a
10594 // template with a previous instantiation declaration. MinGW doesn't
10595 // allow this.
10596 auto *A = cast<InheritableAttr>(
10598 A->setInherited(true);
10599 Def->addAttr(A);
10601 }
10602 }
10603
10604 // Fix a TSK_ImplicitInstantiation followed by a
10605 // TSK_ExplicitInstantiationDefinition
10606 bool NewlyDLLExported =
10607 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10608 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10609 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10610 // An explicit instantiation definition can add a dll attribute to a
10611 // template with a previous implicit instantiation. MinGW doesn't allow
10612 // this. We limit clang to only adding dllexport, to avoid potentially
10613 // strange codegen behavior. For example, if we extend this conditional
10614 // to dllimport, and we have a source file calling a method on an
10615 // implicitly instantiated template class instance and then declaring a
10616 // dllimport explicit instantiation definition for the same template
10617 // class, the codegen for the method call will not respect the dllimport,
10618 // while it will with cl. The Def will already have the DLL attribute,
10619 // since the Def and Specialization will be the same in the case of
10620 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10621 // attribute to the Specialization; we just need to make it take effect.
10622 assert(Def == Specialization &&
10623 "Def and Specialization should match for implicit instantiation");
10625 }
10626
10627 // In MinGW mode, export the template instantiation if the declaration
10628 // was marked dllexport.
10629 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10630 Context.getTargetInfo().getTriple().isOSCygMing() &&
10631 PrevDecl->hasAttr<DLLExportAttr>()) {
10633 }
10634
10635 // Set the template specialization kind. Make sure it is set before
10636 // instantiating the members which will trigger ASTConsumer callbacks.
10637 Specialization->setTemplateSpecializationKind(TSK);
10638 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10639 } else {
10640
10641 // Set the template specialization kind.
10642 Specialization->setTemplateSpecializationKind(TSK);
10643 }
10644
10646 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10647 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10648 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10649 Context.getCanonicalTagType(Specialization));
10651 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10652 TemplateNameLoc, TSI, TSK);
10653 return Specialization;
10654}
10655
10658 SourceLocation TemplateLoc, unsigned TagSpec,
10659 SourceLocation KWLoc, CXXScopeSpec &SS,
10660 IdentifierInfo *Name, SourceLocation NameLoc,
10661 const ParsedAttributesView &Attr) {
10662
10663 bool Owned = false;
10664 bool IsDependent = false;
10665 Decl *TagD =
10666 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10667 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10668 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10669 false, TypeResult(), /*IsTypeSpecifier*/ false,
10670 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10671 .get();
10672 assert(!IsDependent &&
10673 "explicit instantiation of dependent name not yet handled");
10674
10675 if (!TagD)
10676 return true;
10677
10678 TagDecl *Tag = cast<TagDecl>(TagD);
10679 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10680
10681 if (Tag->isInvalidDecl())
10682 return true;
10683
10685 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10686 if (!Pattern) {
10687 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10688 << Context.getCanonicalTagType(Record);
10689 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10690 return true;
10691 }
10692
10693 // C++0x [temp.explicit]p2:
10694 // If the explicit instantiation is for a class or member class, the
10695 // elaborated-type-specifier in the declaration shall include a
10696 // simple-template-id.
10697 //
10698 // C++98 has the same restriction, just worded differently.
10700 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10701 << Record << SS.getRange();
10702
10703 // C++0x [temp.explicit]p2:
10704 // There are two forms of explicit instantiation: an explicit instantiation
10705 // definition and an explicit instantiation declaration. An explicit
10706 // instantiation declaration begins with the extern keyword. [...]
10710
10711 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10712
10713 // Verify that it is okay to explicitly instantiate here.
10714 CXXRecordDecl *PrevDecl
10715 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10716 if (!PrevDecl && Record->getDefinition())
10717 PrevDecl = Record;
10718 if (PrevDecl) {
10720 bool HasNoEffect = false;
10721 assert(MSInfo && "No member specialization information?");
10722 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10723 PrevDecl,
10725 MSInfo->getPointOfInstantiation(),
10726 HasNoEffect))
10727 return true;
10728 if (HasNoEffect) {
10732 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10733 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10734 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10735 TL.setElaboratedKeywordLoc(KWLoc);
10736 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10737 TL.setNameLoc(NameLoc);
10739 TemplateLoc, NestedNameSpecifierLoc(),
10740 nullptr, NameLoc, TSI, TSK);
10741 return TagD;
10742 }
10743 }
10744
10745 CXXRecordDecl *RecordDef
10746 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10747 if (!RecordDef) {
10748 // C++ [temp.explicit]p3:
10749 // A definition of a member class of a class template shall be in scope
10750 // at the point of an explicit instantiation of the member class.
10751 CXXRecordDecl *Def
10752 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10753 if (!Def) {
10754 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10755 << 0 << Record->getDeclName() << Record->getDeclContext();
10756 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10757 << Pattern;
10758 return true;
10759 } else {
10760 if (InstantiateClass(NameLoc, Record, Def,
10762 TSK))
10763 return true;
10764
10765 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10766 if (!RecordDef)
10767 return true;
10768 }
10769 }
10770
10771 // Instantiate all of the members of the class.
10772 InstantiateClassMembers(NameLoc, RecordDef,
10774
10776 MarkVTableUsed(NameLoc, RecordDef, true);
10777
10780 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10781 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10782 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10783 TL.setElaboratedKeywordLoc(KWLoc);
10784 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10785 TL.setNameLoc(NameLoc);
10787 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10788 NameLoc, TSI, TSK);
10789 return TagD;
10790}
10791
10793 SourceLocation ExternLoc,
10794 SourceLocation TemplateLoc,
10795 Declarator &D) {
10796 // Explicit instantiations always require a name.
10797 // TODO: check if/when DNInfo should replace Name.
10799 DeclarationName Name = NameInfo.getName();
10800 if (!Name) {
10801 if (!D.isInvalidType())
10803 diag::err_explicit_instantiation_requires_name)
10805
10806 return true;
10807 }
10808
10809 // Get the innermost enclosing declaration scope.
10810 S = S->getDeclParent();
10811
10812 // Determine the type of the declaration.
10814 QualType R = T->getType();
10815 if (R.isNull())
10816 return true;
10817
10818 // C++ [dcl.stc]p1:
10819 // A storage-class-specifier shall not be specified in [...] an explicit
10820 // instantiation (14.7.2) directive.
10822 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10823 << Name;
10824 return true;
10825 } else if (D.getDeclSpec().getStorageClassSpec()
10827 // Complain about then remove the storage class specifier.
10828 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10830
10832 }
10833
10834 // C++0x [temp.explicit]p1:
10835 // [...] An explicit instantiation of a function template shall not use the
10836 // inline or constexpr specifiers.
10837 // Presumably, this also applies to member functions of class templates as
10838 // well.
10842 diag::err_explicit_instantiation_inline :
10843 diag::warn_explicit_instantiation_inline_0x)
10845 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10846 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10847 // not already specified.
10849 diag::err_explicit_instantiation_constexpr);
10850
10851 // A deduction guide is not on the list of entities that can be explicitly
10852 // instantiated.
10854 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10855 << /*explicit instantiation*/ 0;
10856 return true;
10857 }
10858
10859 // C++0x [temp.explicit]p2:
10860 // There are two forms of explicit instantiation: an explicit instantiation
10861 // definition and an explicit instantiation declaration. An explicit
10862 // instantiation declaration begins with the extern keyword. [...]
10866
10867 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10869 /*ObjectType=*/QualType());
10870
10871 if (!R->isFunctionType()) {
10872 // C++ [temp.explicit]p1:
10873 // A [...] static data member of a class template can be explicitly
10874 // instantiated from the member definition associated with its class
10875 // template.
10876 // C++1y [temp.explicit]p1:
10877 // A [...] variable [...] template specialization can be explicitly
10878 // instantiated from its template.
10879 if (Previous.isAmbiguous())
10880 return true;
10881
10882 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10883 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10884 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10885
10886 if (!PrevTemplate) {
10887 if (!Prev || !Prev->isStaticDataMember()) {
10888 // We expect to see a static data member here.
10889 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10890 << Name;
10891 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10892 P != PEnd; ++P)
10893 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10894 return true;
10895 }
10896
10898 // FIXME: Check for explicit specialization?
10900 diag::err_explicit_instantiation_data_member_not_instantiated)
10901 << Prev;
10902 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10903 // FIXME: Can we provide a note showing where this was declared?
10904 return true;
10905 }
10906 } else {
10907 // Explicitly instantiate a variable template.
10908
10909 // C++1y [dcl.spec.auto]p6:
10910 // ... A program that uses auto or decltype(auto) in a context not
10911 // explicitly allowed in this section is ill-formed.
10912 //
10913 // This includes auto-typed variable template instantiations.
10914 if (R->isUndeducedType()) {
10915 Diag(T->getTypeLoc().getBeginLoc(),
10916 diag::err_auto_not_allowed_var_inst);
10917 return true;
10918 }
10919
10921 // C++1y [temp.explicit]p3:
10922 // If the explicit instantiation is for a variable, the unqualified-id
10923 // in the declaration shall be a template-id.
10925 diag::err_explicit_instantiation_without_template_id)
10926 << PrevTemplate;
10927 Diag(PrevTemplate->getLocation(),
10928 diag::note_explicit_instantiation_here);
10929 return true;
10930 }
10931
10932 // Translate the parser's template argument list into our AST format.
10933 TemplateArgumentListInfo TemplateArgs =
10935
10936 DeclResult Res =
10937 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10938 TemplateArgs, /*SetWrittenArgs=*/true);
10939 if (Res.isInvalid())
10940 return true;
10941
10942 if (!Res.isUsable()) {
10943 // We somehow specified dependent template arguments in an explicit
10944 // instantiation. This should probably only happen during error
10945 // recovery.
10946 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10947 return true;
10948 }
10949
10950 // Ignore access control bits, we don't need them for redeclaration
10951 // checking.
10952 Prev = cast<VarDecl>(Res.get());
10953 ArgsAsWritten =
10955 }
10956
10957 // C++0x [temp.explicit]p2:
10958 // If the explicit instantiation is for a member function, a member class
10959 // or a static data member of a class template specialization, the name of
10960 // the class template specialization in the qualified-id for the member
10961 // name shall be a simple-template-id.
10962 //
10963 // C++98 has the same restriction, just worded differently.
10964 //
10965 // This does not apply to variable template specializations, where the
10966 // template-id is in the unqualified-id instead.
10967 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10969 diag::ext_explicit_instantiation_without_qualified_id)
10970 << Prev << D.getCXXScopeSpec().getRange();
10971
10972 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10973
10974 // Verify that it is okay to explicitly instantiate here.
10977 bool HasNoEffect = false;
10979 PrevTSK, POI, HasNoEffect))
10980 return true;
10981
10982 if (!HasNoEffect) {
10983 // Instantiate static data member or variable template.
10985 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10986 VTSD->setExternKeywordLoc(ExternLoc);
10987 VTSD->setTemplateKeywordLoc(TemplateLoc);
10988 }
10989
10990 // Merge attributes.
10992 if (PrevTemplate)
10993 ProcessAPINotes(Prev);
10994
10997 }
10998
10999 // Check the new variable specialization against the parsed input.
11000 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
11001 Diag(T->getTypeLoc().getBeginLoc(),
11002 diag::err_invalid_var_template_spec_type)
11003 << 0 << PrevTemplate << R << Prev->getType();
11004 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
11005 << 2 << PrevTemplate->getDeclName();
11006 return true;
11007 }
11008
11010 Context, CurContext, Prev, ExternLoc, TemplateLoc,
11011 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11012 D.getIdentifierLoc(), T, TSK);
11013 return (Decl *)nullptr;
11014 }
11015
11016 // If the declarator is a template-id, translate the parser's template
11017 // argument list into our AST format.
11018 bool HasExplicitTemplateArgs = false;
11019 TemplateArgumentListInfo TemplateArgs;
11021 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
11022 HasExplicitTemplateArgs = true;
11023 }
11024
11025 // C++ [temp.explicit]p1:
11026 // A [...] function [...] can be explicitly instantiated from its template.
11027 // A member function [...] of a class template can be explicitly
11028 // instantiated from the member definition associated with its class
11029 // template.
11030 UnresolvedSet<8> TemplateMatches;
11031 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
11033 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
11034 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11035 P != PEnd; ++P) {
11036 NamedDecl *Prev = *P;
11037 if (!HasExplicitTemplateArgs) {
11038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11039 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11040 /*AdjustExceptionSpec*/true);
11041 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11042 if (Method->getPrimaryTemplate()) {
11043 TemplateMatches.addDecl(Method, P.getAccess());
11044 } else {
11045 OverloadCandidate &C = NonTemplateMatches.addCandidate();
11046 C.FoundDecl = P.getPair();
11047 C.Function = Method;
11048 C.Viable = true;
11050 if (Method->getTrailingRequiresClause() &&
11052 /*ForOverloadResolution=*/true) ||
11053 !S.IsSatisfied)) {
11054 C.Viable = false;
11056 }
11057 }
11058 }
11059 }
11060 }
11061
11062 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11063 if (!FunTmpl)
11064 continue;
11065
11066 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11067 FunctionDecl *Specialization = nullptr;
11069 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11070 Specialization, Info);
11072 // Keep track of almost-matches.
11073 FailedTemplateCandidates.addCandidate().set(
11074 P.getPair(), FunTmpl->getTemplatedDecl(),
11075 MakeDeductionFailureInfo(Context, TDK, Info));
11076 (void)TDK;
11077 continue;
11078 }
11079
11080 // Target attributes are part of the cuda function signature, so
11081 // the cuda target of the instantiated function must match that of its
11082 // template. Given that C++ template deduction does not take
11083 // target attributes into account, we reject candidates here that
11084 // have a different target.
11085 if (LangOpts.CUDA &&
11086 CUDA().IdentifyTarget(Specialization,
11087 /* IgnoreImplicitHDAttr = */ true) !=
11088 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11089 FailedTemplateCandidates.addCandidate().set(
11090 P.getPair(), FunTmpl->getTemplatedDecl(),
11093 continue;
11094 }
11095
11096 TemplateMatches.addDecl(Specialization, P.getAccess());
11097 }
11098
11099 FunctionDecl *Specialization = nullptr;
11100 if (!NonTemplateMatches.empty()) {
11101 unsigned Msg = 0;
11102 OverloadCandidateDisplayKind DisplayKind;
11104 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11105 Best)) {
11106 case OR_Success:
11107 case OR_Deleted:
11108 Specialization = cast<FunctionDecl>(Best->Function);
11109 break;
11110 case OR_Ambiguous:
11111 Msg = diag::err_explicit_instantiation_ambiguous;
11112 DisplayKind = OCD_AmbiguousCandidates;
11113 break;
11115 Msg = diag::err_explicit_instantiation_no_candidate;
11116 DisplayKind = OCD_AllCandidates;
11117 break;
11118 }
11119 if (Msg) {
11120 PartialDiagnostic Diag = PDiag(Msg) << Name;
11121 NonTemplateMatches.NoteCandidates(
11122 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11123 {});
11124 return true;
11125 }
11126 }
11127
11128 if (!Specialization) {
11129 // Find the most specialized function template specialization.
11131 TemplateMatches.begin(), TemplateMatches.end(),
11132 FailedTemplateCandidates, D.getIdentifierLoc(),
11133 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11134 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11135 PDiag(diag::note_explicit_instantiation_candidate));
11136
11137 if (Result == TemplateMatches.end())
11138 return true;
11139
11140 // Ignore access control bits, we don't need them for redeclaration checking.
11142 }
11143
11144 // C++11 [except.spec]p4
11145 // In an explicit instantiation an exception-specification may be specified,
11146 // but is not required.
11147 // If an exception-specification is specified in an explicit instantiation
11148 // directive, it shall be compatible with the exception-specifications of
11149 // other declarations of that function.
11150 if (auto *FPT = R->getAs<FunctionProtoType>())
11151 if (FPT->hasExceptionSpec()) {
11152 unsigned DiagID =
11153 diag::err_mismatched_exception_spec_explicit_instantiation;
11154 if (getLangOpts().MicrosoftExt)
11155 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11157 PDiag(DiagID) << Specialization->getType(),
11158 PDiag(diag::note_explicit_instantiation_here),
11159 Specialization->getType()->getAs<FunctionProtoType>(),
11160 Specialization->getLocation(), FPT, D.getBeginLoc());
11161 // In Microsoft mode, mismatching exception specifications just cause a
11162 // warning.
11163 if (!getLangOpts().MicrosoftExt && Result)
11164 return true;
11165 }
11166
11167 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11169 diag::err_explicit_instantiation_member_function_not_instantiated)
11171 << (Specialization->getTemplateSpecializationKind() ==
11173 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11174 return true;
11175 }
11176
11177 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11178 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11179 PrevDecl = Specialization;
11180
11181 if (PrevDecl) {
11182 bool HasNoEffect = false;
11184 PrevDecl,
11186 PrevDecl->getPointOfInstantiation(),
11187 HasNoEffect))
11188 return true;
11189
11190 if (HasNoEffect) {
11191 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11192 if (HasExplicitTemplateArgs)
11193 ArgsAsWritten =
11196 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11197 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11198 D.getIdentifierLoc(), T, TSK);
11199 return (Decl *)nullptr;
11200 }
11201 }
11202
11203 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11204 // functions
11205 // valarray<size_t>::valarray(size_t) and
11206 // valarray<size_t>::~valarray()
11207 // that it declared to have internal linkage with the internal_linkage
11208 // attribute. Ignore the explicit instantiation declaration in this case.
11209 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11211 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11212 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11213 RD->isInStdNamespace())
11214 return (Decl*) nullptr;
11215 }
11216
11219
11220 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11221 // instantiation declarations.
11223 Specialization->hasAttr<DLLImportAttr>() &&
11224 Context.getTargetInfo().getCXXABI().isMicrosoft())
11226
11227 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11228 if (Specialization->isDefined()) {
11229 // Let the ASTConsumer know that this function has been explicitly
11230 // instantiated now, and its linkage might have changed.
11231 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11232 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11233 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11234 // be explicitly instantiated.
11235 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11236 RD && RD->isLambda()) {
11237 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11238 << /*instantiation*/ 1;
11239 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11240 return (Decl *)nullptr;
11241 }
11243 }
11244
11245 // C++0x [temp.explicit]p2:
11246 // If the explicit instantiation is for a member function, a member class
11247 // or a static data member of a class template specialization, the name of
11248 // the class template specialization in the qualified-id for the member
11249 // name shall be a simple-template-id.
11250 //
11251 // C++98 has the same restriction, just worded differently.
11252 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11253 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11254 D.getCXXScopeSpec().isSet() &&
11257 diag::ext_explicit_instantiation_without_qualified_id)
11259
11261 *this,
11262 FunTmpl ? (NamedDecl *)FunTmpl
11263 : Specialization->getInstantiatedFromMemberFunction(),
11264 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11265
11266 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11267 if (HasExplicitTemplateArgs)
11268 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11270 TemplateLoc,
11272 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11273 return (Decl *)nullptr;
11274}
11275
11277 const CXXScopeSpec &SS,
11278 const IdentifierInfo *Name,
11279 SourceLocation TagLoc,
11280 SourceLocation NameLoc) {
11281 // This has to hold, because SS is expected to be defined.
11282 assert(Name && "Expected a name in a dependent tag");
11283
11285 if (!NNS)
11286 return true;
11287
11288 if (TUK == TagUseKind::Friend &&
11290 return true;
11291
11293
11294 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11295 Diag(NameLoc, diag::err_dependent_tag_decl)
11296 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11297 return true;
11298 }
11299
11300 // Create the resulting type.
11302 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11303
11304 // Create type-source location information for this type.
11305 TypeLocBuilder TLB;
11307 TL.setElaboratedKeywordLoc(TagLoc);
11309 TL.setNameLoc(NameLoc);
11311}
11312
11314 const CXXScopeSpec &SS,
11315 const IdentifierInfo &II,
11316 SourceLocation IdLoc,
11317 ImplicitTypenameContext IsImplicitTypename) {
11318 if (SS.isInvalid())
11319 return true;
11320
11321 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11322 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11323 << FixItHint::CreateRemoval(TypenameLoc);
11324
11326 TypeSourceInfo *TSI = nullptr;
11327 QualType T =
11330 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11331 /*DeducedTSTContext=*/true);
11332 if (T.isNull())
11333 return true;
11334 return CreateParsedType(T, TSI);
11335}
11336
11339 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11340 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11341 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11342 ASTTemplateArgsPtr TemplateArgsIn,
11343 SourceLocation RAngleLoc) {
11344 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11345 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11346 ? diag::compat_cxx11_typename_outside_of_template
11347 : diag::compat_pre_cxx11_typename_outside_of_template)
11348 << FixItHint::CreateRemoval(TypenameLoc);
11349
11350 // Strangely, non-type results are not ignored by this lookup, so the
11351 // program is ill-formed if it finds an injected-class-name.
11352 if (TypenameLoc.isValid()) {
11353 auto *LookupRD =
11354 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11355 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11356 Diag(TemplateIILoc,
11357 diag::ext_out_of_line_qualified_id_type_names_constructor)
11358 << TemplateII << 0 /*injected-class-name used as template name*/
11359 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11360 }
11361 }
11362
11363 // Translate the parser's template argument list in our AST format.
11364 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11365 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11366
11370 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11371 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11372 if (T.isNull())
11373 return true;
11374
11375 // Provide source-location information for the template specialization type.
11376 TypeLocBuilder Builder;
11378 = Builder.push<TemplateSpecializationTypeLoc>(T);
11379 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11380 TemplateIILoc, TemplateArgs);
11381 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11382 return CreateParsedType(T, TSI);
11383}
11384
11385/// Determine whether this failed name lookup should be treated as being
11386/// disabled by a usage of std::enable_if.
11388 SourceRange &CondRange, Expr *&Cond) {
11389 // We must be looking for a ::type...
11390 if (!II.isStr("type"))
11391 return false;
11392
11393 // ... within an explicitly-written template specialization...
11395 return false;
11396
11397 // FIXME: Look through sugar.
11398 auto EnableIfTSTLoc =
11400 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11401 return false;
11402 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11403
11404 // ... which names a complete class template declaration...
11405 const TemplateDecl *EnableIfDecl =
11406 EnableIfTST->getTemplateName().getAsTemplateDecl();
11407 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11408 return false;
11409
11410 // ... called "enable_if".
11411 const IdentifierInfo *EnableIfII =
11412 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11413 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11414 return false;
11415
11416 // Assume the first template argument is the condition.
11417 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11418
11419 // Dig out the condition.
11420 Cond = nullptr;
11421 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11423 return true;
11424
11425 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11426
11427 // Ignore Boolean literals; they add no value.
11429 Cond = nullptr;
11430
11431 return true;
11432}
11433
11436 SourceLocation KeywordLoc,
11437 NestedNameSpecifierLoc QualifierLoc,
11438 const IdentifierInfo &II,
11439 SourceLocation IILoc,
11440 TypeSourceInfo **TSI,
11441 bool DeducedTSTContext) {
11442 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11443 DeducedTSTContext);
11444 if (T.isNull())
11445 return QualType();
11446
11447 TypeLocBuilder TLB;
11448 if (isa<DependentNameType>(T)) {
11449 auto TL = TLB.push<DependentNameTypeLoc>(T);
11450 TL.setElaboratedKeywordLoc(KeywordLoc);
11451 TL.setQualifierLoc(QualifierLoc);
11452 TL.setNameLoc(IILoc);
11455 TL.setElaboratedKeywordLoc(KeywordLoc);
11456 TL.setQualifierLoc(QualifierLoc);
11457 TL.setNameLoc(IILoc);
11458 } else if (isa<TemplateTypeParmType>(T)) {
11459 // FIXME: There might be a 'typename' keyword here, but we just drop it
11460 // as it can't be represented.
11461 assert(!QualifierLoc);
11462 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11463 } else if (isa<TagType>(T)) {
11464 auto TL = TLB.push<TagTypeLoc>(T);
11465 TL.setElaboratedKeywordLoc(KeywordLoc);
11466 TL.setQualifierLoc(QualifierLoc);
11467 TL.setNameLoc(IILoc);
11468 } else if (isa<TypedefType>(T)) {
11469 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11470 } else {
11471 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11472 }
11473 *TSI = TLB.getTypeSourceInfo(Context, T);
11474 return T;
11475}
11476
11477/// Build the type that describes a C++ typename specifier,
11478/// e.g., "typename T::type".
11481 SourceLocation KeywordLoc,
11482 NestedNameSpecifierLoc QualifierLoc,
11483 const IdentifierInfo &II,
11484 SourceLocation IILoc, bool DeducedTSTContext) {
11485 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11486
11487 CXXScopeSpec SS;
11488 SS.Adopt(QualifierLoc);
11489
11490 DeclContext *Ctx = nullptr;
11491 if (QualifierLoc) {
11492 Ctx = computeDeclContext(SS);
11493 if (!Ctx) {
11494 // If the nested-name-specifier is dependent and couldn't be
11495 // resolved to a type, build a typename type.
11496 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11497 return Context.getDependentNameType(Keyword,
11498 QualifierLoc.getNestedNameSpecifier(),
11499 &II);
11500 }
11501
11502 // If the nested-name-specifier refers to the current instantiation,
11503 // the "typename" keyword itself is superfluous. In C++03, the
11504 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11505 // allows such extraneous "typename" keywords, and we retroactively
11506 // apply this DR to C++03 code with only a warning. In any case we continue.
11507
11508 if (RequireCompleteDeclContext(SS, Ctx))
11509 return QualType();
11510 }
11511
11512 DeclarationName Name(&II);
11513 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11514 if (Ctx)
11515 LookupQualifiedName(Result, Ctx, SS);
11516 else
11517 LookupName(Result, CurScope);
11518 unsigned DiagID = 0;
11519 Decl *Referenced = nullptr;
11520 switch (Result.getResultKind()) {
11522 // If we're looking up 'type' within a template named 'enable_if', produce
11523 // a more specific diagnostic.
11524 SourceRange CondRange;
11525 Expr *Cond = nullptr;
11526 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11527 // If we have a condition, narrow it down to the specific failed
11528 // condition.
11529 if (Cond) {
11530 Expr *FailedCond;
11531 std::string FailedDescription;
11532 std::tie(FailedCond, FailedDescription) =
11534
11535 Diag(FailedCond->getExprLoc(),
11536 diag::err_typename_nested_not_found_requirement)
11537 << FailedDescription
11538 << FailedCond->getSourceRange();
11539 return QualType();
11540 }
11541
11542 Diag(CondRange.getBegin(),
11543 diag::err_typename_nested_not_found_enable_if)
11544 << Ctx << CondRange;
11545 return QualType();
11546 }
11547
11548 DiagID = Ctx ? diag::err_typename_nested_not_found
11549 : diag::err_unknown_typename;
11550 break;
11551 }
11552
11554 // We found a using declaration that is a value. Most likely, the using
11555 // declaration itself is meant to have the 'typename' keyword.
11556 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11557 IILoc);
11558 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11559 << Name << Ctx << FullRange;
11560 if (UnresolvedUsingValueDecl *Using
11561 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11562 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11563 Diag(Loc, diag::note_using_value_decl_missing_typename)
11564 << FixItHint::CreateInsertion(Loc, "typename ");
11565 }
11566 }
11567 // Fall through to create a dependent typename type, from which we can
11568 // recover better.
11569 [[fallthrough]];
11570
11572 // Okay, it's a member of an unknown instantiation.
11573 return Context.getDependentNameType(Keyword,
11574 QualifierLoc.getNestedNameSpecifier(),
11575 &II);
11576
11578 // FXIME: Missing support for UsingShadowDecl on this path?
11579 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11580 // C++ [class.qual]p2:
11581 // In a lookup in which function names are not ignored and the
11582 // nested-name-specifier nominates a class C, if the name specified
11583 // after the nested-name-specifier, when looked up in C, is the
11584 // injected-class-name of C [...] then the name is instead considered
11585 // to name the constructor of class C.
11586 //
11587 // Unlike in an elaborated-type-specifier, function names are not ignored
11588 // in typename-specifier lookup. However, they are ignored in all the
11589 // contexts where we form a typename type with no keyword (that is, in
11590 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11591 //
11592 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11593 // ignore functions, but that appears to be an oversight.
11598 Type, IILoc);
11599 // FIXME: This appears to be the only case where a template type parameter
11600 // can have an elaborated keyword. We should preserve it somehow.
11603 assert(!QualifierLoc);
11605 }
11606 return Context.getTypeDeclType(
11607 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11608 }
11609
11610 // C++ [dcl.type.simple]p2:
11611 // A type-specifier of the form
11612 // typename[opt] nested-name-specifier[opt] template-name
11613 // is a placeholder for a deduced class type [...].
11614 if (getLangOpts().CPlusPlus17) {
11615 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11616 if (!DeducedTSTContext) {
11617 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11618 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11619 Diag(IILoc, diag::err_dependent_deduced_tst)
11621 << QualType(Qualifier.getAsType(), 0);
11622 else
11623 Diag(IILoc, diag::err_deduced_tst)
11626 return QualType();
11627 }
11628 TemplateName Name = Context.getQualifiedTemplateName(
11629 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11630 TemplateName(TD));
11631 return Context.getDeducedTemplateSpecializationType(
11632 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11633 Name);
11634 }
11635 }
11636
11637 DiagID = Ctx ? diag::err_typename_nested_not_type
11638 : diag::err_typename_not_type;
11639 Referenced = Result.getFoundDecl();
11640 break;
11641
11643 DiagID = Ctx ? diag::err_typename_nested_not_type
11644 : diag::err_typename_not_type;
11645 Referenced = *Result.begin();
11646 break;
11647
11649 return QualType();
11650 }
11651
11652 // If we get here, it's because name lookup did not find a
11653 // type. Emit an appropriate diagnostic and return an error.
11654 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11655 IILoc);
11656 if (Ctx)
11657 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11658 else
11659 Diag(IILoc, DiagID) << FullRange << Name;
11660 if (Referenced)
11661 Diag(Referenced->getLocation(),
11662 Ctx ? diag::note_typename_member_refers_here
11663 : diag::note_typename_refers_here)
11664 << Name;
11665 return QualType();
11666}
11667
11668namespace {
11669 // See Sema::RebuildTypeInCurrentInstantiation
11670 class CurrentInstantiationRebuilder
11671 : public TreeTransform<CurrentInstantiationRebuilder> {
11672 SourceLocation Loc;
11673 DeclarationName Entity;
11674
11675 public:
11677
11678 CurrentInstantiationRebuilder(Sema &SemaRef,
11679 SourceLocation Loc,
11680 DeclarationName Entity)
11681 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11682 Loc(Loc), Entity(Entity) { }
11683
11684 /// Determine whether the given type \p T has already been
11685 /// transformed.
11686 ///
11687 /// For the purposes of type reconstruction, a type has already been
11688 /// transformed if it is NULL or if it is not dependent.
11689 bool AlreadyTransformed(QualType T) {
11690 return T.isNull() || !T->isInstantiationDependentType();
11691 }
11692
11693 /// Returns the location of the entity whose type is being
11694 /// rebuilt.
11695 SourceLocation getBaseLocation() { return Loc; }
11696
11697 /// Returns the name of the entity whose type is being rebuilt.
11698 DeclarationName getBaseEntity() { return Entity; }
11699
11700 /// Sets the "base" location and entity when that
11701 /// information is known based on another transformation.
11702 void setBase(SourceLocation Loc, DeclarationName Entity) {
11703 this->Loc = Loc;
11704 this->Entity = Entity;
11705 }
11706
11707 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11708 // Lambdas never need to be transformed.
11709 return E;
11710 }
11711 };
11712} // end anonymous namespace
11713
11715 SourceLocation Loc,
11716 DeclarationName Name) {
11717 if (!T || !T->getType()->isInstantiationDependentType())
11718 return T;
11719
11720 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11721 return Rebuilder.TransformType(T);
11722}
11723
11725 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11726 DeclarationName());
11727 return Rebuilder.TransformExpr(E);
11728}
11729
11731 if (SS.isInvalid())
11732 return true;
11733
11735 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11736 DeclarationName());
11738 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11739 if (!Rebuilt)
11740 return true;
11741
11742 SS.Adopt(Rebuilt);
11743 return false;
11744}
11745
11747 TemplateParameterList *Params) {
11748 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11749 Decl *Param = Params->getParam(I);
11750
11751 // There is nothing to rebuild in a type parameter.
11752 if (isa<TemplateTypeParmDecl>(Param))
11753 continue;
11754
11755 // Rebuild the template parameter list of a template template parameter.
11757 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11759 TTP->getTemplateParameters()))
11760 return true;
11761
11762 continue;
11763 }
11764
11765 // Rebuild the type of a non-type template parameter.
11767 TypeSourceInfo *NewTSI
11769 NTTP->getLocation(),
11770 NTTP->getDeclName());
11771 if (!NewTSI)
11772 return true;
11773
11774 if (NewTSI->getType()->isUndeducedType()) {
11775 // C++17 [temp.dep.expr]p3:
11776 // An id-expression is type-dependent if it contains
11777 // - an identifier associated by name lookup with a non-type
11778 // template-parameter declared with a type that contains a
11779 // placeholder type (7.1.7.4),
11780 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11781 }
11782
11783 if (NewTSI != NTTP->getTypeSourceInfo()) {
11784 NTTP->setTypeSourceInfo(NewTSI);
11785 NTTP->setType(NewTSI->getType());
11786 }
11787 }
11788
11789 return false;
11790}
11791
11792std::string
11794 const TemplateArgumentList &Args) {
11795 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11796}
11797
11798std::string
11800 const TemplateArgument *Args,
11801 unsigned NumArgs) {
11802 SmallString<128> Str;
11803 llvm::raw_svector_ostream Out(Str);
11804
11805 if (!Params || Params->size() == 0 || NumArgs == 0)
11806 return std::string();
11807
11808 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11809 if (I >= NumArgs)
11810 break;
11811
11812 if (I == 0)
11813 Out << "[with ";
11814 else
11815 Out << ", ";
11816
11817 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11818 Out << Id->getName();
11819 } else {
11820 Out << '$' << I;
11821 }
11822
11823 Out << " = ";
11824 Args[I].print(getPrintingPolicy(), Out,
11826 getPrintingPolicy(), Params, I));
11827 }
11828
11829 Out << ']';
11830 return std::string(Out.str());
11831}
11832
11834 CachedTokens &Toks) {
11835 if (!FD)
11836 return;
11837
11838 auto LPT = std::make_unique<LateParsedTemplate>();
11839
11840 // Take tokens to avoid allocations
11841 LPT->Toks.swap(Toks);
11842 LPT->D = FnD;
11843 LPT->FPO = getCurFPFeatures();
11844 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11845
11846 FD->setLateTemplateParsed(true);
11847}
11848
11850 if (!FD)
11851 return;
11852 FD->setLateTemplateParsed(false);
11853}
11854
11856 DeclContext *DC = CurContext;
11857
11858 while (DC) {
11859 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11860 const FunctionDecl *FD = RD->isLocalClass();
11861 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11862 } else if (DC->isTranslationUnit() || DC->isNamespace())
11863 return false;
11864
11865 DC = DC->getParent();
11866 }
11867 return false;
11868}
11869
11870namespace {
11871/// Walk the path from which a declaration was instantiated, and check
11872/// that every explicit specialization along that path is visible. This enforces
11873/// C++ [temp.expl.spec]/6:
11874///
11875/// If a template, a member template or a member of a class template is
11876/// explicitly specialized then that specialization shall be declared before
11877/// the first use of that specialization that would cause an implicit
11878/// instantiation to take place, in every translation unit in which such a
11879/// use occurs; no diagnostic is required.
11880///
11881/// and also C++ [temp.class.spec]/1:
11882///
11883/// A partial specialization shall be declared before the first use of a
11884/// class template specialization that would make use of the partial
11885/// specialization as the result of an implicit or explicit instantiation
11886/// in every translation unit in which such a use occurs; no diagnostic is
11887/// required.
11888class ExplicitSpecializationVisibilityChecker {
11889 Sema &S;
11890 SourceLocation Loc;
11893
11894public:
11895 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11897 : S(S), Loc(Loc), Kind(Kind) {}
11898
11899 void check(NamedDecl *ND) {
11900 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11901 return checkImpl(FD);
11902 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11903 return checkImpl(RD);
11904 if (auto *VD = dyn_cast<VarDecl>(ND))
11905 return checkImpl(VD);
11906 if (auto *ED = dyn_cast<EnumDecl>(ND))
11907 return checkImpl(ED);
11908 }
11909
11910private:
11911 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11912 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11913 : Sema::MissingImportKind::ExplicitSpecialization;
11914 const bool Recover = true;
11915
11916 // If we got a custom set of modules (because only a subset of the
11917 // declarations are interesting), use them, otherwise let
11918 // diagnoseMissingImport intelligently pick some.
11919 if (Modules.empty())
11920 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11921 else
11922 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11923 }
11924
11925 bool CheckMemberSpecialization(const NamedDecl *D) {
11926 return Kind == Sema::AcceptableKind::Visible
11929 }
11930
11931 bool CheckExplicitSpecialization(const NamedDecl *D) {
11932 return Kind == Sema::AcceptableKind::Visible
11935 }
11936
11937 bool CheckDeclaration(const NamedDecl *D) {
11938 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11940 }
11941
11942 // Check a specific declaration. There are three problematic cases:
11943 //
11944 // 1) The declaration is an explicit specialization of a template
11945 // specialization.
11946 // 2) The declaration is an explicit specialization of a member of an
11947 // templated class.
11948 // 3) The declaration is an instantiation of a template, and that template
11949 // is an explicit specialization of a member of a templated class.
11950 //
11951 // We don't need to go any deeper than that, as the instantiation of the
11952 // surrounding class / etc is not triggered by whatever triggered this
11953 // instantiation, and thus should be checked elsewhere.
11954 template<typename SpecDecl>
11955 void checkImpl(SpecDecl *Spec) {
11956 bool IsHiddenExplicitSpecialization = false;
11957 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11958 // Some invalid friend declarations are written as specializations but are
11959 // instantiated implicitly.
11960 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11961 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11962 if (SpecKind == TSK_ExplicitSpecialization) {
11963 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11964 ? !CheckMemberSpecialization(Spec)
11965 : !CheckExplicitSpecialization(Spec);
11966 } else {
11967 checkInstantiated(Spec);
11968 }
11969
11970 if (IsHiddenExplicitSpecialization)
11971 diagnose(Spec->getMostRecentDecl(), false);
11972 }
11973
11974 void checkInstantiated(FunctionDecl *FD) {
11975 if (auto *TD = FD->getPrimaryTemplate())
11976 checkTemplate(TD);
11977 }
11978
11979 void checkInstantiated(CXXRecordDecl *RD) {
11980 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11981 if (!SD)
11982 return;
11983
11984 auto From = SD->getSpecializedTemplateOrPartial();
11985 if (auto *TD = dyn_cast<ClassTemplateDecl *>(From))
11986 checkTemplate(TD);
11987 else if (auto *TD =
11988 dyn_cast<ClassTemplatePartialSpecializationDecl *>(From)) {
11989 if (!CheckDeclaration(TD))
11990 diagnose(TD, true);
11991 checkTemplate(TD);
11992 }
11993 }
11994
11995 void checkInstantiated(VarDecl *RD) {
11996 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11997 if (!SD)
11998 return;
11999
12000 auto From = SD->getSpecializedTemplateOrPartial();
12001 if (auto *TD = dyn_cast<VarTemplateDecl *>(From))
12002 checkTemplate(TD);
12003 else if (auto *TD =
12004 dyn_cast<VarTemplatePartialSpecializationDecl *>(From)) {
12005 if (!CheckDeclaration(TD))
12006 diagnose(TD, true);
12007 checkTemplate(TD);
12008 }
12009 }
12010
12011 void checkInstantiated(EnumDecl *FD) {}
12012
12013 template<typename TemplDecl>
12014 void checkTemplate(TemplDecl *TD) {
12015 if (TD->isMemberSpecialization()) {
12016 if (!CheckMemberSpecialization(TD))
12017 diagnose(TD->getMostRecentDecl(), false);
12018 }
12019 }
12020};
12021} // end anonymous namespace
12022
12024 if (!getLangOpts().Modules)
12025 return;
12026
12027 ExplicitSpecializationVisibilityChecker(*this, Loc,
12029 .check(Spec);
12030}
12031
12033 NamedDecl *Spec) {
12034 if (!getLangOpts().CPlusPlusModules)
12035 return checkSpecializationVisibility(Loc, Spec);
12036
12037 ExplicitSpecializationVisibilityChecker(*this, Loc,
12039 .check(Spec);
12040}
12041
12044 return N->getLocation();
12045 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12047 return FD->getLocation();
12050 return N->getLocation();
12051 }
12052 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12053 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12054 continue;
12055 return CSC.PointOfInstantiation;
12056 }
12057 return N->getLocation();
12058}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static ExprResult BuildExpressionFromReflection(Sema &S, const APValue &RV, SourceLocation CaretCaretLoc)
Construct a new reflect expression that refers to the given entity with the given source-location of ...
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static QualType sortBuiltinTemplatePack(ASTContext &Context, ArrayRef< TemplateArgument > InputArgs)
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static void diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D)
Diagnose a missing template argument.
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, bool IsSpecified, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
const LValueBase getLValueBase() const
Definition APValue.cpp:1137
const void * getReflectionOpaqueOperand() const
Definition APValue.h:791
APSInt & getInt()
Definition APValue.h:577
APSInt & getComplexIntImag()
Definition APValue.h:615
ValueKind getKind() const
Definition APValue.h:537
APFixedPoint & getFixedPoint()
Definition APValue.h:599
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1220
APValue & getVectorElt(unsigned I)
Definition APValue.h:651
unsigned getVectorLength() const
Definition APValue.h:659
bool isLValue() const
Definition APValue.h:554
bool isMemberPointer() const
Definition APValue.h:560
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:167
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
bool isNullPointer() const
Definition APValue.cpp:1173
APSInt & getComplexIntReal()
Definition APValue.h:607
APFloat & getComplexFloatImag()
Definition APValue.h:631
APFloat & getComplexFloatReal()
Definition APValue.h:623
APFloat & getFloat()
Definition APValue.h:591
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3991
QualType getElementType() const
Definition TypeBase.h:3833
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8496
Attr - This represents one attribute.
Definition Attr.h:47
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2516
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2534
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2584
TemplateName getNamedConcept() const
Definition TypeLoc.h:2558
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2577
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2552
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2564
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8538
Pointer to a block type.
Definition TypeBase.h:3654
QualType getPointeeType() const
Definition TypeBase.h:3666
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:3246
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:2142
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:740
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3924
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1581
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2032
base_class_range bases()
Definition DeclCXX.h:609
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2039
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2073
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:531
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, const TypeSourceInfo *TSI)
Definition ExprCXX.cpp:1983
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:187
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1073
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3363
QualType getElementType() const
Definition TypeBase.h:3373
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateName NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3859
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4623
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents an opaque OpenCL cooperative matrix type.
Definition TypeBase.h:4718
QualType getElementType() const
Returns the element type.
Definition TypeBase.h:4743
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2263
bool isFileContext() const
Definition DeclBase.h:2201
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:2223
bool isTranslationUnit() const
Definition DeclBase.h:2206
bool isRecord() const
Definition DeclBase.h:2210
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2165
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1416
ValueDecl * getDecl()
Definition Expr.h:1383
Captures information about "declaration specifiers".
Definition DeclSpec.h:284
bool isVirtualSpecified() const
Definition DeclSpec.h:725
void ClearStorageClassSpecs()
Definition DeclSpec.h:570
bool isNoreturnSpecified() const
Definition DeclSpec.h:738
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:565
SCS getStorageClassSpec() const
Definition DeclSpec.h:556
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:630
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:629
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:739
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:731
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:557
ParsedAttributes & getAttributes()
Definition DeclSpec.h:950
bool isInlineSpecified() const
Definition DeclSpec.h:714
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:566
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:726
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:913
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:717
bool hasExplicitSpecifier() const
Definition DeclSpec.h:728
bool hasConstexprSpecifier() const
Definition DeclSpec.h:914
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1079
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
T * getAttr() const
Definition DeclBase.h:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
@ FOK_None
Not a friend object.
Definition DeclBase.h:1235
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:825
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1198
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2809
bool isInvalidDecl() const
Definition DeclBase.h:597
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:457
AccessSpecifier getAccess() const
Definition DeclBase.h:516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:816
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:839
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2000
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2154
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2445
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2850
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2190
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2173
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2169
bool hasEllipsis() const
Definition DeclSpec.h:2849
bool isInvalidType() const
Definition DeclSpec.h:2838
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2189
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2161
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2439
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4160
QualType getPointeeType() const
Definition TypeBase.h:4172
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2724
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2704
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2713
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3564
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:574
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4110
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4200
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4816
static DependentTemplateIdExpr * Create(const ASTContext &Context, const DeclarationNameInfo &NameInfo, TemplateName Name, const TemplateArgumentListInfo &TemplateArgs)
Definition ExprCXX.cpp:423
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3510
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4458
QualType getElementType() const
Definition TypeBase.h:4470
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4192
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4464
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5265
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3135
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3130
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:872
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3110
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:4111
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
ExtVectorType - Extended vector type.
Definition TypeBase.h:4498
Represents a member of a struct/union/class.
Definition Decl.h:3341
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
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:102
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1007
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1086
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
Represents a function declaration or definition.
Definition Decl.h:2082
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2645
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4283
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4612
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4391
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4250
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3823
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4222
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:4456
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2531
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4495
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3177
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4243
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:5228
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5650
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5939
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5935
ArrayRef< QualType > param_types() const
Definition TypeBase.h:6090
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:5186
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3922
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:4008
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5377
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
Represents a linkage specification.
Definition DeclCXX.h:3062
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
A global _GUID constant.
Definition DeclCXX.h:4468
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4587
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3784
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5874
QualType getPointeeType() const
Definition TypeBase.h:3770
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:242
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1685
NamedDecl * getMostRecentDecl()
Definition Decl.h:503
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:719
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1947
Represent a C++ namespace.
Definition Decl.h:594
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8265
Represents a pointer to an Objective C object.
Definition TypeBase.h:8321
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1162
@ CSK_Normal
Normal lookup.
Definition Overload.h:1166
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1378
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:1429
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4417
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2756
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8509
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3404
QualType getPointeeType() const
Definition TypeBase.h:3414
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8769
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3848
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8680
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:8865
QualType getCanonicalType() const
Definition TypeBase.h:8732
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8774
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3841
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
bool ValidateCandidate(const TypoCorrection &Candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
QualifiedLookupValidatorCCC(bool HasQualifier)
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3734
Represents a struct/union/class.
Definition Decl.h:4506
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4690
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5517
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3679
QualType getPointeeType() const
Definition TypeBase.h:3701
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
Scope * getDeclParent()
Definition Scope.h:321
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
Scope * getTemplateParamParent()
Definition Scope.h:318
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:120
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:49
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:14008
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8715
A RAII object to temporarily push a declaration context.
Definition Sema.h:3683
Whether and why a template name is required in this lookup.
Definition Sema.h:11734
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11742
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12792
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12826
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7961
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13955
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13406
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2721
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9608
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9612
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9620
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9615
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:9924
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:1518
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4366
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:2126
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:11705
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12303
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12306
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12310
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1339
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:231
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:935
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:773
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:1243
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:12482
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12500
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12490
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12510
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:11755
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11762
@ None
This is not assumed to be a template name.
Definition Sema.h:11757
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11759
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:11691
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:930
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
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:14832
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14820
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14829
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14823
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14847
const LangOptions & getLangOpts() const
Definition Sema.h:928
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1338
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:1337
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:652
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:1491
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
ExprResult CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateName Template, const TemplateArgumentListInfo *TemplateArgs)
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:14046
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:15886
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ASTConsumer & Consumer
Definition Sema.h:1340
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:4879
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:6955
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6934
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:14346
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static QualType getTypeOfConstantTemplateParameter(const TemplateArgument &Arg)
Determine the declared type of the constant template parameter that Arg names, if any.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11732
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:528
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:11915
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11925
@ TPC_FriendFunctionTemplate
Definition Sema.h:11923
@ TPC_ClassTemplateMember
Definition Sema.h:11921
@ TPC_FunctionTemplate
Definition Sema.h:11920
@ TPC_FriendClassTemplate
Definition Sema.h:11922
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11924
friend class InitializationSequence
Definition Sema.h:1633
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6551
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6635
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1331
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3676
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11697
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:151
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:9933
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13249
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8928
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:14043
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4718
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
StringRef getKindName() const
Definition Decl.h:4094
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:5017
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5153
TagKind getTagKind() const
Definition Decl.h:4098
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
TemplateTemplateParmDecl * getAsTemplateTemplateParmDecl() const
Retrieve the template template parameter that this template name refers to, if any.
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:653
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3869
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:224
Represents a declaration of a type.
Definition Decl.h:3694
const Type * getTypeForDecl() const
Definition Decl.h:3719
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3728
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:892
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6560
A container of type source information.
Definition TypeBase.h:8651
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:8662
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBooleanType() const
Definition TypeBase.h:9447
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2433
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2501
bool isRValueReferenceType() const
Definition TypeBase.h:8949
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:845
bool isArrayType() const
Definition TypeBase.h:9016
bool isPointerType() const
Definition TypeBase.h:8917
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9604
bool isReferenceType() const
Definition TypeBase.h:8941
bool isEnumeralType() const
Definition TypeBase.h:9048
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2300
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:595
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9432
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:9108
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2981
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2872
bool isLValueReferenceType() const
Definition TypeBase.h:8945
bool isBitIntType() const
Definition TypeBase.h:9196
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:9040
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2864
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2251
bool isMemberPointerType() const
Definition TypeBase.h:8998
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9453
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:5230
bool isPointerOrReferenceType() const
Definition TypeBase.h:8921
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2678
bool isFunctionType() const
Definition TypeBase.h:8913
bool isVectorType() const
Definition TypeBase.h:9056
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
bool isNullPtrType() const
Definition TypeBase.h:9347
bool isRecordType() const
Definition TypeBase.h:9044
QualType getUnderlyingType() const
Definition Decl.h:3798
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4398
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1114
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1326
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1323
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1142
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1196
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1166
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:464
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6365
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3987
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3446
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3510
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:934
TLSKind getTLSKind() const
Definition Decl.cpp:2151
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2766
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:2899
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:2794
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:2773
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2892
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4065
Represents a GCC generic vector type.
Definition TypeBase.h:4399
QualType getElementType() const
Definition TypeBase.h:4413
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
const PartialDiagnosticAt & peekSFINAEDiagnostic() const
Peek at the SFINAE diagnostic.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1983
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1843
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:922
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:153
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:598
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1106
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1098
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1092
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1094
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_public
Definition Specifiers.h:128
@ AS_none
Definition Specifiers.h:131
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:252
@ SC_Extern
Definition Specifiers.h:255
@ TSCS_unspecified
Definition Specifiers.h:240
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:445
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6273
@ Enum
The "enum" keyword.
Definition TypeBase.h:6287
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:374
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:218
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6248
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6269
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6262
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6266
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2250
CharacterLiteralKind
Definition Expr.h:1648
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:651
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
Extra information about a function prototype.
Definition TypeBase.h:5735
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3541
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3558
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3523
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:935
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12341
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12337
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12330
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12327
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12327
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13457
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13561
A stack object to be created when performing template instantiation.
Definition Sema.h:13651
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13804
NamedDecl * Previous
Definition Sema.h:361
Location information for a TemplateArgument.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1125