Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/Type.h"
30#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/Overload.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/SemaCUDA.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/SmallBitVector.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/SaveAndRestore.h"
45
46#include <optional>
47using namespace clang;
48using namespace sema;
49
50// Exported for use by Parser.
53 unsigned N) {
54 if (!N) return SourceRange();
55 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56}
57
58unsigned Sema::getTemplateDepth(Scope *S) const {
59 unsigned Depth = 0;
60
61 // Each template parameter scope represents one level of template parameter
62 // depth.
63 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65 ++Depth;
66 }
67
68 // Note that there are template parameters with the given depth.
69 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70
71 // Look for parameters of an enclosing generic lambda. We don't create a
72 // template parameter scope for these.
74 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75 if (!LSI->TemplateParams.empty()) {
76 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77 break;
78 }
79 if (LSI->GLTemplateParameterList) {
80 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81 break;
82 }
83 }
84 }
85
86 // Look for parameters of an enclosing terse function template. We don't
87 // create a template parameter scope for these either.
88 for (const InventedTemplateParameterInfo &Info :
90 if (!Info.TemplateParams.empty()) {
91 ParamsAtDepth(Info.AutoTemplateParameterDepth);
92 break;
93 }
94 }
95
96 return Depth;
97}
98
99/// \brief Determine whether the declaration found is acceptable as the name
100/// of a template and, if so, return that template declaration. Otherwise,
101/// returns null.
102///
103/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104/// is true. In all other cases it will return a TemplateDecl (or null).
106 bool AllowFunctionTemplates,
107 bool AllowDependent) {
108 D = D->getUnderlyingDecl();
109
110 if (isa<TemplateDecl>(D)) {
111 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112 return nullptr;
113
114 return D;
115 }
116
117 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118 // C++ [temp.local]p1:
119 // Like normal (non-template) classes, class templates have an
120 // injected-class-name (Clause 9). The injected-class-name
121 // can be used with or without a template-argument-list. When
122 // it is used without a template-argument-list, it is
123 // equivalent to the injected-class-name followed by the
124 // template-parameters of the class template enclosed in
125 // <>. When it is used with a template-argument-list, it
126 // refers to the specified class template specialization,
127 // which could be the current specialization or another
128 // specialization.
129 if (Record->isInjectedClassName()) {
130 Record = cast<CXXRecordDecl>(Record->getDeclContext());
131 if (Record->getDescribedClassTemplate())
132 return Record->getDescribedClassTemplate();
133
134 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135 return Spec->getSpecializedTemplate();
136 }
137
138 return nullptr;
139 }
140
141 // 'using Dependent::foo;' can resolve to a template name.
142 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143 // injected-class-name).
144 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145 return D;
146
147 return nullptr;
148}
149
151 bool AllowFunctionTemplates,
152 bool AllowDependent) {
153 LookupResult::Filter filter = R.makeFilter();
154 while (filter.hasNext()) {
155 NamedDecl *Orig = filter.next();
156 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157 filter.erase();
158 }
159 filter.done();
160}
161
163 bool AllowFunctionTemplates,
164 bool AllowDependent,
165 bool AllowNonTemplateFunctions) {
166 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168 return true;
169 if (AllowNonTemplateFunctions &&
170 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171 return true;
172 }
173
174 return false;
175}
176
178 CXXScopeSpec &SS,
179 bool hasTemplateKeyword,
180 const UnqualifiedId &Name,
181 ParsedType ObjectTypePtr,
182 bool EnteringContext,
183 TemplateTy &TemplateResult,
184 bool &MemberOfUnknownSpecialization,
185 bool Disambiguation) {
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,
216 /*AllowTypoCorrection=*/!Disambiguation))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241 if (isa<FunctionTemplateDecl>(FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
280 } else {
281 if (!D) {
283 assert(D && "unambiguous result is not a template name");
284 }
285
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299 Template);
300 }
301
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
307 } else {
311 TemplateKind =
313 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
317 }
318 }
319
321 S->getTemplateParamParent() == nullptr)
322 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
323 // Recover by returning the template, even though we would never be able to
324 // substitute it.
325
326 TemplateResult = TemplateTy::make(Template);
327 return TemplateKind;
328}
329
331 SourceLocation NameLoc, CXXScopeSpec &SS,
332 ParsedTemplateTy *Template /*=nullptr*/) {
333 // We could use redeclaration lookup here, but we don't need to: the
334 // syntactic form of a deduction guide is enough to identify it even
335 // if we can't look up the template name at all.
336 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
337 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
338 /*EnteringContext*/ false))
339 return false;
340
341 if (R.empty()) return false;
342 if (R.isAmbiguous()) {
343 // FIXME: Diagnose an ambiguity if we find at least one template.
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
351 if (!TD || !getAsTypeTemplateDecl(TD))
352 return false;
353
354 if (Template) {
355 TemplateName Name = Context.getQualifiedTemplateName(
356 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
357 *Template = TemplateTy::make(Name);
358 }
359 return true;
360}
361
363 SourceLocation IILoc,
364 Scope *S,
365 const CXXScopeSpec *SS,
366 TemplateTy &SuggestedTemplate,
367 TemplateNameKind &SuggestedKind) {
368 // We can't recover unless there's a dependent scope specifier preceding the
369 // template name.
370 // FIXME: Typo correction?
371 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
373 return false;
374
375 // The code is missing a 'template' keyword prior to the dependent template
376 // name.
377 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
378 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
379 Diag(IILoc, diag::err_template_kw_missing)
380 << SuggestedTemplate.get()
381 << FixItHint::CreateInsertion(IILoc, "template ");
382 SuggestedKind = TNK_Dependent_template_name;
383 return true;
384}
385
387 QualType ObjectType, bool EnteringContext,
388 RequiredTemplateKind RequiredTemplate,
390 bool AllowTypoCorrection) {
391 if (ATK)
393
394 if (SS.isInvalid())
395 return true;
396
397 Found.setTemplateNameLookup(true);
398
399 // Determine where to perform name lookup
400 DeclContext *LookupCtx = nullptr;
401 bool IsDependent = false;
402 if (!ObjectType.isNull()) {
403 // This nested-name-specifier occurs in a member access expression, e.g.,
404 // x->B::f, and we are looking into the type of the object.
405 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
406 LookupCtx = computeDeclContext(ObjectType);
407 IsDependent = !LookupCtx && ObjectType->isDependentType();
408 assert((IsDependent || !ObjectType->isIncompleteType() ||
409 !ObjectType->getAs<TagType>() ||
410 ObjectType->castAs<TagType>()
411 ->getOriginalDecl()
412 ->isEntityBeingDefined()) &&
413 "Caller should have completed object type");
414
415 // Template names cannot appear inside an Objective-C class or object type
416 // or a vector type.
417 //
418 // FIXME: This is wrong. For example:
419 //
420 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
421 // Vec<int> vi;
422 // vi.Vec<int>::~Vec<int>();
423 //
424 // ... should be accepted but we will not treat 'Vec' as a template name
425 // here. The right thing to do would be to check if the name is a valid
426 // vector component name, and look up a template name if not. And similarly
427 // for lookups into Objective-C class and object types, where the same
428 // problem can arise.
429 if (ObjectType->isObjCObjectOrInterfaceType() ||
430 ObjectType->isVectorType()) {
431 Found.clear();
432 return false;
433 }
434 } else if (SS.isNotEmpty()) {
435 // This nested-name-specifier occurs after another nested-name-specifier,
436 // so long into the context associated with the prior nested-name-specifier.
437 LookupCtx = computeDeclContext(SS, EnteringContext);
438 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
439
440 // The declaration context must be complete.
441 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
442 return true;
443 }
444
445 bool ObjectTypeSearchedInScope = false;
446 bool AllowFunctionTemplatesInLookup = true;
447 if (LookupCtx) {
448 // Perform "qualified" name lookup into the declaration context we
449 // computed, which is either the type of the base of a member access
450 // expression or the declaration context associated with a prior
451 // nested-name-specifier.
452 LookupQualifiedName(Found, LookupCtx);
453
454 // FIXME: The C++ standard does not clearly specify what happens in the
455 // case where the object type is dependent, and implementations vary. In
456 // Clang, we treat a name after a . or -> as a template-name if lookup
457 // finds a non-dependent member or member of the current instantiation that
458 // is a type template, or finds no such members and lookup in the context
459 // of the postfix-expression finds a type template. In the latter case, the
460 // name is nonetheless dependent, and we may resolve it to a member of an
461 // unknown specialization when we come to instantiate the template.
462 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
463 }
464
465 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
466 // C++ [basic.lookup.classref]p1:
467 // In a class member access expression (5.2.5), if the . or -> token is
468 // immediately followed by an identifier followed by a <, the
469 // identifier must be looked up to determine whether the < is the
470 // beginning of a template argument list (14.2) or a less-than operator.
471 // The identifier is first looked up in the class of the object
472 // expression. If the identifier is not found, it is then looked up in
473 // the context of the entire postfix-expression and shall name a class
474 // template.
475 if (S)
476 LookupName(Found, S);
477
478 if (!ObjectType.isNull()) {
479 // FIXME: We should filter out all non-type templates here, particularly
480 // variable templates and concepts. But the exclusion of alias templates
481 // and template template parameters is a wording defect.
482 AllowFunctionTemplatesInLookup = false;
483 ObjectTypeSearchedInScope = true;
484 }
485
486 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
487 }
488
489 if (Found.isAmbiguous())
490 return false;
491
492 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
493 !RequiredTemplate.hasTemplateKeyword()) {
494 // C++2a [temp.names]p2:
495 // A name is also considered to refer to a template if it is an
496 // unqualified-id followed by a < and name lookup finds either one or more
497 // functions or finds nothing.
498 //
499 // To keep our behavior consistent, we apply the "finds nothing" part in
500 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
501 // successfully form a call to an undeclared template-id.
502 bool AllFunctions =
503 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
505 });
506 if (AllFunctions || (Found.empty() && !IsDependent)) {
507 // If lookup found any functions, or if this is a name that can only be
508 // used for a function, then strongly assume this is a function
509 // template-id.
510 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
513 Found.clear();
514 return false;
515 }
516 }
517
518 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
519 // If we did not find any names, and this is not a disambiguation, attempt
520 // to correct any typos.
521 DeclarationName Name = Found.getLookupName();
522 Found.clear();
523 // Simple filter callback that, for keywords, only accepts the C++ *_cast
524 DefaultFilterCCC FilterCCC{};
525 FilterCCC.WantTypeSpecifiers = false;
526 FilterCCC.WantExpressionKeywords = false;
527 FilterCCC.WantRemainingKeywords = false;
528 FilterCCC.WantCXXNamedCasts = true;
529 if (TypoCorrection Corrected = CorrectTypo(
530 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
531 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
532 if (auto *ND = Corrected.getFoundDecl())
533 Found.addDecl(ND);
535 if (Found.isAmbiguous()) {
536 Found.clear();
537 } else if (!Found.empty()) {
538 // Do not erase the typo-corrected result to avoid duplicated
539 // diagnostics.
540 AllowFunctionTemplatesInLookup = true;
541 Found.setLookupName(Corrected.getCorrection());
542 if (LookupCtx) {
543 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
544 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
545 Name.getAsString() == CorrectedStr;
546 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
547 << Name << LookupCtx << DroppedSpecifier
548 << SS.getRange());
549 } else {
550 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
551 }
552 }
553 }
554 }
555
556 NamedDecl *ExampleLookupResult =
557 Found.empty() ? nullptr : Found.getRepresentativeDecl();
558 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
559 if (Found.empty()) {
560 if (IsDependent) {
561 Found.setNotFoundInCurrentInstantiation();
562 return false;
563 }
564
565 // If a 'template' keyword was used, a lookup that finds only non-template
566 // names is an error.
567 if (ExampleLookupResult && RequiredTemplate) {
568 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
569 << Found.getLookupName() << SS.getRange()
570 << RequiredTemplate.hasTemplateKeyword()
571 << RequiredTemplate.getTemplateKeywordLoc();
572 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
573 diag::note_template_kw_refers_to_non_template)
574 << Found.getLookupName();
575 return true;
576 }
577
578 return false;
579 }
580
581 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
583 // C++03 [basic.lookup.classref]p1:
584 // [...] If the lookup in the class of the object expression finds a
585 // template, the name is also looked up in the context of the entire
586 // postfix-expression and [...]
587 //
588 // Note: C++11 does not perform this second lookup.
589 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
591 FoundOuter.setTemplateNameLookup(true);
592 LookupName(FoundOuter, S);
593 // FIXME: We silently accept an ambiguous lookup here, in violation of
594 // [basic.lookup]/1.
595 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
596
597 NamedDecl *OuterTemplate;
598 if (FoundOuter.empty()) {
599 // - if the name is not found, the name found in the class of the
600 // object expression is used, otherwise
601 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
602 !(OuterTemplate =
603 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
604 // - if the name is found in the context of the entire
605 // postfix-expression and does not name a class template, the name
606 // found in the class of the object expression is used, otherwise
607 FoundOuter.clear();
608 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
609 // - if the name found is a class template, it must refer to the same
610 // entity as the one found in the class of the object expression,
611 // otherwise the program is ill-formed.
612 if (!Found.isSingleResult() ||
613 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
614 OuterTemplate->getCanonicalDecl()) {
615 Diag(Found.getNameLoc(),
616 diag::ext_nested_name_member_ref_lookup_ambiguous)
617 << Found.getLookupName()
618 << ObjectType;
619 Diag(Found.getRepresentativeDecl()->getLocation(),
620 diag::note_ambig_member_ref_object_type)
621 << ObjectType;
622 Diag(FoundOuter.getFoundDecl()->getLocation(),
623 diag::note_ambig_member_ref_scope);
624
625 // Recover by taking the template that we found in the object
626 // expression's type.
627 }
628 }
629 }
630
631 return false;
632}
633
637 if (TemplateName.isInvalid())
638 return;
639
640 DeclarationNameInfo NameInfo;
641 CXXScopeSpec SS;
642 LookupNameKind LookupKind;
643
644 DeclContext *LookupCtx = nullptr;
645 NamedDecl *Found = nullptr;
646 bool MissingTemplateKeyword = false;
647
648 // Figure out what name we looked up.
649 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
650 NameInfo = DRE->getNameInfo();
651 SS.Adopt(DRE->getQualifierLoc());
652 LookupKind = LookupOrdinaryName;
653 Found = DRE->getFoundDecl();
654 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
655 NameInfo = ME->getMemberNameInfo();
656 SS.Adopt(ME->getQualifierLoc());
657 LookupKind = LookupMemberName;
658 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
659 Found = ME->getMemberDecl();
660 } else if (auto *DSDRE =
661 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
662 NameInfo = DSDRE->getNameInfo();
663 SS.Adopt(DSDRE->getQualifierLoc());
664 MissingTemplateKeyword = true;
665 } else if (auto *DSME =
666 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
667 NameInfo = DSME->getMemberNameInfo();
668 SS.Adopt(DSME->getQualifierLoc());
669 MissingTemplateKeyword = true;
670 } else {
671 llvm_unreachable("unexpected kind of potential template name");
672 }
673
674 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
675 // was missing.
676 if (MissingTemplateKeyword) {
677 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
678 << NameInfo.getName() << SourceRange(Less, Greater);
679 return;
680 }
681
682 // Try to correct the name by looking for templates and C++ named casts.
683 struct TemplateCandidateFilter : CorrectionCandidateCallback {
684 Sema &S;
685 TemplateCandidateFilter(Sema &S) : S(S) {
686 WantTypeSpecifiers = false;
687 WantExpressionKeywords = false;
688 WantRemainingKeywords = false;
689 WantCXXNamedCasts = true;
690 };
691 bool ValidateCandidate(const TypoCorrection &Candidate) override {
692 if (auto *ND = Candidate.getCorrectionDecl())
693 return S.getAsTemplateNameDecl(ND);
694 return Candidate.isKeyword();
695 }
696
697 std::unique_ptr<CorrectionCandidateCallback> clone() override {
698 return std::make_unique<TemplateCandidateFilter>(*this);
699 }
700 };
701
702 DeclarationName Name = NameInfo.getName();
703 TemplateCandidateFilter CCC(*this);
704 if (TypoCorrection Corrected =
705 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
706 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
707 auto *ND = Corrected.getFoundDecl();
708 if (ND)
709 ND = getAsTemplateNameDecl(ND);
710 if (ND || Corrected.isKeyword()) {
711 if (LookupCtx) {
712 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
713 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
714 Name.getAsString() == CorrectedStr;
715 diagnoseTypo(Corrected,
716 PDiag(diag::err_non_template_in_member_template_id_suggest)
717 << Name << LookupCtx << DroppedSpecifier
718 << SS.getRange(), false);
719 } else {
720 diagnoseTypo(Corrected,
721 PDiag(diag::err_non_template_in_template_id_suggest)
722 << Name, false);
723 }
724 if (Found)
725 Diag(Found->getLocation(),
726 diag::note_non_template_in_template_id_found);
727 return;
728 }
729 }
730
731 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
732 << Name << SourceRange(Less, Greater);
733 if (Found)
734 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
735}
736
739 SourceLocation TemplateKWLoc,
740 const DeclarationNameInfo &NameInfo,
741 bool isAddressOfOperand,
742 const TemplateArgumentListInfo *TemplateArgs) {
743 if (SS.isEmpty()) {
744 // FIXME: This codepath is only used by dependent unqualified names
745 // (e.g. a dependent conversion-function-id, or operator= once we support
746 // it). It doesn't quite do the right thing, and it will silently fail if
747 // getCurrentThisType() returns null.
748 QualType ThisType = getCurrentThisType();
749 if (ThisType.isNull())
750 return ExprError();
751
753 Context, /*Base=*/nullptr, ThisType,
754 /*IsArrow=*/!Context.getLangOpts().HLSL,
755 /*OperatorLoc=*/SourceLocation(),
756 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
757 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
758 }
759 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
760}
761
764 SourceLocation TemplateKWLoc,
765 const DeclarationNameInfo &NameInfo,
766 const TemplateArgumentListInfo *TemplateArgs) {
767 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
768 if (!SS.isValid())
769 return CreateRecoveryExpr(
770 SS.getBeginLoc(),
771 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
772
774 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
775 TemplateArgs);
776}
777
779 NamedDecl *Instantiation,
780 bool InstantiatedFromMember,
781 const NamedDecl *Pattern,
782 const NamedDecl *PatternDef,
784 bool Complain, bool *Unreachable) {
785 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
786 isa<VarDecl>(Instantiation));
787
788 bool IsEntityBeingDefined = false;
789 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
790 IsEntityBeingDefined = TD->isBeingDefined();
791
792 if (PatternDef && !IsEntityBeingDefined) {
793 NamedDecl *SuggestedDef = nullptr;
794 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
795 &SuggestedDef,
796 /*OnlyNeedComplete*/ false)) {
797 if (Unreachable)
798 *Unreachable = true;
799 // If we're allowed to diagnose this and recover, do so.
800 bool Recover = Complain && !isSFINAEContext();
801 if (Complain)
802 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
804 return !Recover;
805 }
806 return false;
807 }
808
809 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
810 return true;
811
812 CanQualType InstantiationTy;
813 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
814 InstantiationTy = Context.getCanonicalTagType(TD);
815 if (PatternDef) {
816 Diag(PointOfInstantiation,
817 diag::err_template_instantiate_within_definition)
818 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
819 << InstantiationTy;
820 // Not much point in noting the template declaration here, since
821 // we're lexically inside it.
822 Instantiation->setInvalidDecl();
823 } else if (InstantiatedFromMember) {
824 if (isa<FunctionDecl>(Instantiation)) {
825 Diag(PointOfInstantiation,
826 diag::err_explicit_instantiation_undefined_member)
827 << /*member function*/ 1 << Instantiation->getDeclName()
828 << Instantiation->getDeclContext();
829 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
830 } else {
831 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
832 Diag(PointOfInstantiation,
833 diag::err_implicit_instantiate_member_undefined)
834 << InstantiationTy;
835 Diag(Pattern->getLocation(), diag::note_member_declared_at);
836 }
837 } else {
838 if (isa<FunctionDecl>(Instantiation)) {
839 Diag(PointOfInstantiation,
840 diag::err_explicit_instantiation_undefined_func_template)
841 << Pattern;
842 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
843 } else if (isa<TagDecl>(Instantiation)) {
844 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
845 << (TSK != TSK_ImplicitInstantiation)
846 << InstantiationTy;
847 NoteTemplateLocation(*Pattern);
848 } else {
849 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
850 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
851 Diag(PointOfInstantiation,
852 diag::err_explicit_instantiation_undefined_var_template)
853 << Instantiation;
854 Instantiation->setInvalidDecl();
855 } else
856 Diag(PointOfInstantiation,
857 diag::err_explicit_instantiation_undefined_member)
858 << /*static data member*/ 2 << Instantiation->getDeclName()
859 << Instantiation->getDeclContext();
860 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
861 }
862 }
863
864 // In general, Instantiation isn't marked invalid to get more than one
865 // error for multiple undefined instantiations. But the code that does
866 // explicit declaration -> explicit definition conversion can't handle
867 // invalid declarations, so mark as invalid in that case.
869 Instantiation->setInvalidDecl();
870 return true;
871}
872
874 bool SupportedForCompatibility) {
875 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
876
877 // C++23 [temp.local]p6:
878 // The name of a template-parameter shall not be bound to any following.
879 // declaration whose locus is contained by the scope to which the
880 // template-parameter belongs.
881 //
882 // When MSVC compatibility is enabled, the diagnostic is always a warning
883 // by default. Otherwise, it an error unless SupportedForCompatibility is
884 // true, in which case it is a default-to-error warning.
885 unsigned DiagId =
886 getLangOpts().MSVCCompat
887 ? diag::ext_template_param_shadow
888 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
889 : diag::err_template_param_shadow);
890 const auto *ND = cast<NamedDecl>(PrevDecl);
891 Diag(Loc, DiagId) << ND->getDeclName();
893}
894
896 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
897 D = Temp->getTemplatedDecl();
898 return Temp;
899 }
900 return nullptr;
901}
902
904 SourceLocation EllipsisLoc) const {
905 assert(Kind == Template &&
906 "Only template template arguments can be pack expansions here");
907 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
908 "Template template argument pack expansion without packs");
910 Result.EllipsisLoc = EllipsisLoc;
911 return Result;
912}
913
915 const ParsedTemplateArgument &Arg) {
916
917 switch (Arg.getKind()) {
919 TypeSourceInfo *DI;
920 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
921 if (!DI)
922 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
924 }
925
927 Expr *E = Arg.getAsExpr();
928 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
929 }
930
933 TemplateArgument TArg;
934 if (Arg.getEllipsisLoc().isValid())
935 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
936 else
937 TArg = Template;
938 return TemplateArgumentLoc(
939 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
941 Arg.getNameLoc(), Arg.getEllipsisLoc());
942 }
943 }
944
945 llvm_unreachable("Unhandled parsed template argument");
946}
947
949 TemplateArgumentListInfo &TemplateArgs) {
950 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
951 TemplateArgs.addArgument(translateTemplateArgument(*this,
952 TemplateArgsIn[I]));
953}
954
956 SourceLocation Loc,
957 const IdentifierInfo *Name) {
958 NamedDecl *PrevDecl =
959 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
961 if (PrevDecl && PrevDecl->isTemplateParameter())
962 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
963}
964
966 TypeSourceInfo *TInfo;
967 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
968 if (T.isNull())
969 return ParsedTemplateArgument();
970 assert(TInfo && "template argument with no location");
971
972 // If we might have formed a deduced template specialization type, convert
973 // it to a template template argument.
974 if (getLangOpts().CPlusPlus17) {
975 TypeLoc TL = TInfo->getTypeLoc();
976 SourceLocation EllipsisLoc;
977 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
978 EllipsisLoc = PET.getEllipsisLoc();
979 TL = PET.getPatternLoc();
980 }
981
982 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
983 TemplateName Name = DTST.getTypePtr()->getTemplateName();
984 CXXScopeSpec SS;
985 SS.Adopt(DTST.getQualifierLoc());
986 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
987 TemplateTy::make(Name),
988 DTST.getTemplateNameLoc());
989 if (EllipsisLoc.isValid())
990 Result = Result.getTemplatePackExpansion(EllipsisLoc);
991 return Result;
992 }
993 }
994
995 // This is a normal type template argument. Note, if the type template
996 // argument is an injected-class-name for a template, it has a dual nature
997 // and can be used as either a type or a template. We handle that in
998 // convertTypeTemplateArgumentToTemplate.
1000 ParsedType.get().getAsOpaquePtr(),
1001 TInfo->getTypeLoc().getBeginLoc());
1002}
1003
1005 SourceLocation EllipsisLoc,
1006 SourceLocation KeyLoc,
1007 IdentifierInfo *ParamName,
1008 SourceLocation ParamNameLoc,
1009 unsigned Depth, unsigned Position,
1010 SourceLocation EqualLoc,
1011 ParsedType DefaultArg,
1012 bool HasTypeConstraint) {
1013 assert(S->isTemplateParamScope() &&
1014 "Template type parameter not in template parameter scope!");
1015
1016 bool IsParameterPack = EllipsisLoc.isValid();
1018 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1019 KeyLoc, ParamNameLoc, Depth, Position,
1020 ParamName, Typename, IsParameterPack,
1021 HasTypeConstraint);
1022 Param->setAccess(AS_public);
1023
1024 if (Param->isParameterPack())
1025 if (auto *CSI = getEnclosingLambdaOrBlock())
1026 CSI->LocalPacks.push_back(Param);
1027
1028 if (ParamName) {
1029 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1030
1031 // Add the template parameter into the current scope.
1032 S->AddDecl(Param);
1033 IdResolver.AddDecl(Param);
1034 }
1035
1036 // C++0x [temp.param]p9:
1037 // A default template-argument may be specified for any kind of
1038 // template-parameter that is not a template parameter pack.
1039 if (DefaultArg && IsParameterPack) {
1040 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1041 DefaultArg = nullptr;
1042 }
1043
1044 // Handle the default argument, if provided.
1045 if (DefaultArg) {
1046 TypeSourceInfo *DefaultTInfo;
1047 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1048
1049 assert(DefaultTInfo && "expected source information for type");
1050
1051 // Check for unexpanded parameter packs.
1052 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1054 return Param;
1055
1056 // Check the template argument itself.
1057 if (CheckTemplateArgument(DefaultTInfo)) {
1058 Param->setInvalidDecl();
1059 return Param;
1060 }
1061
1062 Param->setDefaultArgument(
1063 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1064 }
1065
1066 return Param;
1067}
1068
1069/// Convert the parser's template argument list representation into our form.
1072 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1073 TemplateId.RAngleLoc);
1074 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1075 TemplateId.NumArgs);
1076 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1077 return TemplateArgs;
1078}
1079
1081
1082 TemplateName TN = TypeConstr->Template.get();
1083 NamedDecl *CD = nullptr;
1084 bool IsTypeConcept = false;
1085 bool RequiresArguments = false;
1086 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1087 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1088 RequiresArguments =
1089 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1090 CD = TTP;
1091 } else {
1092 CD = TN.getAsTemplateDecl();
1093 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1094 RequiresArguments = cast<ConceptDecl>(CD)
1095 ->getTemplateParameters()
1096 ->getMinRequiredArguments() > 1;
1097 }
1098
1099 // C++2a [temp.param]p4:
1100 // [...] The concept designated by a type-constraint shall be a type
1101 // concept ([temp.concept]).
1102 if (!IsTypeConcept) {
1103 Diag(TypeConstr->TemplateNameLoc,
1104 diag::err_type_constraint_non_type_concept);
1105 return true;
1106 }
1107
1108 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1109 return true;
1110
1111 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1112
1113 if (!WereArgsSpecified && RequiresArguments) {
1114 Diag(TypeConstr->TemplateNameLoc,
1115 diag::err_type_constraint_missing_arguments)
1116 << CD;
1117 return true;
1118 }
1119 return false;
1120}
1121
1123 TemplateIdAnnotation *TypeConstr,
1124 TemplateTypeParmDecl *ConstrainedParameter,
1125 SourceLocation EllipsisLoc) {
1126 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1127 false);
1128}
1129
1131 TemplateIdAnnotation *TypeConstr,
1132 TemplateTypeParmDecl *ConstrainedParameter,
1133 SourceLocation EllipsisLoc,
1134 bool AllowUnexpandedPack) {
1135
1136 if (CheckTypeConstraint(TypeConstr))
1137 return true;
1138
1139 TemplateName TN = TypeConstr->Template.get();
1142
1143 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1144 TypeConstr->TemplateNameLoc);
1145
1146 TemplateArgumentListInfo TemplateArgs;
1147 if (TypeConstr->LAngleLoc.isValid()) {
1148 TemplateArgs =
1149 makeTemplateArgumentListInfo(*this, *TypeConstr);
1150
1151 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1152 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1154 return true;
1155 }
1156 }
1157 }
1158 return AttachTypeConstraint(
1160 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1161 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1162 ConstrainedParameter, EllipsisLoc);
1163}
1164
1165template <typename ArgumentLocAppender>
1168 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1169 SourceLocation RAngleLoc, QualType ConstrainedType,
1170 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1171 SourceLocation EllipsisLoc) {
1172
1173 TemplateArgumentListInfo ConstraintArgs;
1174 ConstraintArgs.addArgument(
1176 /*NTTPType=*/QualType(), ParamNameLoc));
1177
1178 ConstraintArgs.setRAngleLoc(RAngleLoc);
1179 ConstraintArgs.setLAngleLoc(LAngleLoc);
1180 Appender(ConstraintArgs);
1181
1182 // C++2a [temp.param]p4:
1183 // [...] This constraint-expression E is called the immediately-declared
1184 // constraint of T. [...]
1185 CXXScopeSpec SS;
1186 SS.Adopt(NS);
1187 ExprResult ImmediatelyDeclaredConstraint;
1188 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1189 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1190 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1191 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, CD,
1192 &ConstraintArgs);
1193 }
1194 // We have a template template parameter
1195 else {
1196 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1197 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1198 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1199 }
1200 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1201 return ImmediatelyDeclaredConstraint;
1202
1203 // C++2a [temp.param]p4:
1204 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1205 //
1206 // We have the following case:
1207 //
1208 // template<typename T> concept C1 = true;
1209 // template<C1... T> struct s1;
1210 //
1211 // The constraint: (C1<T> && ...)
1212 //
1213 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1214 // any unqualified lookups for 'operator&&' here.
1215 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1216 /*LParenLoc=*/SourceLocation(),
1217 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1218 EllipsisLoc, /*RHS=*/nullptr,
1219 /*RParenLoc=*/SourceLocation(),
1220 /*NumExpansions=*/std::nullopt);
1221}
1222
1224 DeclarationNameInfo NameInfo,
1225 TemplateDecl *NamedConcept,
1226 NamedDecl *FoundDecl,
1227 const TemplateArgumentListInfo *TemplateArgs,
1228 TemplateTypeParmDecl *ConstrainedParameter,
1229 SourceLocation EllipsisLoc) {
1230 // C++2a [temp.param]p4:
1231 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1232 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1233 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1235 *TemplateArgs) : nullptr;
1236
1237 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1238
1239 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1240 *this, NS, NameInfo, NamedConcept, FoundDecl,
1241 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1242 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1243 ParamAsArgument, ConstrainedParameter->getLocation(),
1244 [&](TemplateArgumentListInfo &ConstraintArgs) {
1245 if (TemplateArgs)
1246 for (const auto &ArgLoc : TemplateArgs->arguments())
1247 ConstraintArgs.addArgument(ArgLoc);
1248 },
1249 EllipsisLoc);
1250 if (ImmediatelyDeclaredConstraint.isInvalid())
1251 return true;
1252
1253 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1254 /*TemplateKWLoc=*/SourceLocation{},
1255 /*ConceptNameInfo=*/NameInfo,
1256 /*FoundDecl=*/FoundDecl,
1257 /*NamedConcept=*/NamedConcept,
1258 /*ArgsWritten=*/ArgsAsWritten);
1259 ConstrainedParameter->setTypeConstraint(
1260 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1261 return false;
1262}
1263
1265 NonTypeTemplateParmDecl *NewConstrainedParm,
1266 NonTypeTemplateParmDecl *OrigConstrainedParm,
1267 SourceLocation EllipsisLoc) {
1268 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1270 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1271 diag::err_unsupported_placeholder_constraint)
1272 << NewConstrainedParm->getTypeSourceInfo()
1273 ->getTypeLoc()
1274 .getSourceRange();
1275 return true;
1276 }
1277 // FIXME: Concepts: This should be the type of the placeholder, but this is
1278 // unclear in the wording right now.
1279 DeclRefExpr *Ref =
1280 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1281 VK_PRValue, OrigConstrainedParm->getLocation());
1282 if (!Ref)
1283 return true;
1284 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1286 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1288 OrigConstrainedParm->getLocation(),
1289 [&](TemplateArgumentListInfo &ConstraintArgs) {
1290 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1291 ConstraintArgs.addArgument(TL.getArgLoc(I));
1292 },
1293 EllipsisLoc);
1294 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1295 !ImmediatelyDeclaredConstraint.isUsable())
1296 return true;
1297
1298 NewConstrainedParm->setPlaceholderTypeConstraint(
1299 ImmediatelyDeclaredConstraint.get());
1300 return false;
1301}
1302
1304 SourceLocation Loc) {
1305 if (TSI->getType()->isUndeducedType()) {
1306 // C++17 [temp.dep.expr]p3:
1307 // An id-expression is type-dependent if it contains
1308 // - an identifier associated by name lookup with a non-type
1309 // template-parameter declared with a type that contains a
1310 // placeholder type (7.1.7.4),
1312 }
1313
1314 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1315}
1316
1318 if (T->isDependentType())
1319 return false;
1320
1321 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1322 return true;
1323
1324 if (T->isStructuralType())
1325 return false;
1326
1327 // Structural types are required to be object types or lvalue references.
1328 if (T->isRValueReferenceType()) {
1329 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1330 return true;
1331 }
1332
1333 // Don't mention structural types in our diagnostic prior to C++20. Also,
1334 // there's not much more we can say about non-scalar non-class types --
1335 // because we can't see functions or arrays here, those can only be language
1336 // extensions.
1337 if (!getLangOpts().CPlusPlus20 ||
1338 (!T->isScalarType() && !T->isRecordType())) {
1339 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1340 return true;
1341 }
1342
1343 // Structural types are required to be literal types.
1344 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1345 return true;
1346
1347 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1348
1349 // Drill down into the reason why the class is non-structural.
1350 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1351 // All members are required to be public and non-mutable, and can't be of
1352 // rvalue reference type. Check these conditions first to prefer a "local"
1353 // reason over a more distant one.
1354 for (const FieldDecl *FD : RD->fields()) {
1355 if (FD->getAccess() != AS_public) {
1356 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1357 return true;
1358 }
1359 if (FD->isMutable()) {
1360 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1361 return true;
1362 }
1363 if (FD->getType()->isRValueReferenceType()) {
1364 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1365 << T;
1366 return true;
1367 }
1368 }
1369
1370 // All bases are required to be public.
1371 for (const auto &BaseSpec : RD->bases()) {
1372 if (BaseSpec.getAccessSpecifier() != AS_public) {
1373 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1374 << T << 1;
1375 return true;
1376 }
1377 }
1378
1379 // All subobjects are required to be of structural types.
1380 SourceLocation SubLoc;
1381 QualType SubType;
1382 int Kind = -1;
1383
1384 for (const FieldDecl *FD : RD->fields()) {
1385 QualType T = Context.getBaseElementType(FD->getType());
1386 if (!T->isStructuralType()) {
1387 SubLoc = FD->getLocation();
1388 SubType = T;
1389 Kind = 0;
1390 break;
1391 }
1392 }
1393
1394 if (Kind == -1) {
1395 for (const auto &BaseSpec : RD->bases()) {
1396 QualType T = BaseSpec.getType();
1397 if (!T->isStructuralType()) {
1398 SubLoc = BaseSpec.getBaseTypeLoc();
1399 SubType = T;
1400 Kind = 1;
1401 break;
1402 }
1403 }
1404 }
1405
1406 assert(Kind != -1 && "couldn't find reason why type is not structural");
1407 Diag(SubLoc, diag::note_not_structural_subobject)
1408 << T << Kind << SubType;
1409 T = SubType;
1410 RD = T->getAsCXXRecordDecl();
1411 }
1412
1413 return true;
1414}
1415
1417 SourceLocation Loc) {
1418 // We don't allow variably-modified types as the type of non-type template
1419 // parameters.
1420 if (T->isVariablyModifiedType()) {
1421 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1422 << T;
1423 return QualType();
1424 }
1425
1426 // C++ [temp.param]p4:
1427 //
1428 // A non-type template-parameter shall have one of the following
1429 // (optionally cv-qualified) types:
1430 //
1431 // -- integral or enumeration type,
1432 if (T->isIntegralOrEnumerationType() ||
1433 // -- pointer to object or pointer to function,
1434 T->isPointerType() ||
1435 // -- lvalue reference to object or lvalue reference to function,
1436 T->isLValueReferenceType() ||
1437 // -- pointer to member,
1438 T->isMemberPointerType() ||
1439 // -- std::nullptr_t, or
1440 T->isNullPtrType() ||
1441 // -- a type that contains a placeholder type.
1442 T->isUndeducedType()) {
1443 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1444 // are ignored when determining its type.
1445 return T.getUnqualifiedType();
1446 }
1447
1448 // C++ [temp.param]p8:
1449 //
1450 // A non-type template-parameter of type "array of T" or
1451 // "function returning T" is adjusted to be of type "pointer to
1452 // T" or "pointer to function returning T", respectively.
1453 if (T->isArrayType() || T->isFunctionType())
1454 return Context.getDecayedType(T);
1455
1456 // If T is a dependent type, we can't do the check now, so we
1457 // assume that it is well-formed. Note that stripping off the
1458 // qualifiers here is not really correct if T turns out to be
1459 // an array type, but we'll recompute the type everywhere it's
1460 // used during instantiation, so that should be OK. (Using the
1461 // qualified type is equally wrong.)
1462 if (T->isDependentType())
1463 return T.getUnqualifiedType();
1464
1465 // C++20 [temp.param]p6:
1466 // -- a structural type
1467 if (RequireStructuralType(T, Loc))
1468 return QualType();
1469
1470 if (!getLangOpts().CPlusPlus20) {
1471 // FIXME: Consider allowing structural types as an extension in C++17. (In
1472 // earlier language modes, the template argument evaluation rules are too
1473 // inflexible.)
1474 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1475 return QualType();
1476 }
1477
1478 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1479 return T.getUnqualifiedType();
1480}
1481
1483 unsigned Depth,
1484 unsigned Position,
1485 SourceLocation EqualLoc,
1486 Expr *Default) {
1488
1489 // Check that we have valid decl-specifiers specified.
1490 auto CheckValidDeclSpecifiers = [this, &D] {
1491 // C++ [temp.param]
1492 // p1
1493 // template-parameter:
1494 // ...
1495 // parameter-declaration
1496 // p2
1497 // ... A storage class shall not be specified in a template-parameter
1498 // declaration.
1499 // [dcl.typedef]p1:
1500 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1501 // of a parameter-declaration
1502 const DeclSpec &DS = D.getDeclSpec();
1503 auto EmitDiag = [this](SourceLocation Loc) {
1504 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1506 };
1508 EmitDiag(DS.getStorageClassSpecLoc());
1509
1511 EmitDiag(DS.getThreadStorageClassSpecLoc());
1512
1513 // [dcl.inline]p1:
1514 // The inline specifier can be applied only to the declaration or
1515 // definition of a variable or function.
1516
1517 if (DS.isInlineSpecified())
1518 EmitDiag(DS.getInlineSpecLoc());
1519
1520 // [dcl.constexpr]p1:
1521 // The constexpr specifier shall be applied only to the definition of a
1522 // variable or variable template or the declaration of a function or
1523 // function template.
1524
1525 if (DS.hasConstexprSpecifier())
1526 EmitDiag(DS.getConstexprSpecLoc());
1527
1528 // [dcl.fct.spec]p1:
1529 // Function-specifiers can be used only in function declarations.
1530
1531 if (DS.isVirtualSpecified())
1532 EmitDiag(DS.getVirtualSpecLoc());
1533
1534 if (DS.hasExplicitSpecifier())
1535 EmitDiag(DS.getExplicitSpecLoc());
1536
1537 if (DS.isNoreturnSpecified())
1538 EmitDiag(DS.getNoreturnSpecLoc());
1539 };
1540
1541 CheckValidDeclSpecifiers();
1542
1543 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1544 if (isa<AutoType>(T))
1546 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1547 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1548
1549 assert(S->isTemplateParamScope() &&
1550 "Non-type template parameter not in template parameter scope!");
1551 bool Invalid = false;
1552
1554 if (T.isNull()) {
1555 T = Context.IntTy; // Recover with an 'int' type.
1556 Invalid = true;
1557 }
1558
1560
1561 const IdentifierInfo *ParamName = D.getIdentifier();
1562 bool IsParameterPack = D.hasEllipsis();
1564 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1565 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1566 TInfo);
1567 Param->setAccess(AS_public);
1568
1570 if (TL.isConstrained()) {
1571 if (D.getEllipsisLoc().isInvalid() &&
1572 T->containsUnexpandedParameterPack()) {
1573 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1574 for (auto &Loc :
1575 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1578 }
1579 if (!Invalid &&
1580 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1581 Invalid = true;
1582 }
1583
1584 if (Invalid)
1585 Param->setInvalidDecl();
1586
1587 if (Param->isParameterPack())
1588 if (auto *CSI = getEnclosingLambdaOrBlock())
1589 CSI->LocalPacks.push_back(Param);
1590
1591 if (ParamName) {
1593 ParamName);
1594
1595 // Add the template parameter into the current scope.
1596 S->AddDecl(Param);
1597 IdResolver.AddDecl(Param);
1598 }
1599
1600 // C++0x [temp.param]p9:
1601 // A default template-argument may be specified for any kind of
1602 // template-parameter that is not a template parameter pack.
1603 if (Default && IsParameterPack) {
1604 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1605 Default = nullptr;
1606 }
1607
1608 // Check the well-formedness of the default template argument, if provided.
1609 if (Default) {
1610 // Check for unexpanded parameter packs.
1612 return Param;
1613
1614 Param->setDefaultArgument(
1616 TemplateArgument(Default, /*IsCanonical=*/false),
1617 QualType(), SourceLocation()));
1618 }
1619
1620 return Param;
1621}
1622
1623/// ActOnTemplateTemplateParameter - Called when a C++ template template
1624/// parameter (e.g. T in template <template <typename> class T> class array)
1625/// has been parsed. S is the current scope.
1627 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1628 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1629 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1630 unsigned Position, SourceLocation EqualLoc,
1632 assert(S->isTemplateParamScope() &&
1633 "Template template parameter not in template parameter scope!");
1634
1635 bool IsParameterPack = EllipsisLoc.isValid();
1636
1637 bool Invalid = false;
1639 Params,
1640 /*OldParams=*/nullptr,
1641 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1642 Invalid = true;
1643
1644 // Construct the parameter object.
1646 Context, Context.getTranslationUnitDecl(),
1647 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1648 Name, Kind, Typename, Params);
1649 Param->setAccess(AS_public);
1650
1651 if (Param->isParameterPack())
1652 if (auto *LSI = getEnclosingLambdaOrBlock())
1653 LSI->LocalPacks.push_back(Param);
1654
1655 // If the template template parameter has a name, then link the identifier
1656 // into the scope and lookup mechanisms.
1657 if (Name) {
1658 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1659
1660 S->AddDecl(Param);
1661 IdResolver.AddDecl(Param);
1662 }
1663
1664 if (Params->size() == 0) {
1665 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1666 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1667 Invalid = true;
1668 }
1669
1670 if (Invalid)
1671 Param->setInvalidDecl();
1672
1673 // C++0x [temp.param]p9:
1674 // A default template-argument may be specified for any kind of
1675 // template-parameter that is not a template parameter pack.
1676 if (IsParameterPack && !Default.isInvalid()) {
1677 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1679 }
1680
1681 if (!Default.isInvalid()) {
1682 // Check only that we have a template template argument. We don't want to
1683 // try to check well-formedness now, because our template template parameter
1684 // might have dependent types in its template parameters, which we wouldn't
1685 // be able to match now.
1686 //
1687 // If none of the template template parameter's template arguments mention
1688 // other template parameters, we could actually perform more checking here.
1689 // However, it isn't worth doing.
1691 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1692 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1693 << DefaultArg.getSourceRange();
1694 return Param;
1695 }
1696
1697 TemplateName Name =
1700 if (Template &&
1702 return Param;
1703 }
1704
1705 // Check for unexpanded parameter packs.
1707 DefaultArg.getArgument().getAsTemplate(),
1709 return Param;
1710
1711 Param->setDefaultArgument(Context, DefaultArg);
1712 }
1713
1714 return Param;
1715}
1716
1717namespace {
1718class ConstraintRefersToContainingTemplateChecker
1720 using inherited = ConstDynamicRecursiveASTVisitor;
1721 bool Result = false;
1722 const FunctionDecl *Friend = nullptr;
1723 unsigned TemplateDepth = 0;
1724
1725 // Check a record-decl that we've seen to see if it is a lexical parent of the
1726 // Friend, likely because it was referred to without its template arguments.
1727 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1728 CheckingRD = CheckingRD->getMostRecentDecl();
1729 if (!CheckingRD->isTemplated())
1730 return true;
1731
1732 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1733 DC && !DC->isFileContext(); DC = DC->getParent())
1734 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1735 if (CheckingRD == RD->getMostRecentDecl()) {
1736 Result = true;
1737 return false;
1738 }
1739
1740 return true;
1741 }
1742
1743 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1744 if (D->getDepth() < TemplateDepth)
1745 Result = true;
1746
1747 // Necessary because the type of the NTTP might be what refers to the parent
1748 // constriant.
1749 return TraverseType(D->getType());
1750 }
1751
1752public:
1753 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1754 unsigned TemplateDepth)
1755 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1756
1757 bool getResult() const { return Result; }
1758
1759 // This should be the only template parm type that we have to deal with.
1760 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1761 // FunctionParmPackExpr are all partially substituted, which cannot happen
1762 // with concepts at this point in translation.
1763 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1764 if (Type->getDecl()->getDepth() < TemplateDepth) {
1765 Result = true;
1766 return false;
1767 }
1768 return true;
1769 }
1770
1771 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1772 return TraverseDecl(E->getDecl());
1773 }
1774
1775 bool TraverseTypedefType(const TypedefType *TT,
1776 bool /*TraverseQualifier*/) override {
1777 return TraverseType(TT->desugar());
1778 }
1779
1780 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1781 // We don't care about TypeLocs. So traverse Types instead.
1782 return TraverseType(TL.getType(), TraverseQualifier);
1783 }
1784
1785 bool VisitTagType(const TagType *T) override {
1786 return TraverseDecl(T->getOriginalDecl());
1787 }
1788
1789 bool TraverseDecl(const Decl *D) override {
1790 assert(D);
1791 // FIXME : This is possibly an incomplete list, but it is unclear what other
1792 // Decl kinds could be used to refer to the template parameters. This is a
1793 // best guess so far based on examples currently available, but the
1794 // unreachable should catch future instances/cases.
1795 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1796 return TraverseType(TD->getUnderlyingType());
1797 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1798 return CheckNonTypeTemplateParmDecl(NTTPD);
1799 if (auto *VD = dyn_cast<ValueDecl>(D))
1800 return TraverseType(VD->getType());
1801 if (isa<TemplateDecl>(D))
1802 return true;
1803 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1804 return CheckIfContainingRecord(RD);
1805
1807 // No direct types to visit here I believe.
1808 } else
1809 llvm_unreachable("Don't know how to handle this declaration type yet");
1810 return true;
1811 }
1812};
1813} // namespace
1814
1816 const FunctionDecl *Friend, unsigned TemplateDepth,
1817 const Expr *Constraint) {
1818 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1819 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1820 Checker.TraverseStmt(Constraint);
1821 return Checker.getResult();
1822}
1823
1826 SourceLocation ExportLoc,
1827 SourceLocation TemplateLoc,
1828 SourceLocation LAngleLoc,
1829 ArrayRef<NamedDecl *> Params,
1830 SourceLocation RAngleLoc,
1831 Expr *RequiresClause) {
1832 if (ExportLoc.isValid())
1833 Diag(ExportLoc, diag::warn_template_export_unsupported);
1834
1835 for (NamedDecl *P : Params)
1837
1838 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1839 llvm::ArrayRef(Params), RAngleLoc,
1840 RequiresClause);
1841}
1842
1844 const CXXScopeSpec &SS) {
1845 if (SS.isSet())
1846 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1847}
1848
1849// Returns the template parameter list with all default template argument
1850// information.
1852 // Make sure we get the template parameter list from the most
1853 // recent declaration, since that is the only one that is guaranteed to
1854 // have all the default template argument information.
1855 Decl *D = TD->getMostRecentDecl();
1856 // C++11 N3337 [temp.param]p12:
1857 // A default template argument shall not be specified in a friend class
1858 // template declaration.
1859 //
1860 // Skip past friend *declarations* because they are not supposed to contain
1861 // default template arguments. Moreover, these declarations may introduce
1862 // template parameters living in different template depths than the
1863 // corresponding template parameters in TD, causing unmatched constraint
1864 // substitution.
1865 //
1866 // FIXME: Diagnose such cases within a class template:
1867 // template <class T>
1868 // struct S {
1869 // template <class = void> friend struct C;
1870 // };
1871 // template struct S<int>;
1873 D->getPreviousDecl())
1874 D = D->getPreviousDecl();
1875 return cast<TemplateDecl>(D)->getTemplateParameters();
1876}
1877
1879 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1880 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1881 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1882 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1883 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1884 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1885 assert(TemplateParams && TemplateParams->size() > 0 &&
1886 "No template parameters");
1887 assert(TUK != TagUseKind::Reference &&
1888 "Can only declare or define class templates");
1889 bool Invalid = false;
1890
1891 // Check that we can declare a template here.
1892 if (CheckTemplateDeclScope(S, TemplateParams))
1893 return true;
1894
1896 assert(Kind != TagTypeKind::Enum &&
1897 "can't build template of enumerated type");
1898
1899 // There is no such thing as an unnamed class template.
1900 if (!Name) {
1901 Diag(KWLoc, diag::err_template_unnamed_class);
1902 return true;
1903 }
1904
1905 // Find any previous declaration with this name. For a friend with no
1906 // scope explicitly specified, we only look for tag declarations (per
1907 // C++11 [basic.lookup.elab]p2).
1908 DeclContext *SemanticContext;
1909 LookupResult Previous(*this, Name, NameLoc,
1910 (SS.isEmpty() && TUK == TagUseKind::Friend)
1914 if (SS.isNotEmpty() && !SS.isInvalid()) {
1915 SemanticContext = computeDeclContext(SS, true);
1916 if (!SemanticContext) {
1917 // FIXME: Horrible, horrible hack! We can't currently represent this
1918 // in the AST, and historically we have just ignored such friend
1919 // class templates, so don't complain here.
1920 Diag(NameLoc, TUK == TagUseKind::Friend
1921 ? diag::warn_template_qualified_friend_ignored
1922 : diag::err_template_qualified_declarator_no_match)
1923 << SS.getScopeRep() << SS.getRange();
1924 return TUK != TagUseKind::Friend;
1925 }
1926
1927 if (RequireCompleteDeclContext(SS, SemanticContext))
1928 return true;
1929
1930 // If we're adding a template to a dependent context, we may need to
1931 // rebuilding some of the types used within the template parameter list,
1932 // now that we know what the current instantiation is.
1933 if (SemanticContext->isDependentContext()) {
1934 ContextRAII SavedContext(*this, SemanticContext);
1936 Invalid = true;
1937 }
1938
1939 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1940 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1941 /*TemplateId-*/ nullptr,
1942 /*IsMemberSpecialization*/ false);
1943
1944 LookupQualifiedName(Previous, SemanticContext);
1945 } else {
1946 SemanticContext = CurContext;
1947
1948 // C++14 [class.mem]p14:
1949 // If T is the name of a class, then each of the following shall have a
1950 // name different from T:
1951 // -- every member template of class T
1952 if (TUK != TagUseKind::Friend &&
1953 DiagnoseClassNameShadow(SemanticContext,
1954 DeclarationNameInfo(Name, NameLoc)))
1955 return true;
1956
1957 LookupName(Previous, S);
1958 }
1959
1960 if (Previous.isAmbiguous())
1961 return true;
1962
1963 // Let the template parameter scope enter the lookup chain of the current
1964 // class template. For example, given
1965 //
1966 // namespace ns {
1967 // template <class> bool Param = false;
1968 // template <class T> struct N;
1969 // }
1970 //
1971 // template <class Param> struct ns::N { void foo(Param); };
1972 //
1973 // When we reference Param inside the function parameter list, our name lookup
1974 // chain for it should be like:
1975 // FunctionScope foo
1976 // -> RecordScope N
1977 // -> TemplateParamScope (where we will find Param)
1978 // -> NamespaceScope ns
1979 //
1980 // See also CppLookupName().
1981 if (S->isTemplateParamScope())
1982 EnterTemplatedContext(S, SemanticContext);
1983
1984 NamedDecl *PrevDecl = nullptr;
1985 if (Previous.begin() != Previous.end())
1986 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1987
1988 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1989 // Maybe we will complain about the shadowed template parameter.
1990 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1991 // Just pretend that we didn't see the previous declaration.
1992 PrevDecl = nullptr;
1993 }
1994
1995 // If there is a previous declaration with the same name, check
1996 // whether this is a valid redeclaration.
1997 ClassTemplateDecl *PrevClassTemplate =
1998 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1999
2000 // We may have found the injected-class-name of a class template,
2001 // class template partial specialization, or class template specialization.
2002 // In these cases, grab the template that is being defined or specialized.
2003 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2004 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2005 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2006 PrevClassTemplate
2007 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2008 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2009 PrevClassTemplate
2011 ->getSpecializedTemplate();
2012 }
2013 }
2014
2015 if (TUK == TagUseKind::Friend) {
2016 // C++ [namespace.memdef]p3:
2017 // [...] When looking for a prior declaration of a class or a function
2018 // declared as a friend, and when the name of the friend class or
2019 // function is neither a qualified name nor a template-id, scopes outside
2020 // the innermost enclosing namespace scope are not considered.
2021 if (!SS.isSet()) {
2022 DeclContext *OutermostContext = CurContext;
2023 while (!OutermostContext->isFileContext())
2024 OutermostContext = OutermostContext->getLookupParent();
2025
2026 if (PrevDecl &&
2027 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2028 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2029 SemanticContext = PrevDecl->getDeclContext();
2030 } else {
2031 // Declarations in outer scopes don't matter. However, the outermost
2032 // context we computed is the semantic context for our new
2033 // declaration.
2034 PrevDecl = PrevClassTemplate = nullptr;
2035 SemanticContext = OutermostContext;
2036
2037 // Check that the chosen semantic context doesn't already contain a
2038 // declaration of this name as a non-tag type.
2040 DeclContext *LookupContext = SemanticContext;
2041 while (LookupContext->isTransparentContext())
2042 LookupContext = LookupContext->getLookupParent();
2043 LookupQualifiedName(Previous, LookupContext);
2044
2045 if (Previous.isAmbiguous())
2046 return true;
2047
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050 }
2051 }
2052 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2053 SemanticContext, S, SS.isValid()))
2054 PrevDecl = PrevClassTemplate = nullptr;
2055
2056 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2057 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2058 if (SS.isEmpty() &&
2059 !(PrevClassTemplate &&
2060 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2061 SemanticContext->getRedeclContext()))) {
2062 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2063 Diag(Shadow->getTargetDecl()->getLocation(),
2064 diag::note_using_decl_target);
2065 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2066 // Recover by ignoring the old declaration.
2067 PrevDecl = PrevClassTemplate = nullptr;
2068 }
2069 }
2070
2071 if (PrevClassTemplate) {
2072 // Ensure that the template parameter lists are compatible. Skip this check
2073 // for a friend in a dependent context: the template parameter list itself
2074 // could be dependent.
2075 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2077 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2078 : CurContext,
2079 CurContext, KWLoc),
2080 TemplateParams, PrevClassTemplate,
2081 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2083 return true;
2084
2085 // C++ [temp.class]p4:
2086 // In a redeclaration, partial specialization, explicit
2087 // specialization or explicit instantiation of a class template,
2088 // the class-key shall agree in kind with the original class
2089 // template declaration (7.1.5.3).
2090 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2092 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2093 Diag(KWLoc, diag::err_use_with_wrong_tag)
2094 << Name
2095 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2096 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2097 Kind = PrevRecordDecl->getTagKind();
2098 }
2099
2100 // Check for redefinition of this class template.
2101 if (TUK == TagUseKind::Definition) {
2102 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2103 // If we have a prior definition that is not visible, treat this as
2104 // simply making that previous definition visible.
2105 NamedDecl *Hidden = nullptr;
2106 bool HiddenDefVisible = false;
2107 if (SkipBody &&
2108 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2109 SkipBody->ShouldSkip = true;
2110 SkipBody->Previous = Def;
2111 if (!HiddenDefVisible && Hidden) {
2112 auto *Tmpl =
2113 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2114 assert(Tmpl && "original definition of a class template is not a "
2115 "class template?");
2118 }
2119 } else {
2120 Diag(NameLoc, diag::err_redefinition) << Name;
2121 Diag(Def->getLocation(), diag::note_previous_definition);
2122 // FIXME: Would it make sense to try to "forget" the previous
2123 // definition, as part of error recovery?
2124 return true;
2125 }
2126 }
2127 }
2128 } else if (PrevDecl) {
2129 // C++ [temp]p5:
2130 // A class template shall not have the same name as any other
2131 // template, class, function, object, enumeration, enumerator,
2132 // namespace, or type in the same scope (3.3), except as specified
2133 // in (14.5.4).
2134 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2135 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2136 return true;
2137 }
2138
2139 // Check the template parameter list of this declaration, possibly
2140 // merging in the template parameter list from the previous class
2141 // template declaration. Skip this check for a friend in a dependent
2142 // context, because the template parameter list might be dependent.
2143 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2145 TemplateParams,
2146 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2147 : nullptr,
2148 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2149 SemanticContext->isDependentContext())
2152 : TPC_Other,
2153 SkipBody))
2154 Invalid = true;
2155
2156 if (SS.isSet()) {
2157 // If the name of the template was qualified, we must be defining the
2158 // template out-of-line.
2159 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2160 Diag(NameLoc, TUK == TagUseKind::Friend
2161 ? diag::err_friend_decl_does_not_match
2162 : diag::err_member_decl_does_not_match)
2163 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2164 Invalid = true;
2165 }
2166 }
2167
2168 // If this is a templated friend in a dependent context we should not put it
2169 // on the redecl chain. In some cases, the templated friend can be the most
2170 // recent declaration tricking the template instantiator to make substitutions
2171 // there.
2172 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2173 bool ShouldAddRedecl =
2174 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2175
2177 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2178 PrevClassTemplate && ShouldAddRedecl
2179 ? PrevClassTemplate->getTemplatedDecl()
2180 : nullptr);
2181 SetNestedNameSpecifier(*this, NewClass, SS);
2182 if (NumOuterTemplateParamLists > 0)
2184 Context,
2185 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2186
2187 // Add alignment attributes if necessary; these attributes are checked when
2188 // the ASTContext lays out the structure.
2189 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2190 if (LangOpts.HLSL)
2191 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2194 }
2195
2196 ClassTemplateDecl *NewTemplate
2197 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2198 DeclarationName(Name), TemplateParams,
2199 NewClass);
2200
2201 if (ShouldAddRedecl)
2202 NewTemplate->setPreviousDecl(PrevClassTemplate);
2203
2204 NewClass->setDescribedClassTemplate(NewTemplate);
2205
2206 if (ModulePrivateLoc.isValid())
2207 NewTemplate->setModulePrivate();
2208
2209 // If we are providing an explicit specialization of a member that is a
2210 // class template, make a note of that.
2211 if (PrevClassTemplate &&
2212 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2213 PrevClassTemplate->setMemberSpecialization();
2214
2215 // Set the access specifier.
2216 if (!Invalid && TUK != TagUseKind::Friend &&
2217 NewTemplate->getDeclContext()->isRecord())
2218 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2219
2220 // Set the lexical context of these templates
2222 NewTemplate->setLexicalDeclContext(CurContext);
2223
2224 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2225 NewClass->startDefinition();
2226
2227 ProcessDeclAttributeList(S, NewClass, Attr);
2228
2229 if (PrevClassTemplate)
2230 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2231
2235
2236 if (TUK != TagUseKind::Friend) {
2237 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2238 Scope *Outer = S;
2239 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2240 Outer = Outer->getParent();
2241 PushOnScopeChains(NewTemplate, Outer);
2242 } else {
2243 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2244 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2245 NewClass->setAccess(PrevClassTemplate->getAccess());
2246 }
2247
2248 NewTemplate->setObjectOfFriendDecl();
2249
2250 // Friend templates are visible in fairly strange ways.
2251 if (!CurContext->isDependentContext()) {
2252 DeclContext *DC = SemanticContext->getRedeclContext();
2253 DC->makeDeclVisibleInContext(NewTemplate);
2254 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2255 PushOnScopeChains(NewTemplate, EnclosingScope,
2256 /* AddToContext = */ false);
2257 }
2258
2260 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2261 Friend->setAccess(AS_public);
2262 CurContext->addDecl(Friend);
2263 }
2264
2265 if (PrevClassTemplate)
2266 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2267
2268 if (Invalid) {
2269 NewTemplate->setInvalidDecl();
2270 NewClass->setInvalidDecl();
2271 }
2272
2273 ActOnDocumentableDecl(NewTemplate);
2274
2275 if (SkipBody && SkipBody->ShouldSkip)
2276 return SkipBody->Previous;
2277
2278 return NewTemplate;
2279}
2280
2281/// Diagnose the presence of a default template argument on a
2282/// template parameter, which is ill-formed in certain contexts.
2283///
2284/// \returns true if the default template argument should be dropped.
2287 SourceLocation ParamLoc,
2288 SourceRange DefArgRange) {
2289 switch (TPC) {
2290 case Sema::TPC_Other:
2292 return false;
2293
2296 // C++ [temp.param]p9:
2297 // A default template-argument shall not be specified in a
2298 // function template declaration or a function template
2299 // definition [...]
2300 // If a friend function template declaration specifies a default
2301 // template-argument, that declaration shall be a definition and shall be
2302 // the only declaration of the function template in the translation unit.
2303 // (C++98/03 doesn't have this wording; see DR226).
2304 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2305 << DefArgRange;
2306 return false;
2307
2309 // C++0x [temp.param]p9:
2310 // A default template-argument shall not be specified in the
2311 // template-parameter-lists of the definition of a member of a
2312 // class template that appears outside of the member's class.
2313 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2314 << DefArgRange;
2315 return true;
2316
2319 // C++ [temp.param]p9:
2320 // A default template-argument shall not be specified in a
2321 // friend template declaration.
2322 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2323 << DefArgRange;
2324 return true;
2325
2326 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2327 // for friend function templates if there is only a single
2328 // declaration (and it is a definition). Strange!
2329 }
2330
2331 llvm_unreachable("Invalid TemplateParamListContext!");
2332}
2333
2334/// Check for unexpanded parameter packs within the template parameters
2335/// of a template template parameter, recursively.
2338 // A template template parameter which is a parameter pack is also a pack
2339 // expansion.
2340 if (TTP->isParameterPack())
2341 return false;
2342
2344 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2345 NamedDecl *P = Params->getParam(I);
2346 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2347 if (!TTP->isParameterPack())
2348 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2349 if (TC->hasExplicitTemplateArgs())
2350 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2353 return true;
2354 continue;
2355 }
2356
2357 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2358 if (!NTTP->isParameterPack() &&
2359 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2360 NTTP->getTypeSourceInfo(),
2362 return true;
2363
2364 continue;
2365 }
2366
2367 if (TemplateTemplateParmDecl *InnerTTP
2368 = dyn_cast<TemplateTemplateParmDecl>(P))
2369 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2370 return true;
2371 }
2372
2373 return false;
2374}
2375
2377 TemplateParameterList *OldParams,
2379 SkipBodyInfo *SkipBody) {
2380 bool Invalid = false;
2381
2382 // C++ [temp.param]p10:
2383 // The set of default template-arguments available for use with a
2384 // template declaration or definition is obtained by merging the
2385 // default arguments from the definition (if in scope) and all
2386 // declarations in scope in the same way default function
2387 // arguments are (8.3.6).
2388 bool SawDefaultArgument = false;
2389 SourceLocation PreviousDefaultArgLoc;
2390
2391 // Dummy initialization to avoid warnings.
2392 TemplateParameterList::iterator OldParam = NewParams->end();
2393 if (OldParams)
2394 OldParam = OldParams->begin();
2395
2396 bool RemoveDefaultArguments = false;
2397 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2398 NewParamEnd = NewParams->end();
2399 NewParam != NewParamEnd; ++NewParam) {
2400 // Whether we've seen a duplicate default argument in the same translation
2401 // unit.
2402 bool RedundantDefaultArg = false;
2403 // Whether we've found inconsis inconsitent default arguments in different
2404 // translation unit.
2405 bool InconsistentDefaultArg = false;
2406 // The name of the module which contains the inconsistent default argument.
2407 std::string PrevModuleName;
2408
2409 SourceLocation OldDefaultLoc;
2410 SourceLocation NewDefaultLoc;
2411
2412 // Variable used to diagnose missing default arguments
2413 bool MissingDefaultArg = false;
2414
2415 // Variable used to diagnose non-final parameter packs
2416 bool SawParameterPack = false;
2417
2418 if (TemplateTypeParmDecl *NewTypeParm
2419 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2420 // Check the presence of a default argument here.
2421 if (NewTypeParm->hasDefaultArgument() &&
2423 *this, TPC, NewTypeParm->getLocation(),
2424 NewTypeParm->getDefaultArgument().getSourceRange()))
2425 NewTypeParm->removeDefaultArgument();
2426
2427 // Merge default arguments for template type parameters.
2428 TemplateTypeParmDecl *OldTypeParm
2429 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2430 if (NewTypeParm->isParameterPack()) {
2431 assert(!NewTypeParm->hasDefaultArgument() &&
2432 "Parameter packs can't have a default argument!");
2433 SawParameterPack = true;
2434 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2435 NewTypeParm->hasDefaultArgument() &&
2436 (!SkipBody || !SkipBody->ShouldSkip)) {
2437 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2438 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2439 SawDefaultArgument = true;
2440
2441 if (!OldTypeParm->getOwningModule())
2442 RedundantDefaultArg = true;
2443 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2444 NewTypeParm)) {
2445 InconsistentDefaultArg = true;
2446 PrevModuleName =
2448 }
2449 PreviousDefaultArgLoc = NewDefaultLoc;
2450 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2451 // Merge the default argument from the old declaration to the
2452 // new declaration.
2453 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2454 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2455 } else if (NewTypeParm->hasDefaultArgument()) {
2456 SawDefaultArgument = true;
2457 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2458 } else if (SawDefaultArgument)
2459 MissingDefaultArg = true;
2460 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2461 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2462 // Check for unexpanded parameter packs, except in a template template
2463 // parameter pack, as in those any unexpanded packs should be expanded
2464 // along with the parameter itself.
2466 !NewNonTypeParm->isParameterPack() &&
2467 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2468 NewNonTypeParm->getTypeSourceInfo(),
2470 Invalid = true;
2471 continue;
2472 }
2473
2474 // Check the presence of a default argument here.
2475 if (NewNonTypeParm->hasDefaultArgument() &&
2477 *this, TPC, NewNonTypeParm->getLocation(),
2478 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2479 NewNonTypeParm->removeDefaultArgument();
2480 }
2481
2482 // Merge default arguments for non-type template parameters
2483 NonTypeTemplateParmDecl *OldNonTypeParm
2484 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2485 if (NewNonTypeParm->isParameterPack()) {
2486 assert(!NewNonTypeParm->hasDefaultArgument() &&
2487 "Parameter packs can't have a default argument!");
2488 if (!NewNonTypeParm->isPackExpansion())
2489 SawParameterPack = true;
2490 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2491 NewNonTypeParm->hasDefaultArgument() &&
2492 (!SkipBody || !SkipBody->ShouldSkip)) {
2493 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2494 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2495 SawDefaultArgument = true;
2496 if (!OldNonTypeParm->getOwningModule())
2497 RedundantDefaultArg = true;
2498 else if (!getASTContext().isSameDefaultTemplateArgument(
2499 OldNonTypeParm, NewNonTypeParm)) {
2500 InconsistentDefaultArg = true;
2501 PrevModuleName =
2502 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2503 }
2504 PreviousDefaultArgLoc = NewDefaultLoc;
2505 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2506 // Merge the default argument from the old declaration to the
2507 // new declaration.
2508 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2509 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2510 } else if (NewNonTypeParm->hasDefaultArgument()) {
2511 SawDefaultArgument = true;
2512 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2513 } else if (SawDefaultArgument)
2514 MissingDefaultArg = true;
2515 } else {
2516 TemplateTemplateParmDecl *NewTemplateParm
2517 = cast<TemplateTemplateParmDecl>(*NewParam);
2518
2519 // Check for unexpanded parameter packs, recursively.
2520 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2521 Invalid = true;
2522 continue;
2523 }
2524
2525 // Check the presence of a default argument here.
2526 if (NewTemplateParm->hasDefaultArgument() &&
2528 NewTemplateParm->getLocation(),
2529 NewTemplateParm->getDefaultArgument().getSourceRange()))
2530 NewTemplateParm->removeDefaultArgument();
2531
2532 // Merge default arguments for template template parameters
2533 TemplateTemplateParmDecl *OldTemplateParm
2534 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2535 if (NewTemplateParm->isParameterPack()) {
2536 assert(!NewTemplateParm->hasDefaultArgument() &&
2537 "Parameter packs can't have a default argument!");
2538 if (!NewTemplateParm->isPackExpansion())
2539 SawParameterPack = true;
2540 } else if (OldTemplateParm &&
2541 hasVisibleDefaultArgument(OldTemplateParm) &&
2542 NewTemplateParm->hasDefaultArgument() &&
2543 (!SkipBody || !SkipBody->ShouldSkip)) {
2544 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2545 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2546 SawDefaultArgument = true;
2547 if (!OldTemplateParm->getOwningModule())
2548 RedundantDefaultArg = true;
2549 else if (!getASTContext().isSameDefaultTemplateArgument(
2550 OldTemplateParm, NewTemplateParm)) {
2551 InconsistentDefaultArg = true;
2552 PrevModuleName =
2553 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2554 }
2555 PreviousDefaultArgLoc = NewDefaultLoc;
2556 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2557 // Merge the default argument from the old declaration to the
2558 // new declaration.
2559 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2560 PreviousDefaultArgLoc
2561 = OldTemplateParm->getDefaultArgument().getLocation();
2562 } else if (NewTemplateParm->hasDefaultArgument()) {
2563 SawDefaultArgument = true;
2564 PreviousDefaultArgLoc
2565 = NewTemplateParm->getDefaultArgument().getLocation();
2566 } else if (SawDefaultArgument)
2567 MissingDefaultArg = true;
2568 }
2569
2570 // C++11 [temp.param]p11:
2571 // If a template parameter of a primary class template or alias template
2572 // is a template parameter pack, it shall be the last template parameter.
2573 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2574 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2575 Diag((*NewParam)->getLocation(),
2576 diag::err_template_param_pack_must_be_last_template_parameter);
2577 Invalid = true;
2578 }
2579
2580 // [basic.def.odr]/13:
2581 // There can be more than one definition of a
2582 // ...
2583 // default template argument
2584 // ...
2585 // in a program provided that each definition appears in a different
2586 // translation unit and the definitions satisfy the [same-meaning
2587 // criteria of the ODR].
2588 //
2589 // Simply, the design of modules allows the definition of template default
2590 // argument to be repeated across translation unit. Note that the ODR is
2591 // checked elsewhere. But it is still not allowed to repeat template default
2592 // argument in the same translation unit.
2593 if (RedundantDefaultArg) {
2594 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2595 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2596 Invalid = true;
2597 } else if (InconsistentDefaultArg) {
2598 // We could only diagnose about the case that the OldParam is imported.
2599 // The case NewParam is imported should be handled in ASTReader.
2600 Diag(NewDefaultLoc,
2601 diag::err_template_param_default_arg_inconsistent_redefinition);
2602 Diag(OldDefaultLoc,
2603 diag::note_template_param_prev_default_arg_in_other_module)
2604 << PrevModuleName;
2605 Invalid = true;
2606 } else if (MissingDefaultArg &&
2607 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2608 TPC == TPC_FriendClassTemplate)) {
2609 // C++ 23[temp.param]p14:
2610 // If a template-parameter of a class template, variable template, or
2611 // alias template has a default template argument, each subsequent
2612 // template-parameter shall either have a default template argument
2613 // supplied or be a template parameter pack.
2614 Diag((*NewParam)->getLocation(),
2615 diag::err_template_param_default_arg_missing);
2616 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2617 Invalid = true;
2618 RemoveDefaultArguments = true;
2619 }
2620
2621 // If we have an old template parameter list that we're merging
2622 // in, move on to the next parameter.
2623 if (OldParams)
2624 ++OldParam;
2625 }
2626
2627 // We were missing some default arguments at the end of the list, so remove
2628 // all of the default arguments.
2629 if (RemoveDefaultArguments) {
2630 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2631 NewParamEnd = NewParams->end();
2632 NewParam != NewParamEnd; ++NewParam) {
2633 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2634 TTP->removeDefaultArgument();
2635 else if (NonTypeTemplateParmDecl *NTTP
2636 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2637 NTTP->removeDefaultArgument();
2638 else
2639 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2640 }
2641 }
2642
2643 return Invalid;
2644}
2645
2646namespace {
2647
2648/// A class which looks for a use of a certain level of template
2649/// parameter.
2650struct DependencyChecker : DynamicRecursiveASTVisitor {
2651 unsigned Depth;
2652
2653 // Whether we're looking for a use of a template parameter that makes the
2654 // overall construct type-dependent / a dependent type. This is strictly
2655 // best-effort for now; we may fail to match at all for a dependent type
2656 // in some cases if this is set.
2657 bool IgnoreNonTypeDependent;
2658
2659 bool Match;
2660 SourceLocation MatchLoc;
2661
2662 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2663 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2664 Match(false) {}
2665
2666 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2667 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2668 NamedDecl *ND = Params->getParam(0);
2669 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2670 Depth = PD->getDepth();
2671 } else if (NonTypeTemplateParmDecl *PD =
2672 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2673 Depth = PD->getDepth();
2674 } else {
2675 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2676 }
2677 }
2678
2679 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2680 if (ParmDepth >= Depth) {
2681 Match = true;
2682 MatchLoc = Loc;
2683 return true;
2684 }
2685 return false;
2686 }
2687
2688 bool TraverseStmt(Stmt *S) override {
2689 // Prune out non-type-dependent expressions if requested. This can
2690 // sometimes result in us failing to find a template parameter reference
2691 // (if a value-dependent expression creates a dependent type), but this
2692 // mode is best-effort only.
2693 if (auto *E = dyn_cast_or_null<Expr>(S))
2694 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2695 return true;
2697 }
2698
2699 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2700 if (IgnoreNonTypeDependent && !TL.isNull() &&
2701 !TL.getType()->isDependentType())
2702 return true;
2703 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2704 }
2705
2706 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2707 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2708 }
2709
2710 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2711 // For a best-effort search, keep looking until we find a location.
2712 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2713 }
2714
2715 bool TraverseTemplateName(TemplateName N) override {
2716 if (TemplateTemplateParmDecl *PD =
2717 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2718 if (Matches(PD->getDepth()))
2719 return false;
2721 }
2722
2723 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2724 if (NonTypeTemplateParmDecl *PD =
2725 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2726 if (Matches(PD->getDepth(), E->getExprLoc()))
2727 return false;
2728 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2729 }
2730
2731 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2732 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2733 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2734 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2735 return false;
2736 }
2737 for (auto &TLoc : ULE->template_arguments())
2739 }
2740 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2741 }
2742
2743 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2744 return TraverseType(T->getReplacementType());
2745 }
2746
2747 bool VisitSubstTemplateTypeParmPackType(
2748 SubstTemplateTypeParmPackType *T) override {
2749 return TraverseTemplateArgument(T->getArgumentPack());
2750 }
2751
2752 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2753 bool TraverseQualifier) override {
2754 // An InjectedClassNameType will never have a dependent template name,
2755 // so no need to traverse it.
2756 return TraverseTemplateArguments(
2757 T->getTemplateArgs(T->getOriginalDecl()->getASTContext()));
2758 }
2759};
2760} // end anonymous namespace
2761
2762/// Determines whether a given type depends on the given parameter
2763/// list.
2764static bool
2766 if (!Params->size())
2767 return false;
2768
2769 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2770 Checker.TraverseType(T);
2771 return Checker.Match;
2772}
2773
2774// Find the source range corresponding to the named type in the given
2775// nested-name-specifier, if any.
2777 QualType T,
2778 const CXXScopeSpec &SS) {
2780 for (;;) {
2783 break;
2784 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2785 return NNSLoc.castAsTypeLoc().getSourceRange();
2786 // FIXME: This will always be empty.
2787 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2788 }
2789
2790 return SourceRange();
2791}
2792
2794 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2795 TemplateIdAnnotation *TemplateId,
2796 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2797 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2798 IsMemberSpecialization = false;
2799 Invalid = false;
2800
2801 // The sequence of nested types to which we will match up the template
2802 // parameter lists. We first build this list by starting with the type named
2803 // by the nested-name-specifier and walking out until we run out of types.
2804 SmallVector<QualType, 4> NestedTypes;
2805 QualType T;
2806 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2807 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2808 if (CXXRecordDecl *Record =
2809 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2810 T = Context.getCanonicalTagType(Record);
2811 else
2812 T = QualType(Qualifier.getAsType(), 0);
2813 }
2814
2815 // If we found an explicit specialization that prevents us from needing
2816 // 'template<>' headers, this will be set to the location of that
2817 // explicit specialization.
2818 SourceLocation ExplicitSpecLoc;
2819
2820 while (!T.isNull()) {
2821 NestedTypes.push_back(T);
2822
2823 // Retrieve the parent of a record type.
2824 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2825 // If this type is an explicit specialization, we're done.
2827 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2829 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2830 ExplicitSpecLoc = Spec->getLocation();
2831 break;
2832 }
2833 } else if (Record->getTemplateSpecializationKind()
2835 ExplicitSpecLoc = Record->getLocation();
2836 break;
2837 }
2838
2839 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2840 T = Context.getTypeDeclType(Parent);
2841 else
2842 T = QualType();
2843 continue;
2844 }
2845
2846 if (const TemplateSpecializationType *TST
2847 = T->getAs<TemplateSpecializationType>()) {
2848 TemplateName Name = TST->getTemplateName();
2849 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2850 // Look one step prior in a dependent template specialization type.
2851 if (NestedNameSpecifier NNS = DTS->getQualifier();
2853 T = QualType(NNS.getAsType(), 0);
2854 else
2855 T = QualType();
2856 continue;
2857 }
2858 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2859 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2860 T = Context.getTypeDeclType(Parent);
2861 else
2862 T = QualType();
2863 continue;
2864 }
2865 }
2866
2867 // Look one step prior in a dependent name type.
2868 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2869 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2871 T = QualType(NNS.getAsType(), 0);
2872 else
2873 T = QualType();
2874 continue;
2875 }
2876
2877 // Retrieve the parent of an enumeration type.
2878 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2879 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2880 // check here.
2881 EnumDecl *Enum = EnumT->getOriginalDecl();
2882
2883 // Get to the parent type.
2884 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2885 T = Context.getCanonicalTypeDeclType(Parent);
2886 else
2887 T = QualType();
2888 continue;
2889 }
2890
2891 T = QualType();
2892 }
2893 // Reverse the nested types list, since we want to traverse from the outermost
2894 // to the innermost while checking template-parameter-lists.
2895 std::reverse(NestedTypes.begin(), NestedTypes.end());
2896
2897 // C++0x [temp.expl.spec]p17:
2898 // A member or a member template may be nested within many
2899 // enclosing class templates. In an explicit specialization for
2900 // such a member, the member declaration shall be preceded by a
2901 // template<> for each enclosing class template that is
2902 // explicitly specialized.
2903 bool SawNonEmptyTemplateParameterList = false;
2904
2905 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2906 if (SawNonEmptyTemplateParameterList) {
2907 if (!SuppressDiagnostic)
2908 Diag(DeclLoc, diag::err_specialize_member_of_template)
2909 << !Recovery << Range;
2910 Invalid = true;
2911 IsMemberSpecialization = false;
2912 return true;
2913 }
2914
2915 return false;
2916 };
2917
2918 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2919 // Check that we can have an explicit specialization here.
2920 if (CheckExplicitSpecialization(Range, true))
2921 return true;
2922
2923 // We don't have a template header, but we should.
2924 SourceLocation ExpectedTemplateLoc;
2925 if (!ParamLists.empty())
2926 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2927 else
2928 ExpectedTemplateLoc = DeclStartLoc;
2929
2930 if (!SuppressDiagnostic)
2931 Diag(DeclLoc, diag::err_template_spec_needs_header)
2932 << Range
2933 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2934 return false;
2935 };
2936
2937 unsigned ParamIdx = 0;
2938 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2939 ++TypeIdx) {
2940 T = NestedTypes[TypeIdx];
2941
2942 // Whether we expect a 'template<>' header.
2943 bool NeedEmptyTemplateHeader = false;
2944
2945 // Whether we expect a template header with parameters.
2946 bool NeedNonemptyTemplateHeader = false;
2947
2948 // For a dependent type, the set of template parameters that we
2949 // expect to see.
2950 TemplateParameterList *ExpectedTemplateParams = nullptr;
2951
2952 // C++0x [temp.expl.spec]p15:
2953 // A member or a member template may be nested within many enclosing
2954 // class templates. In an explicit specialization for such a member, the
2955 // member declaration shall be preceded by a template<> for each
2956 // enclosing class template that is explicitly specialized.
2957 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2959 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2960 ExpectedTemplateParams = Partial->getTemplateParameters();
2961 NeedNonemptyTemplateHeader = true;
2962 } else if (Record->isDependentType()) {
2963 if (Record->getDescribedClassTemplate()) {
2964 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2965 ->getTemplateParameters();
2966 NeedNonemptyTemplateHeader = true;
2967 }
2968 } else if (ClassTemplateSpecializationDecl *Spec
2969 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2970 // C++0x [temp.expl.spec]p4:
2971 // Members of an explicitly specialized class template are defined
2972 // in the same manner as members of normal classes, and not using
2973 // the template<> syntax.
2974 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2975 NeedEmptyTemplateHeader = true;
2976 else
2977 continue;
2978 } else if (Record->getTemplateSpecializationKind()) {
2979 if (Record->getTemplateSpecializationKind()
2981 TypeIdx == NumTypes - 1)
2982 IsMemberSpecialization = true;
2983
2984 continue;
2985 }
2986 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
2987 TemplateName Name = TST->getTemplateName();
2988 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2989 ExpectedTemplateParams = Template->getTemplateParameters();
2990 NeedNonemptyTemplateHeader = true;
2991 } else if (Name.getAsDeducedTemplateName()) {
2992 // FIXME: We actually could/should check the template arguments here
2993 // against the corresponding template parameter list.
2994 NeedNonemptyTemplateHeader = false;
2995 }
2996 }
2997
2998 // C++ [temp.expl.spec]p16:
2999 // In an explicit specialization declaration for a member of a class
3000 // template or a member template that appears in namespace scope, the
3001 // member template and some of its enclosing class templates may remain
3002 // unspecialized, except that the declaration shall not explicitly
3003 // specialize a class member template if its enclosing class templates
3004 // are not explicitly specialized as well.
3005 if (ParamIdx < ParamLists.size()) {
3006 if (ParamLists[ParamIdx]->size() == 0) {
3007 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3008 false))
3009 return nullptr;
3010 } else
3011 SawNonEmptyTemplateParameterList = true;
3012 }
3013
3014 if (NeedEmptyTemplateHeader) {
3015 // If we're on the last of the types, and we need a 'template<>' header
3016 // here, then it's a member specialization.
3017 if (TypeIdx == NumTypes - 1)
3018 IsMemberSpecialization = true;
3019
3020 if (ParamIdx < ParamLists.size()) {
3021 if (ParamLists[ParamIdx]->size() > 0) {
3022 // The header has template parameters when it shouldn't. Complain.
3023 if (!SuppressDiagnostic)
3024 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3025 diag::err_template_param_list_matches_nontemplate)
3026 << T
3027 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3028 ParamLists[ParamIdx]->getRAngleLoc())
3030 Invalid = true;
3031 return nullptr;
3032 }
3033
3034 // Consume this template header.
3035 ++ParamIdx;
3036 continue;
3037 }
3038
3039 if (!IsFriend)
3040 if (DiagnoseMissingExplicitSpecialization(
3042 return nullptr;
3043
3044 continue;
3045 }
3046
3047 if (NeedNonemptyTemplateHeader) {
3048 // In friend declarations we can have template-ids which don't
3049 // depend on the corresponding template parameter lists. But
3050 // assume that empty parameter lists are supposed to match this
3051 // template-id.
3052 if (IsFriend && T->isDependentType()) {
3053 if (ParamIdx < ParamLists.size() &&
3055 ExpectedTemplateParams = nullptr;
3056 else
3057 continue;
3058 }
3059
3060 if (ParamIdx < ParamLists.size()) {
3061 // Check the template parameter list, if we can.
3062 if (ExpectedTemplateParams &&
3064 ExpectedTemplateParams,
3065 !SuppressDiagnostic, TPL_TemplateMatch))
3066 Invalid = true;
3067
3068 if (!Invalid &&
3069 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3071 Invalid = true;
3072
3073 ++ParamIdx;
3074 continue;
3075 }
3076
3077 if (!SuppressDiagnostic)
3078 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3079 << T
3081 Invalid = true;
3082 continue;
3083 }
3084 }
3085
3086 // If there were at least as many template-ids as there were template
3087 // parameter lists, then there are no template parameter lists remaining for
3088 // the declaration itself.
3089 if (ParamIdx >= ParamLists.size()) {
3090 if (TemplateId && !IsFriend) {
3091 // We don't have a template header for the declaration itself, but we
3092 // should.
3093 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3094 TemplateId->RAngleLoc));
3095
3096 // Fabricate an empty template parameter list for the invented header.
3098 SourceLocation(), {},
3099 SourceLocation(), nullptr);
3100 }
3101
3102 return nullptr;
3103 }
3104
3105 // If there were too many template parameter lists, complain about that now.
3106 if (ParamIdx < ParamLists.size() - 1) {
3107 bool HasAnyExplicitSpecHeader = false;
3108 bool AllExplicitSpecHeaders = true;
3109 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3110 if (ParamLists[I]->size() == 0)
3111 HasAnyExplicitSpecHeader = true;
3112 else
3113 AllExplicitSpecHeaders = false;
3114 }
3115
3116 if (!SuppressDiagnostic)
3117 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3118 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3119 : diag::err_template_spec_extra_headers)
3120 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3121 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3122
3123 // If there was a specialization somewhere, such that 'template<>' is
3124 // not required, and there were any 'template<>' headers, note where the
3125 // specialization occurred.
3126 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3127 !SuppressDiagnostic)
3128 Diag(ExplicitSpecLoc,
3129 diag::note_explicit_template_spec_does_not_need_header)
3130 << NestedTypes.back();
3131
3132 // We have a template parameter list with no corresponding scope, which
3133 // means that the resulting template declaration can't be instantiated
3134 // properly (we'll end up with dependent nodes when we shouldn't).
3135 if (!AllExplicitSpecHeaders)
3136 Invalid = true;
3137 }
3138
3139 // C++ [temp.expl.spec]p16:
3140 // In an explicit specialization declaration for a member of a class
3141 // template or a member template that ap- pears in namespace scope, the
3142 // member template and some of its enclosing class templates may remain
3143 // unspecialized, except that the declaration shall not explicitly
3144 // specialize a class member template if its en- closing class templates
3145 // are not explicitly specialized as well.
3146 if (ParamLists.back()->size() == 0 &&
3147 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3148 false))
3149 return nullptr;
3150
3151 // Return the last template parameter list, which corresponds to the
3152 // entity being declared.
3153 return ParamLists.back();
3154}
3155
3157 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3158 Diag(Template->getLocation(), diag::note_template_declared_here)
3160 ? 0
3162 ? 1
3164 ? 2
3166 << Template->getDeclName();
3167 return;
3168 }
3169
3171 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3172 IEnd = OST->end();
3173 I != IEnd; ++I)
3174 Diag((*I)->getLocation(), diag::note_template_declared_here)
3175 << 0 << (*I)->getDeclName();
3176
3177 return;
3178 }
3179}
3180
3182 TemplateName BaseTemplate,
3183 SourceLocation TemplateLoc,
3185 auto lookUpCommonType = [&](TemplateArgument T1,
3186 TemplateArgument T2) -> QualType {
3187 // Don't bother looking for other specializations if both types are
3188 // builtins - users aren't allowed to specialize for them
3189 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3190 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3191 {T1, T2});
3192
3196 Args.addArgument(TemplateArgumentLoc(
3197 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3198
3199 EnterExpressionEvaluationContext UnevaluatedContext(
3201 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3203
3204 QualType BaseTemplateInst = S.CheckTemplateIdType(
3205 Keyword, BaseTemplate, TemplateLoc, Args,
3206 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3207
3208 if (SFINAE.hasErrorOccurred())
3209 return QualType();
3210
3211 return BaseTemplateInst;
3212 };
3213
3214 // Note A: For the common_type trait applied to a template parameter pack T of
3215 // types, the member type shall be either defined or not present as follows:
3216 switch (Ts.size()) {
3217
3218 // If sizeof...(T) is zero, there shall be no member type.
3219 case 0:
3220 return QualType();
3221
3222 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3223 // pack T. The member typedef-name type shall denote the same type, if any, as
3224 // common_type_t<T0, T0>; otherwise there shall be no member type.
3225 case 1:
3226 return lookUpCommonType(Ts[0], Ts[0]);
3227
3228 // If sizeof...(T) is two, let the first and second types constituting T be
3229 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3230 // as decay_t<T1> and decay_t<T2>, respectively.
3231 case 2: {
3232 QualType T1 = Ts[0].getAsType();
3233 QualType T2 = Ts[1].getAsType();
3234 QualType D1 = S.BuiltinDecay(T1, {});
3235 QualType D2 = S.BuiltinDecay(T2, {});
3236
3237 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3238 // the same type, if any, as common_type_t<D1, D2>.
3239 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3240 return lookUpCommonType(D1, D2);
3241
3242 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3243 // denotes a valid type, let C denote that type.
3244 {
3245 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3246 EnterExpressionEvaluationContext UnevaluatedContext(
3248 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3250
3251 // false
3253 VK_PRValue);
3254 ExprResult Cond = &CondExpr;
3255
3256 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3257 if (ConstRefQual) {
3258 D1.addConst();
3259 D2.addConst();
3260 }
3261
3262 // declval<D1>()
3263 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3264 ExprResult LHS = &LHSExpr;
3265
3266 // declval<D2>()
3267 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3268 ExprResult RHS = &RHSExpr;
3269
3272
3273 // decltype(false ? declval<D1>() : declval<D2>())
3274 QualType Result =
3275 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3276
3277 if (Result.isNull() || SFINAE.hasErrorOccurred())
3278 return QualType();
3279
3280 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3281 return S.BuiltinDecay(Result, TemplateLoc);
3282 };
3283
3284 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3285 return Res;
3286
3287 // Let:
3288 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3289 // COND-RES(X, Y) be
3290 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3291
3292 // C++20 only
3293 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3294 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3295 if (!S.Context.getLangOpts().CPlusPlus20)
3296 return QualType();
3297 return CheckConditionalOperands(true);
3298 }
3299 }
3300
3301 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3302 // denote the first, second, and (pack of) remaining types constituting T. Let
3303 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3304 // a type C, the member typedef-name type shall denote the same type, if any,
3305 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3306 default: {
3307 QualType Result = Ts.front().getAsType();
3308 for (auto T : llvm::drop_begin(Ts)) {
3309 Result = lookUpCommonType(Result, T.getAsType());
3310 if (Result.isNull())
3311 return QualType();
3312 }
3313 return Result;
3314 }
3315 }
3316}
3317
3318static bool isInVkNamespace(const RecordType *RT) {
3319 DeclContext *DC = RT->getOriginalDecl()->getDeclContext();
3320 if (!DC)
3321 return false;
3322
3323 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3324 if (!ND)
3325 return false;
3326
3327 return ND->getQualifiedNameAsString() == "hlsl::vk";
3328}
3329
3330static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3331 QualType OperandArg,
3332 SourceLocation Loc) {
3333 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3334 bool Literal = false;
3335 SourceLocation LiteralLoc;
3336 if (isInVkNamespace(RT) && RT->getOriginalDecl()->getName() == "Literal") {
3337 auto SpecDecl =
3338 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3339 assert(SpecDecl);
3340
3341 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3342 QualType ConstantType = LiteralArgs[0].getAsType();
3343 RT = ConstantType->getAsCanonical<RecordType>();
3344 Literal = true;
3345 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3346 }
3347
3348 if (RT && isInVkNamespace(RT) &&
3349 RT->getOriginalDecl()->getName() == "integral_constant") {
3350 auto SpecDecl =
3351 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3352 assert(SpecDecl);
3353
3354 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3355
3356 QualType ConstantType = ConstantArgs[0].getAsType();
3357 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3358
3359 if (Literal)
3360 return SpirvOperand::createLiteral(Value);
3361 return SpirvOperand::createConstant(ConstantType, Value);
3362 } else if (Literal) {
3363 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3364 return SpirvOperand();
3365 }
3366 }
3367 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3368 diag::err_call_incomplete_argument))
3369 return SpirvOperand();
3370 return SpirvOperand::createType(OperandArg);
3371}
3372
3375 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3376 TemplateArgumentListInfo &TemplateArgs) {
3377 ASTContext &Context = SemaRef.getASTContext();
3378
3379 switch (BTD->getBuiltinTemplateKind()) {
3380 case BTK__make_integer_seq: {
3381 // Specializations of __make_integer_seq<S, T, N> are treated like
3382 // S<T, 0, ..., N-1>.
3383
3384 QualType OrigType = Converted[1].getAsType();
3385 // C++14 [inteseq.intseq]p1:
3386 // T shall be an integer type.
3387 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3388 SemaRef.Diag(TemplateArgs[1].getLocation(),
3389 diag::err_integer_sequence_integral_element_type);
3390 return QualType();
3391 }
3392
3393 TemplateArgument NumArgsArg = Converted[2];
3394 if (NumArgsArg.isDependent())
3395 return QualType();
3396
3397 TemplateArgumentListInfo SyntheticTemplateArgs;
3398 // The type argument, wrapped in substitution sugar, gets reused as the
3399 // first template argument in the synthetic template argument list.
3400 SyntheticTemplateArgs.addArgument(
3403 OrigType, TemplateArgs[1].getLocation())));
3404
3405 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3406 // Expand N into 0 ... N-1.
3407 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3408 I < NumArgs; ++I) {
3409 TemplateArgument TA(Context, I, OrigType);
3410 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3411 TA, OrigType, TemplateArgs[2].getLocation()));
3412 }
3413 } else {
3414 // C++14 [inteseq.make]p1:
3415 // If N is negative the program is ill-formed.
3416 SemaRef.Diag(TemplateArgs[2].getLocation(),
3417 diag::err_integer_sequence_negative_length);
3418 return QualType();
3419 }
3420
3421 // The first template argument will be reused as the template decl that
3422 // our synthetic template arguments will be applied to.
3423 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3424 TemplateLoc, SyntheticTemplateArgs,
3425 /*Scope=*/nullptr,
3426 /*ForNestedNameSpecifier=*/false);
3427 }
3428
3429 case BTK__type_pack_element: {
3430 // Specializations of
3431 // __type_pack_element<Index, T_1, ..., T_N>
3432 // are treated like T_Index.
3433 assert(Converted.size() == 2 &&
3434 "__type_pack_element should be given an index and a parameter pack");
3435
3436 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3437 if (IndexArg.isDependent() || Ts.isDependent())
3438 return QualType();
3439
3440 llvm::APSInt Index = IndexArg.getAsIntegral();
3441 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3442 "type std::size_t, and hence be non-negative");
3443 // If the Index is out of bounds, the program is ill-formed.
3444 if (Index >= Ts.pack_size()) {
3445 SemaRef.Diag(TemplateArgs[0].getLocation(),
3446 diag::err_type_pack_element_out_of_bounds);
3447 return QualType();
3448 }
3449
3450 // We simply return the type at index `Index`.
3451 int64_t N = Index.getExtValue();
3452 return Ts.getPackAsArray()[N].getAsType();
3453 }
3454
3455 case BTK__builtin_common_type: {
3456 assert(Converted.size() == 4);
3457 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3458 return QualType();
3459
3460 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3461 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3462 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3463 TemplateLoc, Ts);
3464 !CT.isNull()) {
3468 CT, TemplateArgs[1].getLocation())));
3469 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3470 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3471 TAs, /*Scope=*/nullptr,
3472 /*ForNestedNameSpecifier=*/false);
3473 }
3474 QualType HasNoTypeMember = Converted[2].getAsType();
3475 return HasNoTypeMember;
3476 }
3477
3478 case BTK__hlsl_spirv_type: {
3479 assert(Converted.size() == 4);
3480
3481 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3482 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3483 }
3484
3485 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3486 return QualType();
3487
3488 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3489 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3490 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3491
3492 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3493
3495
3496 for (auto &OperandTA : OperandArgs) {
3497 QualType OperandArg = OperandTA.getAsType();
3498 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3499 TemplateArgs[3].getLocation());
3500 if (!Operand.isValid())
3501 return QualType();
3502 Operands.push_back(Operand);
3503 }
3504
3505 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3506 }
3507 case BTK__builtin_dedup_pack: {
3508 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3509 "a parameter pack");
3510 TemplateArgument Ts = Converted[0];
3511 // Delay the computation until we can compute the final result. We choose
3512 // not to remove the duplicates upfront before substitution to keep the code
3513 // simple.
3514 if (Ts.isDependent())
3515 return QualType();
3516 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3518 llvm::SmallDenseSet<QualType> Seen;
3519 // Synthesize a new template argument list, removing duplicates.
3520 for (auto T : Ts.getPackAsArray()) {
3521 assert(T.getKind() == clang::TemplateArgument::Type);
3522 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3523 continue;
3524 OutArgs.push_back(T);
3525 }
3526 return Context.getSubstBuiltinTemplatePack(
3527 TemplateArgument::CreatePackCopy(Context, OutArgs));
3528 }
3529 }
3530 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3531}
3532
3533/// Determine whether this alias template is "enable_if_t".
3534/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3536 return AliasTemplate->getName() == "enable_if_t" ||
3537 AliasTemplate->getName() == "__enable_if_t";
3538}
3539
3540/// Collect all of the separable terms in the given condition, which
3541/// might be a conjunction.
3542///
3543/// FIXME: The right answer is to convert the logical expression into
3544/// disjunctive normal form, so we can find the first failed term
3545/// within each possible clause.
3546static void collectConjunctionTerms(Expr *Clause,
3547 SmallVectorImpl<Expr *> &Terms) {
3548 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3549 if (BinOp->getOpcode() == BO_LAnd) {
3550 collectConjunctionTerms(BinOp->getLHS(), Terms);
3551 collectConjunctionTerms(BinOp->getRHS(), Terms);
3552 return;
3553 }
3554 }
3555
3556 Terms.push_back(Clause);
3557}
3558
3559// The ranges-v3 library uses an odd pattern of a top-level "||" with
3560// a left-hand side that is value-dependent but never true. Identify
3561// the idiom and ignore that term.
3563 // Top-level '||'.
3564 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3565 if (!BinOp) return Cond;
3566
3567 if (BinOp->getOpcode() != BO_LOr) return Cond;
3568
3569 // With an inner '==' that has a literal on the right-hand side.
3570 Expr *LHS = BinOp->getLHS();
3571 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3572 if (!InnerBinOp) return Cond;
3573
3574 if (InnerBinOp->getOpcode() != BO_EQ ||
3575 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3576 return Cond;
3577
3578 // If the inner binary operation came from a macro expansion named
3579 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3580 // of the '||', which is the real, user-provided condition.
3581 SourceLocation Loc = InnerBinOp->getExprLoc();
3582 if (!Loc.isMacroID()) return Cond;
3583
3584 StringRef MacroName = PP.getImmediateMacroName(Loc);
3585 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3586 return BinOp->getRHS();
3587
3588 return Cond;
3589}
3590
3591namespace {
3592
3593// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3594// within failing boolean expression, such as substituting template parameters
3595// for actual types.
3596class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3597public:
3598 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3599 : Policy(P) {}
3600
3601 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3602 const auto *DR = dyn_cast<DeclRefExpr>(E);
3603 if (DR && DR->getQualifier()) {
3604 // If this is a qualified name, expand the template arguments in nested
3605 // qualifiers.
3606 DR->getQualifier().print(OS, Policy, true);
3607 // Then print the decl itself.
3608 const ValueDecl *VD = DR->getDecl();
3609 OS << VD->getName();
3610 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3611 // This is a template variable, print the expanded template arguments.
3612 printTemplateArgumentList(
3613 OS, IV->getTemplateArgs().asArray(), Policy,
3614 IV->getSpecializedTemplate()->getTemplateParameters());
3615 }
3616 return true;
3617 }
3618 return false;
3619 }
3620
3621private:
3622 const PrintingPolicy Policy;
3623};
3624
3625} // end anonymous namespace
3626
3627std::pair<Expr *, std::string>
3630
3631 // Separate out all of the terms in a conjunction.
3634
3635 // Determine which term failed.
3636 Expr *FailedCond = nullptr;
3637 for (Expr *Term : Terms) {
3638 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3639
3640 // Literals are uninteresting.
3641 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3642 isa<IntegerLiteral>(TermAsWritten))
3643 continue;
3644
3645 // The initialization of the parameter from the argument is
3646 // a constant-evaluated context.
3649
3650 bool Succeeded;
3651 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3652 !Succeeded) {
3653 FailedCond = TermAsWritten;
3654 break;
3655 }
3656 }
3657 if (!FailedCond)
3658 FailedCond = Cond->IgnoreParenImpCasts();
3659
3660 std::string Description;
3661 {
3662 llvm::raw_string_ostream Out(Description);
3664 Policy.PrintAsCanonical = true;
3665 FailedBooleanConditionPrinterHelper Helper(Policy);
3666 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3667 }
3668 return { FailedCond, Description };
3669}
3670
3671static TemplateName
3673 const AssumedTemplateStorage *ATN,
3674 SourceLocation NameLoc) {
3675 // We assumed this undeclared identifier to be an (ADL-only) function
3676 // template name, but it was used in a context where a type was required.
3677 // Try to typo-correct it now.
3678 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3679 struct CandidateCallback : CorrectionCandidateCallback {
3680 bool ValidateCandidate(const TypoCorrection &TC) override {
3681 return TC.getCorrectionDecl() &&
3683 }
3684 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3685 return std::make_unique<CandidateCallback>(*this);
3686 }
3687 } FilterCCC;
3688
3689 TypoCorrection Corrected =
3691 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3692 if (Corrected && Corrected.getFoundDecl()) {
3693 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3694 << ATN->getDeclName());
3696 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3698 }
3699
3700 return TemplateName();
3701}
3702
3704 TemplateName Name,
3705 SourceLocation TemplateLoc,
3706 TemplateArgumentListInfo &TemplateArgs,
3707 Scope *Scope, bool ForNestedNameSpecifier) {
3708 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3709
3710 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3711 if (!Template) {
3712 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3713 Template = S->getParameterPack();
3714 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3715 if (DTN->getName().getIdentifier())
3716 // When building a template-id where the template-name is dependent,
3717 // assume the template is a type template. Either our assumption is
3718 // correct, or the code is ill-formed and will be diagnosed when the
3719 // dependent name is substituted.
3720 return Context.getTemplateSpecializationType(Keyword, Name,
3721 TemplateArgs.arguments(),
3722 /*CanonicalArgs=*/{});
3723 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3725 *this, Scope, ATN, TemplateLoc);
3726 CorrectedName.isNull()) {
3727 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3728 return QualType();
3729 } else {
3730 Name = CorrectedName;
3731 Template = Name.getAsTemplateDecl();
3732 }
3733 }
3734 }
3735 if (!Template ||
3737 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3738 if (ForNestedNameSpecifier)
3739 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3740 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3741 else
3742 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3744 return QualType();
3745 }
3746
3747 // Check that the template argument list is well-formed for this
3748 // template.
3750 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3751 DefaultArgs, /*PartialTemplateArgs=*/false,
3752 CTAI,
3753 /*UpdateArgsWithConversions=*/true))
3754 return QualType();
3755
3756 QualType CanonType;
3757
3759 // We might have a substituted template template parameter pack. If so,
3760 // build a template specialization type for it.
3762 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3763
3764 // C++0x [dcl.type.elab]p2:
3765 // If the identifier resolves to a typedef-name or the simple-template-id
3766 // resolves to an alias template specialization, the
3767 // elaborated-type-specifier is ill-formed.
3770 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3773 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3774 }
3775
3776 // Find the canonical type for this type alias template specialization.
3777 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3778 if (Pattern->isInvalidDecl())
3779 return QualType();
3780
3781 // Only substitute for the innermost template argument list.
3782 MultiLevelTemplateArgumentList TemplateArgLists;
3784 /*Final=*/true);
3785 TemplateArgLists.addOuterRetainedLevels(
3786 AliasTemplate->getTemplateParameters()->getDepth());
3787
3790 *this, /*PointOfInstantiation=*/TemplateLoc,
3791 /*Entity=*/AliasTemplate,
3792 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3793
3794 // Diagnose uses of this alias.
3795 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3796
3797 if (Inst.isInvalid())
3798 return QualType();
3799
3800 std::optional<ContextRAII> SavedContext;
3801 if (!AliasTemplate->getDeclContext()->isFileContext())
3802 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3803
3804 CanonType =
3805 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3806 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3807 if (CanonType.isNull()) {
3808 // If this was enable_if and we failed to find the nested type
3809 // within enable_if in a SFINAE context, dig out the specific
3810 // enable_if condition that failed and present that instead.
3812 if (auto DeductionInfo = isSFINAEContext()) {
3813 if (*DeductionInfo &&
3814 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3815 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3816 diag::err_typename_nested_not_found_enable_if &&
3817 TemplateArgs[0].getArgument().getKind()
3819 Expr *FailedCond;
3820 std::string FailedDescription;
3821 std::tie(FailedCond, FailedDescription) =
3822 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3823
3824 // Remove the old SFINAE diagnostic.
3825 PartialDiagnosticAt OldDiag =
3827 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3828
3829 // Add a new SFINAE diagnostic specifying which condition
3830 // failed.
3831 (*DeductionInfo)->addSFINAEDiagnostic(
3832 OldDiag.first,
3833 PDiag(diag::err_typename_nested_not_found_requirement)
3834 << FailedDescription
3835 << FailedCond->getSourceRange());
3836 }
3837 }
3838 }
3839
3840 return QualType();
3841 }
3842 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3843 CanonType = checkBuiltinTemplateIdType(
3844 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3845 } else if (Name.isDependent() ||
3846 TemplateSpecializationType::anyDependentTemplateArguments(
3847 TemplateArgs, CTAI.CanonicalConverted)) {
3848 // This class template specialization is a dependent
3849 // type. Therefore, its canonical type is another class template
3850 // specialization type that contains all of the converted
3851 // arguments in canonical form. This ensures that, e.g., A<T> and
3852 // A<T, T> have identical types when A is declared as:
3853 //
3854 // template<typename T, typename U = T> struct A;
3855 CanonType = Context.getCanonicalTemplateSpecializationType(
3857 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3858 CTAI.CanonicalConverted);
3859 assert(CanonType->isCanonicalUnqualified());
3860
3861 // This might work out to be a current instantiation, in which
3862 // case the canonical type needs to be the InjectedClassNameType.
3863 //
3864 // TODO: in theory this could be a simple hashtable lookup; most
3865 // changes to CurContext don't change the set of current
3866 // instantiations.
3868 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3869 // If we get out to a namespace, we're done.
3870 if (Ctx->isFileContext()) break;
3871
3872 // If this isn't a record, keep looking.
3873 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3874 if (!Record) continue;
3875
3876 // Look for one of the two cases with InjectedClassNameTypes
3877 // and check whether it's the same template.
3879 !Record->getDescribedClassTemplate())
3880 continue;
3881
3882 // Fetch the injected class name type and check whether its
3883 // injected type is equal to the type we just built.
3884 CanQualType ICNT = Context.getCanonicalTagType(Record);
3885 CanQualType Injected =
3886 Record->getCanonicalTemplateSpecializationType(Context);
3887
3888 if (CanonType != Injected)
3889 continue;
3890
3891 // If so, the canonical type of this TST is the injected
3892 // class name type of the record we just found.
3893 CanonType = ICNT;
3894 break;
3895 }
3896 }
3897 } else if (ClassTemplateDecl *ClassTemplate =
3898 dyn_cast<ClassTemplateDecl>(Template)) {
3899 // Find the class template specialization declaration that
3900 // corresponds to these arguments.
3901 void *InsertPos = nullptr;
3903 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3904 if (!Decl) {
3905 // This is the first time we have referenced this class template
3906 // specialization. Create the canonical declaration and add it to
3907 // the set of specializations.
3909 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3910 ClassTemplate->getDeclContext(),
3911 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3912 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3913 CTAI.StrictPackMatch, nullptr);
3914 ClassTemplate->AddSpecialization(Decl, InsertPos);
3915 if (ClassTemplate->isOutOfLine())
3916 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3917 }
3918
3919 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3920 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3921 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3922 if (!Inst.isInvalid()) {
3924 CTAI.CanonicalConverted,
3925 /*Final=*/false);
3926 InstantiateAttrsForDecl(TemplateArgLists,
3927 ClassTemplate->getTemplatedDecl(), Decl);
3928 }
3929 }
3930
3931 // Diagnose uses of this specialization.
3932 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3933
3934 CanonType = Context.getCanonicalTagType(Decl);
3935 assert(isa<RecordType>(CanonType) &&
3936 "type of non-dependent specialization is not a RecordType");
3937 } else {
3938 llvm_unreachable("Unhandled template kind");
3939 }
3940
3941 // Build the fully-sugared type for this class template
3942 // specialization, which refers back to the class template
3943 // specialization we created or found.
3944 return Context.getTemplateSpecializationType(
3945 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
3946 CanonType);
3947}
3948
3950 TemplateNameKind &TNK,
3951 SourceLocation NameLoc,
3952 IdentifierInfo *&II) {
3953 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3954
3955 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
3956 assert(ATN && "not an assumed template name");
3957 II = ATN->getDeclName().getAsIdentifierInfo();
3958
3959 if (TemplateName Name =
3960 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
3961 !Name.isNull()) {
3962 // Resolved to a type template name.
3963 ParsedName = TemplateTy::make(Name);
3964 TNK = TNK_Type_template;
3965 }
3966}
3967
3969 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
3970 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
3971 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
3972 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
3973 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
3974 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
3975 ImplicitTypenameContext AllowImplicitTypename) {
3976 if (SS.isInvalid())
3977 return true;
3978
3979 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3980 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3981
3982 // C++ [temp.res]p3:
3983 // A qualified-id that refers to a type and in which the
3984 // nested-name-specifier depends on a template-parameter (14.6.2)
3985 // shall be prefixed by the keyword typename to indicate that the
3986 // qualified-id denotes a type, forming an
3987 // elaborated-type-specifier (7.1.5.3).
3988 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3989 // C++2a relaxes some of those restrictions in [temp.res]p5.
3990 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
3991 SS.getScopeRep(), TemplateII);
3993 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3994 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
3995 << NNS;
3996 if (!getLangOpts().CPlusPlus20)
3997 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3998 } else
3999 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4000
4001 // FIXME: This is not quite correct recovery as we don't transform SS
4002 // into the corresponding dependent form (and we don't diagnose missing
4003 // 'template' keywords within SS as a result).
4004 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4005 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4006 TemplateArgsIn, RAngleLoc);
4007 }
4008
4009 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4010 // it's not actually allowed to be used as a type in most cases. Because
4011 // we annotate it before we know whether it's valid, we have to check for
4012 // this case here.
4013 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4014 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4015 Diag(TemplateIILoc,
4016 TemplateKWLoc.isInvalid()
4017 ? diag::err_out_of_line_qualified_id_type_names_constructor
4018 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4019 << TemplateII << 0 /*injected-class-name used as template name*/
4020 << 1 /*if any keyword was present, it was 'template'*/;
4021 }
4022 }
4023
4024 // Translate the parser's template argument list in our AST format.
4025 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4026 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4027
4029 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4030 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4031 if (SpecTy.isNull())
4032 return true;
4033
4034 // Build type-source information.
4035 TypeLocBuilder TLB;
4036 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4037 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4038 TemplateIILoc, TemplateArgs);
4039 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4040}
4041
4043 TypeSpecifierType TagSpec,
4044 SourceLocation TagLoc,
4045 CXXScopeSpec &SS,
4046 SourceLocation TemplateKWLoc,
4047 TemplateTy TemplateD,
4048 SourceLocation TemplateLoc,
4049 SourceLocation LAngleLoc,
4050 ASTTemplateArgsPtr TemplateArgsIn,
4051 SourceLocation RAngleLoc) {
4052 if (SS.isInvalid())
4053 return TypeResult(true);
4054
4055 // Translate the parser's template argument list in our AST format.
4056 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4057 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4058
4059 // Determine the tag kind
4063
4065 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4066 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4067 if (Result.isNull())
4068 return TypeResult(true);
4069
4070 // Check the tag kind
4071 if (const RecordType *RT = Result->getAs<RecordType>()) {
4072 RecordDecl *D = RT->getOriginalDecl();
4073
4074 IdentifierInfo *Id = D->getIdentifier();
4075 assert(Id && "templated class must have an identifier");
4076
4078 TagLoc, Id)) {
4079 Diag(TagLoc, diag::err_use_with_wrong_tag)
4080 << Result
4082 Diag(D->getLocation(), diag::note_previous_use);
4083 }
4084 }
4085
4086 // Provide source-location information for the template specialization.
4087 TypeLocBuilder TLB;
4089 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4090 TemplateArgs);
4092}
4093
4094static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4095 NamedDecl *PrevDecl,
4096 SourceLocation Loc,
4098
4100
4102 unsigned Depth,
4103 unsigned Index) {
4104 switch (Arg.getKind()) {
4112 return false;
4113
4115 QualType Type = Arg.getAsType();
4116 const TemplateTypeParmType *TPT =
4117 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4118 return TPT && !Type.hasQualifiers() &&
4119 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4120 }
4121
4123 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4124 if (!DRE || !DRE->getDecl())
4125 return false;
4126 const NonTypeTemplateParmDecl *NTTP =
4127 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4128 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4129 }
4130
4132 const TemplateTemplateParmDecl *TTP =
4133 dyn_cast_or_null<TemplateTemplateParmDecl>(
4135 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4136 }
4137 llvm_unreachable("unexpected kind of template argument");
4138}
4139
4141 TemplateParameterList *SpecParams,
4143 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4144 return false;
4145
4146 unsigned Depth = Params->getDepth();
4147
4148 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4149 TemplateArgument Arg = Args[I];
4150
4151 // If the parameter is a pack expansion, the argument must be a pack
4152 // whose only element is a pack expansion.
4153 if (Params->getParam(I)->isParameterPack()) {
4154 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4155 !Arg.pack_begin()->isPackExpansion())
4156 return false;
4157 Arg = Arg.pack_begin()->getPackExpansionPattern();
4158 }
4159
4160 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4161 return false;
4162
4163 // For NTTPs further specialization is allowed via deduced types, so
4164 // we need to make sure to only reject here if primary template and
4165 // specialization use the same type for the NTTP.
4166 if (auto *SpecNTTP =
4167 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4168 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4169 if (!NTTP || NTTP->getType().getCanonicalType() !=
4170 SpecNTTP->getType().getCanonicalType())
4171 return false;
4172 }
4173 }
4174
4175 return true;
4176}
4177
4178template<typename PartialSpecDecl>
4179static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4180 if (Partial->getDeclContext()->isDependentContext())
4181 return;
4182
4183 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4184 // for non-substitution-failure issues?
4185 TemplateDeductionInfo Info(Partial->getLocation());
4186 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4187 return;
4188
4189 auto *Template = Partial->getSpecializedTemplate();
4190 S.Diag(Partial->getLocation(),
4191 diag::ext_partial_spec_not_more_specialized_than_primary)
4193
4194 if (Info.hasSFINAEDiagnostic()) {
4198 SmallString<128> SFINAEArgString;
4199 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4200 S.Diag(Diag.first,
4201 diag::note_partial_spec_not_more_specialized_than_primary)
4202 << SFINAEArgString;
4203 }
4204
4206 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4207 Template->getAssociatedConstraints(TemplateAC);
4208 Partial->getAssociatedConstraints(PartialAC);
4210 TemplateAC);
4211}
4212
4213static void
4215 const llvm::SmallBitVector &DeducibleParams) {
4216 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4217 if (!DeducibleParams[I]) {
4218 NamedDecl *Param = TemplateParams->getParam(I);
4219 if (Param->getDeclName())
4220 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4221 << Param->getDeclName();
4222 else
4223 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4224 << "(anonymous)";
4225 }
4226 }
4227}
4228
4229
4230template<typename PartialSpecDecl>
4232 PartialSpecDecl *Partial) {
4233 // C++1z [temp.class.spec]p8: (DR1495)
4234 // - The specialization shall be more specialized than the primary
4235 // template (14.5.5.2).
4237
4238 // C++ [temp.class.spec]p8: (DR1315)
4239 // - Each template-parameter shall appear at least once in the
4240 // template-id outside a non-deduced context.
4241 // C++1z [temp.class.spec.match]p3 (P0127R2)
4242 // If the template arguments of a partial specialization cannot be
4243 // deduced because of the structure of its template-parameter-list
4244 // and the template-id, the program is ill-formed.
4245 auto *TemplateParams = Partial->getTemplateParameters();
4246 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4247 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4248 TemplateParams->getDepth(), DeducibleParams);
4249
4250 if (!DeducibleParams.all()) {
4251 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4252 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4254 << (NumNonDeducible > 1)
4255 << SourceRange(Partial->getLocation(),
4256 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4257 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4258 }
4259}
4260
4265
4270
4272 // C++1z [temp.param]p11:
4273 // A template parameter of a deduction guide template that does not have a
4274 // default-argument shall be deducible from the parameter-type-list of the
4275 // deduction guide template.
4276 auto *TemplateParams = TD->getTemplateParameters();
4277 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4278 MarkDeducedTemplateParameters(TD, DeducibleParams);
4279 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4280 // A parameter pack is deducible (to an empty pack).
4281 auto *Param = TemplateParams->getParam(I);
4282 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4283 DeducibleParams[I] = true;
4284 }
4285
4286 if (!DeducibleParams.all()) {
4287 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4288 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4289 << (NumNonDeducible > 1);
4290 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4291 }
4292}
4293
4296 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4298 // D must be variable template id.
4300 "Variable template specialization is declared with a template id.");
4301
4302 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4303 TemplateArgumentListInfo TemplateArgs =
4304 makeTemplateArgumentListInfo(*this, *TemplateId);
4305 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4306 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4307 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4308
4309 TemplateName Name = TemplateId->Template.get();
4310
4311 // The template-id must name a variable template.
4313 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4314 if (!VarTemplate) {
4315 NamedDecl *FnTemplate;
4316 if (auto *OTS = Name.getAsOverloadedTemplate())
4317 FnTemplate = *OTS->begin();
4318 else
4319 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4320 if (FnTemplate)
4321 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4322 << FnTemplate->getDeclName();
4323 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4325 }
4326
4327 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4328 auto Message = DSA->getMessage();
4329 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4330 << VarTemplate << !Message.empty() << Message;
4331 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4332 }
4333
4334 // Check for unexpanded parameter packs in any of the template arguments.
4335 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4336 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4340 return true;
4341
4342 // Check that the template argument list is well-formed for this
4343 // template.
4345 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4346 /*DefaultArgs=*/{},
4347 /*PartialTemplateArgs=*/false, CTAI,
4348 /*UpdateArgsWithConversions=*/true))
4349 return true;
4350
4351 // Find the variable template (partial) specialization declaration that
4352 // corresponds to these arguments.
4355 TemplateArgs.size(),
4356 CTAI.CanonicalConverted))
4357 return true;
4358
4359 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4360 // we also do them during instantiation.
4361 if (!Name.isDependent() &&
4362 !TemplateSpecializationType::anyDependentTemplateArguments(
4363 TemplateArgs, CTAI.CanonicalConverted)) {
4364 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4365 << VarTemplate->getDeclName();
4367 }
4368
4369 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4370 TemplateParams, CTAI.CanonicalConverted) &&
4371 (!Context.getLangOpts().CPlusPlus20 ||
4372 !TemplateParams->hasAssociatedConstraints())) {
4373 // C++ [temp.class.spec]p9b3:
4374 //
4375 // -- The argument list of the specialization shall not be identical
4376 // to the implicit argument list of the primary template.
4377 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4378 << /*variable template*/ 1
4379 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4380 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4381 // FIXME: Recover from this by treating the declaration as a
4382 // redeclaration of the primary template.
4383 return true;
4384 }
4385 }
4386
4387 void *InsertPos = nullptr;
4388 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4389
4391 PrevDecl = VarTemplate->findPartialSpecialization(
4392 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4393 else
4394 PrevDecl =
4395 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4396
4398
4399 // Check whether we can declare a variable template specialization in
4400 // the current scope.
4401 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4402 TemplateNameLoc,
4404 return true;
4405
4406 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4407 // Since the only prior variable template specialization with these
4408 // arguments was referenced but not declared, reuse that
4409 // declaration node as our own, updating its source location and
4410 // the list of outer template parameters to reflect our new declaration.
4411 Specialization = PrevDecl;
4412 Specialization->setLocation(TemplateNameLoc);
4413 PrevDecl = nullptr;
4414 } else if (IsPartialSpecialization) {
4415 // Create a new class template partial specialization declaration node.
4417 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4420 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4421 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4422 CTAI.CanonicalConverted);
4423 Partial->setTemplateArgsAsWritten(TemplateArgs);
4424
4425 if (!PrevPartial)
4426 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4427 Specialization = Partial;
4428
4429 // If we are providing an explicit specialization of a member variable
4430 // template specialization, make a note of that.
4431 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4432 PrevPartial->setMemberSpecialization();
4433
4435 } else {
4436 // Create a new class template specialization declaration node for
4437 // this explicit specialization or friend declaration.
4439 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4440 VarTemplate, DI->getType(), DI, SC, CTAI.CanonicalConverted);
4441 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4442
4443 if (!PrevDecl)
4444 VarTemplate->AddSpecialization(Specialization, InsertPos);
4445 }
4446
4447 // C++ [temp.expl.spec]p6:
4448 // If a template, a member template or the member of a class template is
4449 // explicitly specialized then that specialization shall be declared
4450 // before the first use of that specialization that would cause an implicit
4451 // instantiation to take place, in every translation unit in which such a
4452 // use occurs; no diagnostic is required.
4453 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4454 bool Okay = false;
4455 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4456 // Is there any previous explicit specialization declaration?
4458 Okay = true;
4459 break;
4460 }
4461 }
4462
4463 if (!Okay) {
4464 SourceRange Range(TemplateNameLoc, RAngleLoc);
4465 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4466 << Name << Range;
4467
4468 Diag(PrevDecl->getPointOfInstantiation(),
4469 diag::note_instantiation_required_here)
4470 << (PrevDecl->getTemplateSpecializationKind() !=
4472 return true;
4473 }
4474 }
4475
4476 Specialization->setLexicalDeclContext(CurContext);
4477
4478 // Add the specialization into its lexical context, so that it can
4479 // be seen when iterating through the list of declarations in that
4480 // context. However, specializations are not found by name lookup.
4481 CurContext->addDecl(Specialization);
4482
4483 // Note that this is an explicit specialization.
4484 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4485
4486 Previous.clear();
4487 if (PrevDecl)
4488 Previous.addDecl(PrevDecl);
4489 else if (Specialization->isStaticDataMember() &&
4490 Specialization->isOutOfLine())
4491 Specialization->setAccess(VarTemplate->getAccess());
4492
4493 return Specialization;
4494}
4495
4496namespace {
4497/// A partial specialization whose template arguments have matched
4498/// a given template-id.
4499struct PartialSpecMatchResult {
4502};
4503
4504// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4505// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4506static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4507 if (Var->getName() != "format_kind" ||
4508 !Var->getDeclContext()->isStdNamespace())
4509 return false;
4510
4511 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4512 // release in which users can access std::format_kind.
4513 // We can use 20250520 as the final date, see the following commits.
4514 // GCC releases/gcc-15 branch:
4515 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4516 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4517 // GCC master branch:
4518 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4519 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4520 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4521}
4522} // end anonymous namespace
4523
4526 SourceLocation TemplateNameLoc,
4527 const TemplateArgumentListInfo &TemplateArgs,
4528 bool SetWrittenArgs) {
4529 assert(Template && "A variable template id without template?");
4530
4531 // Check that the template argument list is well-formed for this template.
4534 Template, TemplateNameLoc,
4535 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4536 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4537 /*UpdateArgsWithConversions=*/true))
4538 return true;
4539
4540 // Produce a placeholder value if the specialization is dependent.
4541 if (Template->getDeclContext()->isDependentContext() ||
4542 TemplateSpecializationType::anyDependentTemplateArguments(
4543 TemplateArgs, CTAI.CanonicalConverted)) {
4544 if (ParsingInitForAutoVars.empty())
4545 return DeclResult();
4546
4547 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4548 const TemplateArgument &Arg2) {
4549 return Context.isSameTemplateArgument(Arg1, Arg2);
4550 };
4551
4552 if (VarDecl *Var = Template->getTemplatedDecl();
4553 ParsingInitForAutoVars.count(Var) &&
4554 // See comments on this function definition
4555 !IsLibstdcxxStdFormatKind(PP, Var) &&
4556 llvm::equal(
4557 CTAI.CanonicalConverted,
4558 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4559 IsSameTemplateArg)) {
4560 Diag(TemplateNameLoc,
4561 diag::err_auto_variable_cannot_appear_in_own_initializer)
4562 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4563 return true;
4564 }
4565
4567 Template->getPartialSpecializations(PartialSpecs);
4568 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4569 if (ParsingInitForAutoVars.count(Partial) &&
4570 llvm::equal(CTAI.CanonicalConverted,
4571 Partial->getTemplateArgs().asArray(),
4572 IsSameTemplateArg)) {
4573 Diag(TemplateNameLoc,
4574 diag::err_auto_variable_cannot_appear_in_own_initializer)
4575 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4576 << Partial->getType();
4577 return true;
4578 }
4579
4580 return DeclResult();
4581 }
4582
4583 // Find the variable template specialization declaration that
4584 // corresponds to these arguments.
4585 void *InsertPos = nullptr;
4587 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4588 checkSpecializationReachability(TemplateNameLoc, Spec);
4589 if (Spec->getType()->isUndeducedType()) {
4590 if (ParsingInitForAutoVars.count(Spec))
4591 Diag(TemplateNameLoc,
4592 diag::err_auto_variable_cannot_appear_in_own_initializer)
4593 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4594 << Spec->getType();
4595 else
4596 // We are substituting the initializer of this variable template
4597 // specialization.
4598 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4599 << Spec << Spec->getType();
4600
4601 return true;
4602 }
4603 // If we already have a variable template specialization, return it.
4604 return Spec;
4605 }
4606
4607 // This is the first time we have referenced this variable template
4608 // specialization. Create the canonical declaration and add it to
4609 // the set of specializations, based on the closest partial specialization
4610 // that it represents. That is,
4611 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4612 const TemplateArgumentList *PartialSpecArgs = nullptr;
4613 bool AmbiguousPartialSpec = false;
4614 typedef PartialSpecMatchResult MatchResult;
4616 SourceLocation PointOfInstantiation = TemplateNameLoc;
4617 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4618 /*ForTakingAddress=*/false);
4619
4620 // 1. Attempt to find the closest partial specialization that this
4621 // specializes, if any.
4622 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4623 // Perhaps better after unification of DeduceTemplateArguments() and
4624 // getMoreSpecializedPartialSpecialization().
4626 Template->getPartialSpecializations(PartialSpecs);
4627
4628 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4629 // C++ [temp.spec.partial.member]p2:
4630 // If the primary member template is explicitly specialized for a given
4631 // (implicit) specialization of the enclosing class template, the partial
4632 // specializations of the member template are ignored for this
4633 // specialization of the enclosing class template. If a partial
4634 // specialization of the member template is explicitly specialized for a
4635 // given (implicit) specialization of the enclosing class template, the
4636 // primary member template and its other partial specializations are still
4637 // considered for this specialization of the enclosing class template.
4638 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4639 !Partial->getMostRecentDecl()->isMemberSpecialization())
4640 continue;
4641
4642 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4643
4645 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4647 // Store the failed-deduction information for use in diagnostics, later.
4648 // TODO: Actually use the failed-deduction info?
4649 FailedCandidates.addCandidate().set(
4652 (void)Result;
4653 } else {
4654 Matched.push_back(PartialSpecMatchResult());
4655 Matched.back().Partial = Partial;
4656 Matched.back().Args = Info.takeSugared();
4657 }
4658 }
4659
4660 if (Matched.size() >= 1) {
4661 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4662 if (Matched.size() == 1) {
4663 // -- If exactly one matching specialization is found, the
4664 // instantiation is generated from that specialization.
4665 // We don't need to do anything for this.
4666 } else {
4667 // -- If more than one matching specialization is found, the
4668 // partial order rules (14.5.4.2) are used to determine
4669 // whether one of the specializations is more specialized
4670 // than the others. If none of the specializations is more
4671 // specialized than all of the other matching
4672 // specializations, then the use of the variable template is
4673 // ambiguous and the program is ill-formed.
4674 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4675 PEnd = Matched.end();
4676 P != PEnd; ++P) {
4677 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4678 PointOfInstantiation) ==
4679 P->Partial)
4680 Best = P;
4681 }
4682
4683 // Determine if the best partial specialization is more specialized than
4684 // the others.
4685 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4686 PEnd = Matched.end();
4687 P != PEnd; ++P) {
4689 P->Partial, Best->Partial,
4690 PointOfInstantiation) != Best->Partial) {
4691 AmbiguousPartialSpec = true;
4692 break;
4693 }
4694 }
4695 }
4696
4697 // Instantiate using the best variable template partial specialization.
4698 InstantiationPattern = Best->Partial;
4699 PartialSpecArgs = Best->Args;
4700 } else {
4701 // -- If no match is found, the instantiation is generated
4702 // from the primary template.
4703 // InstantiationPattern = Template->getTemplatedDecl();
4704 }
4705
4706 // 2. Create the canonical declaration.
4707 // Note that we do not instantiate a definition until we see an odr-use
4708 // in DoMarkVarDeclReferenced().
4709 // FIXME: LateAttrs et al.?
4711 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4712 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4713 if (!Decl)
4714 return true;
4715 if (SetWrittenArgs)
4716 Decl->setTemplateArgsAsWritten(TemplateArgs);
4717
4718 if (AmbiguousPartialSpec) {
4719 // Partial ordering did not produce a clear winner. Complain.
4721 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4722 << Decl;
4723
4724 // Print the matching partial specializations.
4725 for (MatchResult P : Matched)
4726 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4727 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4728 *P.Args);
4729 return true;
4730 }
4731
4733 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4734 Decl->setInstantiationOf(D, PartialSpecArgs);
4735
4736 checkSpecializationReachability(TemplateNameLoc, Decl);
4737
4738 assert(Decl && "No variable template specialization?");
4739 return Decl;
4740}
4741
4743 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4744 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4745 const TemplateArgumentListInfo *TemplateArgs) {
4746
4747 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4748 *TemplateArgs, /*SetWrittenArgs=*/false);
4749 if (Decl.isInvalid())
4750 return ExprError();
4751
4752 if (!Decl.get())
4753 return ExprResult();
4754
4755 VarDecl *Var = cast<VarDecl>(Decl.get());
4758 NameInfo.getLoc());
4759
4760 // Build an ordinary singleton decl ref.
4761 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4762}
4763
4765 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4767 const TemplateArgumentListInfo *TemplateArgs) {
4768 assert(Template && "A variable template id without template?");
4769
4770 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4771 Template->templateParameterKind() !=
4773 return ExprResult();
4774
4775 // Check that the template argument list is well-formed for this template.
4778 Template, TemplateLoc,
4779 // FIXME: TemplateArgs will not be modified because
4780 // UpdateArgsWithConversions is false, however, we should
4781 // CheckTemplateArgumentList to be const-correct.
4782 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4783 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4784 /*UpdateArgsWithConversions=*/false))
4785 return true;
4786
4788 R.addDecl(Template);
4789
4790 // FIXME: We model references to variable template and concept parameters
4791 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4792 // data, can generally be used in the same places and work the same way.
4793 // However, it might be cleaner to use a dedicated AST node in the long run.
4796 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4797 /*KnownDependent=*/false,
4798 /*KnownInstantiationDependent=*/false);
4799}
4800
4802 SourceLocation Loc) {
4803 Diag(Loc, diag::err_template_missing_args)
4804 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4805 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4806 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4807 }
4808}
4809
4811 bool TemplateKeyword,
4812 TemplateDecl *TD,
4813 SourceLocation Loc) {
4814 TemplateName Name = Context.getQualifiedTemplateName(
4815 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4817}
4818
4821 SourceLocation TemplateKWLoc,
4822 const DeclarationNameInfo &ConceptNameInfo,
4823 NamedDecl *FoundDecl,
4824 ConceptDecl *NamedConcept,
4825 const TemplateArgumentListInfo *TemplateArgs) {
4826 assert(NamedConcept && "A concept template id without a template?");
4827
4828 if (NamedConcept->isInvalidDecl())
4829 return ExprError();
4830
4833 NamedConcept, ConceptNameInfo.getLoc(),
4834 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4835 /*DefaultArgs=*/{},
4836 /*PartialTemplateArgs=*/false, CTAI,
4837 /*UpdateArgsWithConversions=*/false))
4838 return ExprError();
4839
4840 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4841
4843 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4844 CTAI.CanonicalConverted);
4845 ConstraintSatisfaction Satisfaction;
4846 bool AreArgsDependent =
4847 TemplateSpecializationType::anyDependentTemplateArguments(
4848 *TemplateArgs, CTAI.CanonicalConverted);
4849 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.CanonicalConverted,
4850 /*Final=*/false);
4852
4855
4856 if (!AreArgsDependent &&
4858 NamedConcept, AssociatedConstraint(NamedConcept->getConstraintExpr()),
4859 MLTAL,
4860 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4861 TemplateArgs->getRAngleLoc()),
4862 Satisfaction))
4863 return ExprError();
4865 Context,
4867 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4870 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4871}
4872
4874 SourceLocation TemplateKWLoc,
4875 LookupResult &R,
4876 bool RequiresADL,
4877 const TemplateArgumentListInfo *TemplateArgs) {
4878 // FIXME: Can we do any checking at this point? I guess we could check the
4879 // template arguments that we have against the template name, if the template
4880 // name refers to a single template. That's not a terribly common case,
4881 // though.
4882 // foo<int> could identify a single function unambiguously
4883 // This approach does NOT work, since f<int>(1);
4884 // gets resolved prior to resorting to overload resolution
4885 // i.e., template<class T> void f(double);
4886 // vs template<class T, class U> void f(U);
4887
4888 // These should be filtered out by our callers.
4889 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4890
4891 // Non-function templates require a template argument list.
4892 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4893 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4895 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4896 return ExprError();
4897 }
4898 }
4899 bool KnownDependent = false;
4900 // In C++1y, check variable template ids.
4901 if (R.getAsSingle<VarTemplateDecl>()) {
4904 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4905 if (Res.isInvalid() || Res.isUsable())
4906 return Res;
4907 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4908 KnownDependent = true;
4909 }
4910
4911 // We don't want lookup warnings at this point.
4913
4914 if (R.getAsSingle<ConceptDecl>()) {
4915 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4917 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4918 }
4919
4920 // Check variable template ids (C++17) and concept template parameters
4921 // (C++26).
4926 TemplateKWLoc, TemplateArgs);
4927
4928 // Function templates
4931 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4932 R.begin(), R.end(), KnownDependent,
4933 /*KnownInstantiationDependent=*/false);
4934 // Model the templates with UnresolvedTemplateTy. The expression should then
4935 // either be transformed in an instantiation or be diagnosed in
4936 // CheckPlaceholderExpr.
4937 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4939 ULE->setType(Context.UnresolvedTemplateTy);
4940
4941 return ULE;
4942}
4943
4945 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4946 const DeclarationNameInfo &NameInfo,
4947 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4948 assert(TemplateArgs || TemplateKWLoc.isValid());
4949
4950 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4951 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4952 /*EnteringContext=*/false, TemplateKWLoc))
4953 return ExprError();
4954
4955 if (R.isAmbiguous())
4956 return ExprError();
4957
4959 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4960
4961 if (R.empty()) {
4963 Diag(NameInfo.getLoc(), diag::err_no_member)
4964 << NameInfo.getName() << DC << SS.getRange();
4965 return ExprError();
4966 }
4967
4968 // If necessary, build an implicit class member access.
4969 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4970 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4971 /*S=*/nullptr);
4972
4973 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4974}
4975
4977 CXXScopeSpec &SS,
4978 SourceLocation TemplateKWLoc,
4979 const UnqualifiedId &Name,
4980 ParsedType ObjectType,
4981 bool EnteringContext,
4983 bool AllowInjectedClassName) {
4984 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4985 Diag(TemplateKWLoc,
4987 diag::warn_cxx98_compat_template_outside_of_template :
4988 diag::ext_template_outside_of_template)
4989 << FixItHint::CreateRemoval(TemplateKWLoc);
4990
4991 if (SS.isInvalid())
4992 return TNK_Non_template;
4993
4994 // Figure out where isTemplateName is going to look.
4995 DeclContext *LookupCtx = nullptr;
4996 if (SS.isNotEmpty())
4997 LookupCtx = computeDeclContext(SS, EnteringContext);
4998 else if (ObjectType)
4999 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5000
5001 // C++0x [temp.names]p5:
5002 // If a name prefixed by the keyword template is not the name of
5003 // a template, the program is ill-formed. [Note: the keyword
5004 // template may not be applied to non-template members of class
5005 // templates. -end note ] [ Note: as is the case with the
5006 // typename prefix, the template prefix is allowed in cases
5007 // where it is not strictly necessary; i.e., when the
5008 // nested-name-specifier or the expression on the left of the ->
5009 // or . is not dependent on a template-parameter, or the use
5010 // does not appear in the scope of a template. -end note]
5011 //
5012 // Note: C++03 was more strict here, because it banned the use of
5013 // the "template" keyword prior to a template-name that was not a
5014 // dependent name. C++ DR468 relaxed this requirement (the
5015 // "template" keyword is now permitted). We follow the C++0x
5016 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5017 bool MemberOfUnknownSpecialization;
5018 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5019 ObjectType, EnteringContext, Result,
5020 MemberOfUnknownSpecialization);
5021 if (TNK != TNK_Non_template) {
5022 // We resolved this to a (non-dependent) template name. Return it.
5023 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5024 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5026 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5027 // C++14 [class.qual]p2:
5028 // In a lookup in which function names are not ignored and the
5029 // nested-name-specifier nominates a class C, if the name specified
5030 // [...] is the injected-class-name of C, [...] the name is instead
5031 // considered to name the constructor
5032 //
5033 // We don't get here if naming the constructor would be valid, so we
5034 // just reject immediately and recover by treating the
5035 // injected-class-name as naming the template.
5036 Diag(Name.getBeginLoc(),
5037 diag::ext_out_of_line_qualified_id_type_names_constructor)
5038 << Name.Identifier
5039 << 0 /*injected-class-name used as template name*/
5040 << TemplateKWLoc.isValid();
5041 }
5042 return TNK;
5043 }
5044
5045 if (!MemberOfUnknownSpecialization) {
5046 // Didn't find a template name, and the lookup wasn't dependent.
5047 // Do the lookup again to determine if this is a "nothing found" case or
5048 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5049 // need to do this.
5051 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5053 // Tell LookupTemplateName that we require a template so that it diagnoses
5054 // cases where it finds a non-template.
5055 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5056 ? RequiredTemplateKind(TemplateKWLoc)
5058 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5059 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5060 !R.isAmbiguous()) {
5061 if (LookupCtx)
5062 Diag(Name.getBeginLoc(), diag::err_no_member)
5063 << DNI.getName() << LookupCtx << SS.getRange();
5064 else
5065 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5066 << DNI.getName() << SS.getRange();
5067 }
5068 return TNK_Non_template;
5069 }
5070
5071 NestedNameSpecifier Qualifier = SS.getScopeRep();
5072
5073 switch (Name.getKind()) {
5075 Result = TemplateTy::make(Context.getDependentTemplateName(
5076 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5078
5080 Result = TemplateTy::make(Context.getDependentTemplateName(
5081 {Qualifier, Name.OperatorFunctionId.Operator,
5082 TemplateKWLoc.isValid()}));
5083 return TNK_Function_template;
5084
5086 // This is a kind of template name, but can never occur in a dependent
5087 // scope (literal operators can only be declared at namespace scope).
5088 break;
5089
5090 default:
5091 break;
5092 }
5093
5094 // This name cannot possibly name a dependent template. Diagnose this now
5095 // rather than building a dependent template name that can never be valid.
5096 Diag(Name.getBeginLoc(),
5097 diag::err_template_kw_refers_to_dependent_non_template)
5099 << TemplateKWLoc.isValid() << TemplateKWLoc;
5100 return TNK_Non_template;
5101}
5102
5105 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5106 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5107 const TemplateArgument &Arg = AL.getArgument();
5109 TypeSourceInfo *TSI = nullptr;
5110
5111 // Check template type parameter.
5112 switch(Arg.getKind()) {
5114 // C++ [temp.arg.type]p1:
5115 // A template-argument for a template-parameter which is a
5116 // type shall be a type-id.
5117 ArgType = Arg.getAsType();
5118 TSI = AL.getTypeSourceInfo();
5119 break;
5122 // We have a template type parameter but the template argument
5123 // is a template without any arguments.
5124 SourceRange SR = AL.getSourceRange();
5127 return true;
5128 }
5130 // We have a template type parameter but the template argument is an
5131 // expression; see if maybe it is missing the "typename" keyword.
5132 CXXScopeSpec SS;
5133 DeclarationNameInfo NameInfo;
5134
5135 if (DependentScopeDeclRefExpr *ArgExpr =
5136 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5137 SS.Adopt(ArgExpr->getQualifierLoc());
5138 NameInfo = ArgExpr->getNameInfo();
5139 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5140 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5141 if (ArgExpr->isImplicitAccess()) {
5142 SS.Adopt(ArgExpr->getQualifierLoc());
5143 NameInfo = ArgExpr->getMemberNameInfo();
5144 }
5145 }
5146
5147 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5148 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5149 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5150
5151 if (Result.getAsSingle<TypeDecl>() ||
5152 Result.wasNotFoundInCurrentInstantiation()) {
5153 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5154 // Suggest that the user add 'typename' before the NNS.
5156 Diag(Loc, getLangOpts().MSVCCompat
5157 ? diag::ext_ms_template_type_arg_missing_typename
5158 : diag::err_template_arg_must_be_type_suggest)
5159 << FixItHint::CreateInsertion(Loc, "typename ");
5161
5162 // Recover by synthesizing a type using the location information that we
5163 // already have.
5164 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5165 SS.getScopeRep(), II);
5166 TypeLocBuilder TLB;
5168 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5170 TL.setNameLoc(NameInfo.getLoc());
5171 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5172
5173 // Overwrite our input TemplateArgumentLoc so that we can recover
5174 // properly.
5177
5178 break;
5179 }
5180 }
5181 // fallthrough
5182 [[fallthrough]];
5183 }
5184 default: {
5185 // We allow instantiating a template with template argument packs when
5186 // building deduction guides.
5187 if (Arg.getKind() == TemplateArgument::Pack &&
5188 CodeSynthesisContexts.back().Kind ==
5190 SugaredConverted.push_back(Arg);
5191 CanonicalConverted.push_back(Arg);
5192 return false;
5193 }
5194 // We have a template type parameter but the template argument
5195 // is not a type.
5196 SourceRange SR = AL.getSourceRange();
5197 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5199
5200 return true;
5201 }
5202 }
5203
5204 if (CheckTemplateArgument(TSI))
5205 return true;
5206
5207 // Objective-C ARC:
5208 // If an explicitly-specified template argument type is a lifetime type
5209 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5210 if (getLangOpts().ObjCAutoRefCount &&
5211 ArgType->isObjCLifetimeType() &&
5212 !ArgType.getObjCLifetime()) {
5213 Qualifiers Qs;
5215 ArgType = Context.getQualifiedType(ArgType, Qs);
5216 }
5217
5218 SugaredConverted.push_back(TemplateArgument(ArgType));
5219 CanonicalConverted.push_back(
5220 TemplateArgument(Context.getCanonicalType(ArgType)));
5221 return false;
5222}
5223
5224/// Substitute template arguments into the default template argument for
5225/// the given template type parameter.
5226///
5227/// \param SemaRef the semantic analysis object for which we are performing
5228/// the substitution.
5229///
5230/// \param Template the template that we are synthesizing template arguments
5231/// for.
5232///
5233/// \param TemplateLoc the location of the template name that started the
5234/// template-id we are checking.
5235///
5236/// \param RAngleLoc the location of the right angle bracket ('>') that
5237/// terminates the template-id.
5238///
5239/// \param Param the template template parameter whose default we are
5240/// substituting into.
5241///
5242/// \param Converted the list of template arguments provided for template
5243/// parameters that precede \p Param in the template parameter list.
5244///
5245/// \param Output the resulting substituted template argument.
5246///
5247/// \returns true if an error occurred.
5249 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5250 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5251 ArrayRef<TemplateArgument> SugaredConverted,
5252 ArrayRef<TemplateArgument> CanonicalConverted,
5253 TemplateArgumentLoc &Output) {
5254 Output = Param->getDefaultArgument();
5255
5256 // If the argument type is dependent, instantiate it now based
5257 // on the previously-computed template arguments.
5258 if (Output.getArgument().isInstantiationDependent()) {
5259 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5260 SugaredConverted,
5261 SourceRange(TemplateLoc, RAngleLoc));
5262 if (Inst.isInvalid())
5263 return true;
5264
5265 // Only substitute for the innermost template argument list.
5266 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5267 /*Final=*/true);
5268 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5269 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5270
5271 bool ForLambdaCallOperator = false;
5272 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5273 ForLambdaCallOperator = Rec->isLambda();
5274 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5275 !ForLambdaCallOperator);
5276
5277 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5278 Param->getDefaultArgumentLoc(),
5279 Param->getDeclName()))
5280 return true;
5281 }
5282
5283 return false;
5284}
5285
5286/// Substitute template arguments into the default template argument for
5287/// the given non-type template parameter.
5288///
5289/// \param SemaRef the semantic analysis object for which we are performing
5290/// the substitution.
5291///
5292/// \param Template the template that we are synthesizing template arguments
5293/// for.
5294///
5295/// \param TemplateLoc the location of the template name that started the
5296/// template-id we are checking.
5297///
5298/// \param RAngleLoc the location of the right angle bracket ('>') that
5299/// terminates the template-id.
5300///
5301/// \param Param the non-type template parameter whose default we are
5302/// substituting into.
5303///
5304/// \param Converted the list of template arguments provided for template
5305/// parameters that precede \p Param in the template parameter list.
5306///
5307/// \returns the substituted template argument, or NULL if an error occurred.
5309 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5310 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5311 ArrayRef<TemplateArgument> SugaredConverted,
5312 ArrayRef<TemplateArgument> CanonicalConverted,
5313 TemplateArgumentLoc &Output) {
5314 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5315 SugaredConverted,
5316 SourceRange(TemplateLoc, RAngleLoc));
5317 if (Inst.isInvalid())
5318 return true;
5319
5320 // Only substitute for the innermost template argument list.
5321 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5322 /*Final=*/true);
5323 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5324 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5325
5326 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5327 EnterExpressionEvaluationContext ConstantEvaluated(
5329 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5330 TemplateArgLists, Output);
5331}
5332
5333/// Substitute template arguments into the default template argument for
5334/// the given template template parameter.
5335///
5336/// \param SemaRef the semantic analysis object for which we are performing
5337/// the substitution.
5338///
5339/// \param Template the template that we are synthesizing template arguments
5340/// for.
5341///
5342/// \param TemplateLoc the location of the template name that started the
5343/// template-id we are checking.
5344///
5345/// \param RAngleLoc the location of the right angle bracket ('>') that
5346/// terminates the template-id.
5347///
5348/// \param Param the template template parameter whose default we are
5349/// substituting into.
5350///
5351/// \param Converted the list of template arguments provided for template
5352/// parameters that precede \p Param in the template parameter list.
5353///
5354/// \param QualifierLoc Will be set to the nested-name-specifier (with
5355/// source-location information) that precedes the template name.
5356///
5357/// \returns the substituted template argument, or NULL if an error occurred.
5359 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5360 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5362 ArrayRef<TemplateArgument> SugaredConverted,
5363 ArrayRef<TemplateArgument> CanonicalConverted,
5364 NestedNameSpecifierLoc &QualifierLoc) {
5366 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5367 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5368 if (Inst.isInvalid())
5369 return TemplateName();
5370
5371 // Only substitute for the innermost template argument list.
5372 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5373 /*Final=*/true);
5374 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5375 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5376
5377 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5378
5379 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5380 QualifierLoc = A.getTemplateQualifierLoc();
5381 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5383 A.getTemplateNameLoc(), TemplateArgLists);
5384}
5385
5387 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5388 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5389 ArrayRef<TemplateArgument> SugaredConverted,
5390 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5391 HasDefaultArg = false;
5392
5393 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5394 if (!hasReachableDefaultArgument(TypeParm))
5395 return TemplateArgumentLoc();
5396
5397 HasDefaultArg = true;
5398 TemplateArgumentLoc Output;
5399 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5400 RAngleLoc, TypeParm, SugaredConverted,
5401 CanonicalConverted, Output))
5402 return TemplateArgumentLoc();
5403 return Output;
5404 }
5405
5406 if (NonTypeTemplateParmDecl *NonTypeParm
5407 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5408 if (!hasReachableDefaultArgument(NonTypeParm))
5409 return TemplateArgumentLoc();
5410
5411 HasDefaultArg = true;
5412 TemplateArgumentLoc Output;
5413 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5414 RAngleLoc, NonTypeParm, SugaredConverted,
5415 CanonicalConverted, Output))
5416 return TemplateArgumentLoc();
5417 return Output;
5418 }
5419
5420 TemplateTemplateParmDecl *TempTempParm
5422 if (!hasReachableDefaultArgument(TempTempParm))
5423 return TemplateArgumentLoc();
5424
5425 HasDefaultArg = true;
5426 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5427 NestedNameSpecifierLoc QualifierLoc;
5429 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5430 SugaredConverted, CanonicalConverted, QualifierLoc);
5431 if (TName.isNull())
5432 return TemplateArgumentLoc();
5433
5434 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5435 QualifierLoc, A.getTemplateNameLoc());
5436}
5437
5438/// Convert a template-argument that we parsed as a type into a template, if
5439/// possible. C++ permits injected-class-names to perform dual service as
5440/// template template arguments and as template type arguments.
5443 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5444 if (!TagLoc)
5445 return TemplateArgumentLoc();
5446
5447 // If this type was written as an injected-class-name, it can be used as a
5448 // template template argument.
5449 // If this type was written as an injected-class-name, it may have been
5450 // converted to a RecordType during instantiation. If the RecordType is
5451 // *not* wrapped in a TemplateSpecializationType and denotes a class
5452 // template specialization, it must have come from an injected-class-name.
5453
5454 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5455 if (Name.isNull())
5456 return TemplateArgumentLoc();
5457
5458 return TemplateArgumentLoc(Context, Name,
5459 /*TemplateKWLoc=*/SourceLocation(),
5460 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5461}
5462
5465 SourceLocation TemplateLoc,
5466 SourceLocation RAngleLoc,
5467 unsigned ArgumentPackIndex,
5470 // Check template type parameters.
5471 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5472 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5473 CTAI.CanonicalConverted);
5474
5475 const TemplateArgument &Arg = ArgLoc.getArgument();
5476 // Check non-type template parameters.
5477 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5478 // Do substitution on the type of the non-type template parameter
5479 // with the template arguments we've seen thus far. But if the
5480 // template has a dependent context then we cannot substitute yet.
5481 QualType NTTPType = NTTP->getType();
5482 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5483 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5484
5485 if (NTTPType->isInstantiationDependentType()) {
5486 // Do substitution on the type of the non-type template parameter.
5487 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5488 CTAI.SugaredConverted,
5489 SourceRange(TemplateLoc, RAngleLoc));
5490 if (Inst.isInvalid())
5491 return true;
5492
5494 /*Final=*/true);
5495 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5496 // If the parameter is a pack expansion, expand this slice of the pack.
5497 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5498 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5499 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5500 NTTP->getDeclName());
5501 } else {
5502 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5503 NTTP->getDeclName());
5504 }
5505
5506 // If that worked, check the non-type template parameter type
5507 // for validity.
5508 if (!NTTPType.isNull())
5509 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5510 NTTP->getLocation());
5511 if (NTTPType.isNull())
5512 return true;
5513 }
5514
5515 auto checkExpr = [&](Expr *E) -> Expr * {
5516 TemplateArgument SugaredResult, CanonicalResult;
5517 unsigned CurSFINAEErrors = NumSFINAEErrors;
5519 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5520 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5521 // If the current template argument causes an error, give up now.
5522 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5523 return nullptr;
5524 CTAI.SugaredConverted.push_back(SugaredResult);
5525 CTAI.CanonicalConverted.push_back(CanonicalResult);
5526 return Res.get();
5527 };
5528
5529 switch (Arg.getKind()) {
5531 llvm_unreachable("Should never see a NULL template argument here");
5532
5534 Expr *E = Arg.getAsExpr();
5535 Expr *R = checkExpr(E);
5536 if (!R)
5537 return true;
5538 // If the resulting expression is new, then use it in place of the
5539 // old expression in the template argument.
5540 if (R != E) {
5541 TemplateArgument TA(R, /*IsCanonical=*/false);
5542 ArgLoc = TemplateArgumentLoc(TA, R);
5543 }
5544 break;
5545 }
5546
5547 // As for the converted NTTP kinds, they still might need another
5548 // conversion, as the new corresponding parameter might be different.
5549 // Ideally, we would always perform substitution starting with sugared types
5550 // and never need these, as we would still have expressions. Since these are
5551 // needed so rarely, it's probably a better tradeoff to just convert them
5552 // back to expressions.
5557 // FIXME: StructuralValue is untested here.
5558 ExprResult R =
5560 assert(R.isUsable());
5561 if (!checkExpr(R.get()))
5562 return true;
5563 break;
5564 }
5565
5568 // We were given a template template argument. It may not be ill-formed;
5569 // see below.
5572 // We have a template argument such as \c T::template X, which we
5573 // parsed as a template template argument. However, since we now
5574 // know that we need a non-type template argument, convert this
5575 // template name into an expression.
5576
5577 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5578 ArgLoc.getTemplateNameLoc());
5579
5580 CXXScopeSpec SS;
5581 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5582 // FIXME: the template-template arg was a DependentTemplateName,
5583 // so it was provided with a template keyword. However, its source
5584 // location is not stored in the template argument structure.
5585 SourceLocation TemplateKWLoc;
5587 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5588 nullptr);
5589
5590 // If we parsed the template argument as a pack expansion, create a
5591 // pack expansion expression.
5594 if (E.isInvalid())
5595 return true;
5596 }
5597
5598 TemplateArgument SugaredResult, CanonicalResult;
5600 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5601 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5602 if (E.isInvalid())
5603 return true;
5604
5605 CTAI.SugaredConverted.push_back(SugaredResult);
5606 CTAI.CanonicalConverted.push_back(CanonicalResult);
5607 break;
5608 }
5609
5610 // We have a template argument that actually does refer to a class
5611 // template, alias template, or template template parameter, and
5612 // therefore cannot be a non-type template argument.
5613 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5614 << ArgLoc.getSourceRange();
5616
5617 return true;
5618
5620 // We have a non-type template parameter but the template
5621 // argument is a type.
5622
5623 // C++ [temp.arg]p2:
5624 // In a template-argument, an ambiguity between a type-id and
5625 // an expression is resolved to a type-id, regardless of the
5626 // form of the corresponding template-parameter.
5627 //
5628 // We warn specifically about this case, since it can be rather
5629 // confusing for users.
5630 QualType T = Arg.getAsType();
5631 SourceRange SR = ArgLoc.getSourceRange();
5632 if (T->isFunctionType())
5633 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5634 else
5635 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5637 return true;
5638 }
5639
5641 llvm_unreachable("Caller must expand template argument packs");
5642 }
5643
5644 return false;
5645 }
5646
5647
5648 // Check template template parameters.
5650
5651 TemplateParameterList *Params = TempParm->getTemplateParameters();
5652 if (TempParm->isExpandedParameterPack())
5653 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5654
5655 // Substitute into the template parameter list of the template
5656 // template parameter, since previously-supplied template arguments
5657 // may appear within the template template parameter.
5658 //
5659 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5660 {
5661 // Set up a template instantiation context.
5663 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5664 CTAI.SugaredConverted,
5665 SourceRange(TemplateLoc, RAngleLoc));
5666 if (Inst.isInvalid())
5667 return true;
5668
5669 Params = SubstTemplateParams(
5670 Params, CurContext,
5672 /*Final=*/true),
5673 /*EvaluateConstraints=*/false);
5674 if (!Params)
5675 return true;
5676 }
5677
5678 // C++1z [temp.local]p1: (DR1004)
5679 // When [the injected-class-name] is used [...] as a template-argument for
5680 // a template template-parameter [...] it refers to the class template
5681 // itself.
5682 if (Arg.getKind() == TemplateArgument::Type) {
5684 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5685 if (!ConvertedArg.getArgument().isNull())
5686 ArgLoc = ConvertedArg;
5687 }
5688
5689 switch (Arg.getKind()) {
5691 llvm_unreachable("Should never see a NULL template argument here");
5692
5695 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5696 CTAI.PartialOrdering,
5697 &CTAI.StrictPackMatch))
5698 return true;
5699
5700 CTAI.SugaredConverted.push_back(Arg);
5701 CTAI.CanonicalConverted.push_back(
5702 Context.getCanonicalTemplateArgument(Arg));
5703 break;
5704
5707 auto Kind = 0;
5708 switch (TempParm->templateParameterKind()) {
5710 Kind = 1;
5711 break;
5713 Kind = 2;
5714 break;
5715 default:
5716 break;
5717 }
5718
5719 // We have a template template parameter but the template
5720 // argument does not refer to a template.
5721 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5722 << Kind << getLangOpts().CPlusPlus11;
5723 return true;
5724 }
5725
5730 llvm_unreachable("non-type argument with template template parameter");
5731
5733 llvm_unreachable("Caller must expand template argument packs");
5734 }
5735
5736 return false;
5737}
5738
5739/// Diagnose a missing template argument.
5740template<typename TemplateParmDecl>
5742 TemplateDecl *TD,
5743 const TemplateParmDecl *D,
5745 // Dig out the most recent declaration of the template parameter; there may be
5746 // declarations of the template that are more recent than TD.
5748 ->getTemplateParameters()
5749 ->getParam(D->getIndex()));
5750
5751 // If there's a default argument that's not reachable, diagnose that we're
5752 // missing a module import.
5754 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5756 D->getDefaultArgumentLoc(), Modules,
5758 /*Recover*/true);
5759 return true;
5760 }
5761
5762 // FIXME: If there's a more recent default argument that *is* visible,
5763 // diagnose that it was declared too late.
5764
5766
5767 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5768 << /*not enough args*/0
5770 << TD;
5771 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5772 return true;
5773}
5774
5775/// Check that the given template argument list is well-formed
5776/// for specializing the given template.
5778 TemplateDecl *Template, SourceLocation TemplateLoc,
5779 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5780 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5781 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5782
5784 *ConstraintsNotSatisfied = false;
5785
5786 // Make a copy of the template arguments for processing. Only make the
5787 // changes at the end when successful in matching the arguments to the
5788 // template.
5789 TemplateArgumentListInfo NewArgs = TemplateArgs;
5790
5792
5793 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5794
5795 // C++23 [temp.arg.general]p1:
5796 // [...] The type and form of each template-argument specified in
5797 // a template-id shall match the type and form specified for the
5798 // corresponding parameter declared by the template in its
5799 // template-parameter-list.
5800 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5801 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5802 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5803 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5804 LocalInstantiationScope InstScope(*this, true);
5805 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5806 ParamEnd = Params->end(),
5807 Param = ParamBegin;
5808 Param != ParamEnd;
5809 /* increment in loop */) {
5810 if (size_t ParamIdx = Param - ParamBegin;
5811 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5812 // All written arguments should have been consumed by this point.
5813 assert(ArgIdx == NumArgs && "bad default argument deduction");
5814 if (ParamIdx == DefaultArgs.StartPos) {
5815 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5816 // Default arguments from a DeducedTemplateName are already converted.
5817 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5818 CTAI.SugaredConverted.push_back(DefArg);
5819 CTAI.CanonicalConverted.push_back(
5820 Context.getCanonicalTemplateArgument(DefArg));
5821 ++Param;
5822 }
5823 continue;
5824 }
5825 }
5826
5827 // If we have an expanded parameter pack, make sure we don't have too
5828 // many arguments.
5829 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5830 if (*Expansions == SugaredArgumentPack.size()) {
5831 // We're done with this parameter pack. Pack up its arguments and add
5832 // them to the list.
5833 CTAI.SugaredConverted.push_back(
5834 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5835 SugaredArgumentPack.clear();
5836
5837 CTAI.CanonicalConverted.push_back(
5838 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5839 CanonicalArgumentPack.clear();
5840
5841 // This argument is assigned to the next parameter.
5842 ++Param;
5843 continue;
5844 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5845 // Not enough arguments for this parameter pack.
5846 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5847 << /*not enough args*/0
5849 << Template;
5851 return true;
5852 }
5853 }
5854
5855 // Check for builtins producing template packs in this context, we do not
5856 // support them yet.
5857 if (const NonTypeTemplateParmDecl *NTTP =
5858 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5859 NTTP && NTTP->isPackExpansion()) {
5860 auto TL = NTTP->getTypeSourceInfo()
5861 ->getTypeLoc()
5864 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5865 for (const auto &UPP : Unexpanded) {
5866 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5867 if (!TST)
5868 continue;
5869 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5870 // Expanding a built-in pack in this context is not yet supported.
5871 Diag(TL.getEllipsisLoc(),
5872 diag::err_unsupported_builtin_template_pack_expansion)
5873 << TST->getTemplateName();
5874 return true;
5875 }
5876 }
5877
5878 if (ArgIdx < NumArgs) {
5879 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5880 bool NonPackParameter =
5881 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5882 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5883
5884 if (ArgIsExpansion && CTAI.MatchingTTP) {
5885 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5886 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5887 ++Param) {
5888 TemplateArgument &Arg = Args[Param - First];
5889 Arg = ArgLoc.getArgument();
5890 if (!(*Param)->isTemplateParameterPack() ||
5891 getExpandedPackSize(*Param))
5892 Arg = Arg.getPackExpansionPattern();
5893 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5894 SaveAndRestore _1(CTAI.PartialOrdering, false);
5895 SaveAndRestore _2(CTAI.MatchingTTP, true);
5896 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5897 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5899 return true;
5900 Arg = NewArgLoc.getArgument();
5901 CTAI.CanonicalConverted.back().setIsDefaulted(
5902 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5903 CTAI.CanonicalConverted,
5904 Params->getDepth()));
5905 }
5906 ArgLoc =
5908 ArgLoc.getLocInfo());
5909 } else {
5910 SaveAndRestore _1(CTAI.PartialOrdering, false);
5911 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5912 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5914 return true;
5915 CTAI.CanonicalConverted.back().setIsDefaulted(
5916 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5917 *Param, CTAI.CanonicalConverted,
5918 Params->getDepth()));
5919 if (ArgIsExpansion && NonPackParameter) {
5920 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5921 // alias template or concept, and it's not part of a parameter pack.
5922 // This can't be canonicalized, so reject it now.
5924 Diag(ArgLoc.getLocation(),
5925 diag::err_template_expansion_into_fixed_list)
5926 << (isa<ConceptDecl>(Template) ? 1 : 0)
5927 << ArgLoc.getSourceRange();
5929 return true;
5930 }
5931 }
5932 }
5933
5934 // We're now done with this argument.
5935 ++ArgIdx;
5936
5937 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
5938 // Directly convert the remaining arguments, because we don't know what
5939 // parameters they'll match up with.
5940
5941 if (!SugaredArgumentPack.empty()) {
5942 // If we were part way through filling in an expanded parameter pack,
5943 // fall back to just producing individual arguments.
5944 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
5945 SugaredArgumentPack.begin(),
5946 SugaredArgumentPack.end());
5947 SugaredArgumentPack.clear();
5948
5949 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
5950 CanonicalArgumentPack.begin(),
5951 CanonicalArgumentPack.end());
5952 CanonicalArgumentPack.clear();
5953 }
5954
5955 while (ArgIdx < NumArgs) {
5956 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5957 CTAI.SugaredConverted.push_back(Arg);
5958 CTAI.CanonicalConverted.push_back(
5959 Context.getCanonicalTemplateArgument(Arg));
5960 ++ArgIdx;
5961 }
5962
5963 return false;
5964 }
5965
5966 if ((*Param)->isTemplateParameterPack()) {
5967 // The template parameter was a template parameter pack, so take the
5968 // deduced argument and place it on the argument pack. Note that we
5969 // stay on the same template parameter so that we can deduce more
5970 // arguments.
5971 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
5972 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
5973 } else {
5974 // Move to the next template parameter.
5975 ++Param;
5976 }
5977 continue;
5978 }
5979
5980 // If we're checking a partial template argument list, we're done.
5981 if (PartialTemplateArgs) {
5982 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5983 CTAI.SugaredConverted.push_back(
5984 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5985 CTAI.CanonicalConverted.push_back(
5986 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5987 }
5988 return false;
5989 }
5990
5991 // If we have a template parameter pack with no more corresponding
5992 // arguments, just break out now and we'll fill in the argument pack below.
5993 if ((*Param)->isTemplateParameterPack()) {
5994 assert(!getExpandedPackSize(*Param) &&
5995 "Should have dealt with this already");
5996
5997 // A non-expanded parameter pack before the end of the parameter list
5998 // only occurs for an ill-formed template parameter list, unless we've
5999 // got a partial argument list for a function template, so just bail out.
6000 if (Param + 1 != ParamEnd) {
6001 assert(
6002 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6003 "Concept templates must have parameter packs at the end.");
6004 return true;
6005 }
6006
6007 CTAI.SugaredConverted.push_back(
6008 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6009 SugaredArgumentPack.clear();
6010
6011 CTAI.CanonicalConverted.push_back(
6012 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6013 CanonicalArgumentPack.clear();
6014
6015 ++Param;
6016 continue;
6017 }
6018
6019 // Check whether we have a default argument.
6020 bool HasDefaultArg;
6021
6022 // Retrieve the default template argument from the template
6023 // parameter. For each kind of template parameter, we substitute the
6024 // template arguments provided thus far and any "outer" template arguments
6025 // (when the template parameter was part of a nested template) into
6026 // the default argument.
6028 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6029 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6030
6031 if (Arg.getArgument().isNull()) {
6032 if (!HasDefaultArg) {
6033 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6034 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6035 NewArgs);
6036 if (NonTypeTemplateParmDecl *NTTP =
6037 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6038 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6039 NewArgs);
6040 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6042 NewArgs);
6043 }
6044 return true;
6045 }
6046
6047 // Introduce an instantiation record that describes where we are using
6048 // the default template argument. We're not actually instantiating a
6049 // template here, we just create this object to put a note into the
6050 // context stack.
6051 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6052 CTAI.SugaredConverted,
6053 SourceRange(TemplateLoc, RAngleLoc));
6054 if (Inst.isInvalid())
6055 return true;
6056
6057 SaveAndRestore _1(CTAI.PartialOrdering, false);
6058 SaveAndRestore _2(CTAI.MatchingTTP, false);
6059 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6060 // Check the default template argument.
6061 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6062 CTAI, CTAK_Specified))
6063 return true;
6064
6065 CTAI.SugaredConverted.back().setIsDefaulted(true);
6066 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6067
6068 // Core issue 150 (assumed resolution): if this is a template template
6069 // parameter, keep track of the default template arguments from the
6070 // template definition.
6071 if (isTemplateTemplateParameter)
6072 NewArgs.addArgument(Arg);
6073
6074 // Move to the next template parameter and argument.
6075 ++Param;
6076 ++ArgIdx;
6077 }
6078
6079 // If we're performing a partial argument substitution, allow any trailing
6080 // pack expansions; they might be empty. This can happen even if
6081 // PartialTemplateArgs is false (the list of arguments is complete but
6082 // still dependent).
6083 if (CTAI.MatchingTTP ||
6085 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6086 while (ArgIdx < NumArgs &&
6087 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6088 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6089 CTAI.SugaredConverted.push_back(Arg);
6090 CTAI.CanonicalConverted.push_back(
6091 Context.getCanonicalTemplateArgument(Arg));
6092 }
6093 }
6094
6095 // If we have any leftover arguments, then there were too many arguments.
6096 // Complain and fail.
6097 if (ArgIdx < NumArgs) {
6098 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6099 << /*too many args*/1
6101 << Template
6102 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6104 return true;
6105 }
6106
6107 // No problems found with the new argument list, propagate changes back
6108 // to caller.
6109 if (UpdateArgsWithConversions)
6110 TemplateArgs = std::move(NewArgs);
6111
6112 if (!PartialTemplateArgs) {
6113 // Setup the context/ThisScope for the case where we are needing to
6114 // re-instantiate constraints outside of normal instantiation.
6115 DeclContext *NewContext = Template->getDeclContext();
6116
6117 // If this template is in a template, make sure we extract the templated
6118 // decl.
6119 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6120 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6121 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6122
6123 Qualifiers ThisQuals;
6124 if (const auto *Method =
6125 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6126 ThisQuals = Method->getMethodQualifiers();
6127
6128 ContextRAII Context(*this, NewContext);
6129 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6130
6132 Template, NewContext, /*Final=*/false, CTAI.CanonicalConverted,
6133 /*RelativeToPrimary=*/true,
6134 /*Pattern=*/nullptr,
6135 /*ForConceptInstantiation=*/true);
6137 Template, MLTAL,
6138 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6141 return true;
6142 }
6143 }
6144
6145 return false;
6146}
6147
6148namespace {
6149 class UnnamedLocalNoLinkageFinder
6150 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6151 {
6152 Sema &S;
6153 SourceRange SR;
6154
6156
6157 public:
6158 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6159
6160 bool Visit(QualType T) {
6161 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6162 }
6163
6164#define TYPE(Class, Parent) \
6165 bool Visit##Class##Type(const Class##Type *);
6166#define ABSTRACT_TYPE(Class, Parent) \
6167 bool Visit##Class##Type(const Class##Type *) { return false; }
6168#define NON_CANONICAL_TYPE(Class, Parent) \
6169 bool Visit##Class##Type(const Class##Type *) { return false; }
6170#include "clang/AST/TypeNodes.inc"
6171
6172 bool VisitTagDecl(const TagDecl *Tag);
6173 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6174 };
6175} // end anonymous namespace
6176
6177bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6178 return false;
6179}
6180
6181bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6182 return Visit(T->getElementType());
6183}
6184
6185bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6186 return Visit(T->getPointeeType());
6187}
6188
6189bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6190 const BlockPointerType* T) {
6191 return Visit(T->getPointeeType());
6192}
6193
6194bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6195 const LValueReferenceType* T) {
6196 return Visit(T->getPointeeType());
6197}
6198
6199bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6200 const RValueReferenceType* T) {
6201 return Visit(T->getPointeeType());
6202}
6203
6204bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6205 const MemberPointerType *T) {
6206 if (Visit(T->getPointeeType()))
6207 return true;
6208 if (auto *RD = T->getMostRecentCXXRecordDecl())
6209 return VisitTagDecl(RD);
6210 return VisitNestedNameSpecifier(T->getQualifier());
6211}
6212
6213bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6214 const ConstantArrayType* T) {
6215 return Visit(T->getElementType());
6216}
6217
6218bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6219 const IncompleteArrayType* T) {
6220 return Visit(T->getElementType());
6221}
6222
6223bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6224 const VariableArrayType* T) {
6225 return Visit(T->getElementType());
6226}
6227
6228bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6229 const DependentSizedArrayType* T) {
6230 return Visit(T->getElementType());
6231}
6232
6233bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6235 return Visit(T->getElementType());
6236}
6237
6238bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6239 const DependentSizedMatrixType *T) {
6240 return Visit(T->getElementType());
6241}
6242
6243bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6245 return Visit(T->getPointeeType());
6246}
6247
6248bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6249 return Visit(T->getElementType());
6250}
6251
6252bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6253 const DependentVectorType *T) {
6254 return Visit(T->getElementType());
6255}
6256
6257bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6258 return Visit(T->getElementType());
6259}
6260
6261bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6262 const ConstantMatrixType *T) {
6263 return Visit(T->getElementType());
6264}
6265
6266bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6267 const FunctionProtoType* T) {
6268 for (const auto &A : T->param_types()) {
6269 if (Visit(A))
6270 return true;
6271 }
6272
6273 return Visit(T->getReturnType());
6274}
6275
6276bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6277 const FunctionNoProtoType* T) {
6278 return Visit(T->getReturnType());
6279}
6280
6281bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6282 const UnresolvedUsingType*) {
6283 return false;
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6287 return false;
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6291 return Visit(T->getUnmodifiedType());
6292}
6293
6294bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6295 return false;
6296}
6297
6298bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6299 const PackIndexingType *) {
6300 return false;
6301}
6302
6303bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6304 const UnaryTransformType*) {
6305 return false;
6306}
6307
6308bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6309 return Visit(T->getDeducedType());
6310}
6311
6312bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6313 const DeducedTemplateSpecializationType *T) {
6314 return Visit(T->getDeducedType());
6315}
6316
6317bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6318 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6319}
6320
6321bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6322 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6323}
6324
6325bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6326 const TemplateTypeParmType*) {
6327 return false;
6328}
6329
6330bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6331 const SubstTemplateTypeParmPackType *) {
6332 return false;
6333}
6334
6335bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6336 const SubstBuiltinTemplatePackType *) {
6337 return false;
6338}
6339
6340bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6341 const TemplateSpecializationType*) {
6342 return false;
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6346 const InjectedClassNameType* T) {
6347 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6348}
6349
6350bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6351 const DependentNameType* T) {
6352 return VisitNestedNameSpecifier(T->getQualifier());
6353}
6354
6355bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6356 const PackExpansionType* T) {
6357 return Visit(T->getPattern());
6358}
6359
6360bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6361 return false;
6362}
6363
6364bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6365 const ObjCInterfaceType *) {
6366 return false;
6367}
6368
6369bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6370 const ObjCObjectPointerType *) {
6371 return false;
6372}
6373
6374bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6375 return Visit(T->getValueType());
6376}
6377
6378bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6379 return false;
6380}
6381
6382bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6383 return false;
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6387 const ArrayParameterType *T) {
6388 return VisitConstantArrayType(T);
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6392 const DependentBitIntType *T) {
6393 return false;
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6397 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6398 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6399 ? diag::warn_cxx98_compat_template_arg_local_type
6400 : diag::ext_template_arg_local_type)
6401 << S.Context.getCanonicalTagType(Tag) << SR;
6402 return true;
6403 }
6404
6405 if (!Tag->hasNameForLinkage()) {
6406 S.Diag(SR.getBegin(),
6407 S.getLangOpts().CPlusPlus11 ?
6408 diag::warn_cxx98_compat_template_arg_unnamed_type :
6409 diag::ext_template_arg_unnamed_type) << SR;
6410 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6411 return true;
6412 }
6413
6414 return false;
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6418 NestedNameSpecifier NNS) {
6419 switch (NNS.getKind()) {
6424 return false;
6426 return Visit(QualType(NNS.getAsType(), 0));
6427 }
6428 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6429}
6430
6431bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6432 const HLSLAttributedResourceType *T) {
6433 if (T->hasContainedType() && Visit(T->getContainedType()))
6434 return true;
6435 return Visit(T->getWrappedType());
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6439 const HLSLInlineSpirvType *T) {
6440 for (auto &Operand : T->getOperands())
6441 if (Operand.isConstant() && Operand.isLiteral())
6442 if (Visit(Operand.getResultType()))
6443 return true;
6444 return false;
6445}
6446
6448 assert(ArgInfo && "invalid TypeSourceInfo");
6449 QualType Arg = ArgInfo->getType();
6450 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6451 QualType CanonArg = Context.getCanonicalType(Arg);
6452
6453 if (CanonArg->isVariablyModifiedType()) {
6454 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6455 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6456 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6457 }
6458
6459 // C++03 [temp.arg.type]p2:
6460 // A local type, a type with no linkage, an unnamed type or a type
6461 // compounded from any of these types shall not be used as a
6462 // template-argument for a template type-parameter.
6463 //
6464 // C++11 allows these, and even in C++03 we allow them as an extension with
6465 // a warning.
6466 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6467 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6468 (void)Finder.Visit(CanonArg);
6469 }
6470
6471 return false;
6472}
6473
6479
6480/// Determine whether the given template argument is a null pointer
6481/// value of the appropriate type.
6484 QualType ParamType, Expr *Arg,
6485 Decl *Entity = nullptr) {
6486 if (Arg->isValueDependent() || Arg->isTypeDependent())
6487 return NPV_NotNullPointer;
6488
6489 // dllimport'd entities aren't constant but are available inside of template
6490 // arguments.
6491 if (Entity && Entity->hasAttr<DLLImportAttr>())
6492 return NPV_NotNullPointer;
6493
6494 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6495 llvm_unreachable(
6496 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6497
6498 if (!S.getLangOpts().CPlusPlus11)
6499 return NPV_NotNullPointer;
6500
6501 // Determine whether we have a constant expression.
6503 if (ArgRV.isInvalid())
6504 return NPV_Error;
6505 Arg = ArgRV.get();
6506
6507 Expr::EvalResult EvalResult;
6509 EvalResult.Diag = &Notes;
6510 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6511 EvalResult.HasSideEffects) {
6512 SourceLocation DiagLoc = Arg->getExprLoc();
6513
6514 // If our only note is the usual "invalid subexpression" note, just point
6515 // the caret at its location rather than producing an essentially
6516 // redundant note.
6517 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6518 diag::note_invalid_subexpr_in_const_expr) {
6519 DiagLoc = Notes[0].first;
6520 Notes.clear();
6521 }
6522
6523 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6524 << Arg->getType() << Arg->getSourceRange();
6525 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6526 S.Diag(Notes[I].first, Notes[I].second);
6527
6529 return NPV_Error;
6530 }
6531
6532 // C++11 [temp.arg.nontype]p1:
6533 // - an address constant expression of type std::nullptr_t
6534 if (Arg->getType()->isNullPtrType())
6535 return NPV_NullPointer;
6536
6537 // - a constant expression that evaluates to a null pointer value (4.10); or
6538 // - a constant expression that evaluates to a null member pointer value
6539 // (4.11); or
6540 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6541 (EvalResult.Val.isMemberPointer() &&
6542 !EvalResult.Val.getMemberPointerDecl())) {
6543 // If our expression has an appropriate type, we've succeeded.
6544 bool ObjCLifetimeConversion;
6545 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6546 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6547 ObjCLifetimeConversion))
6548 return NPV_NullPointer;
6549
6550 // The types didn't match, but we know we got a null pointer; complain,
6551 // then recover as if the types were correct.
6552 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6553 << Arg->getType() << ParamType << Arg->getSourceRange();
6555 return NPV_NullPointer;
6556 }
6557
6558 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6559 // We found a pointer that isn't null, but doesn't refer to an object.
6560 // We could just return NPV_NotNullPointer, but we can print a better
6561 // message with the information we have here.
6562 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6563 << EvalResult.Val.getAsString(S.Context, ParamType);
6565 return NPV_Error;
6566 }
6567
6568 // If we don't have a null pointer value, but we do have a NULL pointer
6569 // constant, suggest a cast to the appropriate type.
6571 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6572 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6573 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6575 ")");
6577 return NPV_NullPointer;
6578 }
6579
6580 // FIXME: If we ever want to support general, address-constant expressions
6581 // as non-type template arguments, we should return the ExprResult here to
6582 // be interpreted by the caller.
6583 return NPV_NotNullPointer;
6584}
6585
6586/// Checks whether the given template argument is compatible with its
6587/// template parameter.
6588static bool
6590 QualType ParamType, Expr *ArgIn,
6591 Expr *Arg, QualType ArgType) {
6592 bool ObjCLifetimeConversion;
6593 if (ParamType->isPointerType() &&
6594 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6595 S.IsQualificationConversion(ArgType, ParamType, false,
6596 ObjCLifetimeConversion)) {
6597 // For pointer-to-object types, qualification conversions are
6598 // permitted.
6599 } else {
6600 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6601 if (!ParamRef->getPointeeType()->isFunctionType()) {
6602 // C++ [temp.arg.nontype]p5b3:
6603 // For a non-type template-parameter of type reference to
6604 // object, no conversions apply. The type referred to by the
6605 // reference may be more cv-qualified than the (otherwise
6606 // identical) type of the template- argument. The
6607 // template-parameter is bound directly to the
6608 // template-argument, which shall be an lvalue.
6609
6610 // FIXME: Other qualifiers?
6611 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6612 unsigned ArgQuals = ArgType.getCVRQualifiers();
6613
6614 if ((ParamQuals | ArgQuals) != ParamQuals) {
6615 S.Diag(Arg->getBeginLoc(),
6616 diag::err_template_arg_ref_bind_ignores_quals)
6617 << ParamType << Arg->getType() << Arg->getSourceRange();
6619 return true;
6620 }
6621 }
6622 }
6623
6624 // At this point, the template argument refers to an object or
6625 // function with external linkage. We now need to check whether the
6626 // argument and parameter types are compatible.
6627 if (!S.Context.hasSameUnqualifiedType(ArgType,
6628 ParamType.getNonReferenceType())) {
6629 // We can't perform this conversion or binding.
6630 if (ParamType->isReferenceType())
6631 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6632 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6633 else
6634 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6635 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6637 return true;
6638 }
6639 }
6640
6641 return false;
6642}
6643
6644/// Checks whether the given template argument is the address
6645/// of an object or function according to C++ [temp.arg.nontype]p1.
6647 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6648 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6649 bool Invalid = false;
6650 Expr *Arg = ArgIn;
6651 QualType ArgType = Arg->getType();
6652
6653 bool AddressTaken = false;
6654 SourceLocation AddrOpLoc;
6655 if (S.getLangOpts().MicrosoftExt) {
6656 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6657 // dereference and address-of operators.
6658 Arg = Arg->IgnoreParenCasts();
6659
6660 bool ExtWarnMSTemplateArg = false;
6661 UnaryOperatorKind FirstOpKind;
6662 SourceLocation FirstOpLoc;
6663 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6664 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6665 if (UnOpKind == UO_Deref)
6666 ExtWarnMSTemplateArg = true;
6667 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6668 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6669 if (!AddrOpLoc.isValid()) {
6670 FirstOpKind = UnOpKind;
6671 FirstOpLoc = UnOp->getOperatorLoc();
6672 }
6673 } else
6674 break;
6675 }
6676 if (FirstOpLoc.isValid()) {
6677 if (ExtWarnMSTemplateArg)
6678 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6679 << ArgIn->getSourceRange();
6680
6681 if (FirstOpKind == UO_AddrOf)
6682 AddressTaken = true;
6683 else if (Arg->getType()->isPointerType()) {
6684 // We cannot let pointers get dereferenced here, that is obviously not a
6685 // constant expression.
6686 assert(FirstOpKind == UO_Deref);
6687 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6688 << Arg->getSourceRange();
6689 }
6690 }
6691 } else {
6692 // See through any implicit casts we added to fix the type.
6693 Arg = Arg->IgnoreImpCasts();
6694
6695 // C++ [temp.arg.nontype]p1:
6696 //
6697 // A template-argument for a non-type, non-template
6698 // template-parameter shall be one of: [...]
6699 //
6700 // -- the address of an object or function with external
6701 // linkage, including function templates and function
6702 // template-ids but excluding non-static class members,
6703 // expressed as & id-expression where the & is optional if
6704 // the name refers to a function or array, or if the
6705 // corresponding template-parameter is a reference; or
6706
6707 // In C++98/03 mode, give an extension warning on any extra parentheses.
6708 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6709 bool ExtraParens = false;
6710 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6711 if (!Invalid && !ExtraParens) {
6712 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6713 << Arg->getSourceRange();
6714 ExtraParens = true;
6715 }
6716
6717 Arg = Parens->getSubExpr();
6718 }
6719
6720 while (SubstNonTypeTemplateParmExpr *subst =
6721 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6722 Arg = subst->getReplacement()->IgnoreImpCasts();
6723
6724 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6725 if (UnOp->getOpcode() == UO_AddrOf) {
6726 Arg = UnOp->getSubExpr();
6727 AddressTaken = true;
6728 AddrOpLoc = UnOp->getOperatorLoc();
6729 }
6730 }
6731
6732 while (SubstNonTypeTemplateParmExpr *subst =
6733 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6734 Arg = subst->getReplacement()->IgnoreImpCasts();
6735 }
6736
6737 ValueDecl *Entity = nullptr;
6738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6739 Entity = DRE->getDecl();
6740 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6741 Entity = CUE->getGuidDecl();
6742
6743 // If our parameter has pointer type, check for a null template value.
6744 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6745 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6746 Entity)) {
6747 case NPV_NullPointer:
6748 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6749 SugaredConverted = TemplateArgument(ParamType,
6750 /*isNullPtr=*/true);
6751 CanonicalConverted =
6753 /*isNullPtr=*/true);
6754 return false;
6755
6756 case NPV_Error:
6757 return true;
6758
6759 case NPV_NotNullPointer:
6760 break;
6761 }
6762 }
6763
6764 // Stop checking the precise nature of the argument if it is value dependent,
6765 // it should be checked when instantiated.
6766 if (Arg->isValueDependent()) {
6767 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6768 CanonicalConverted =
6769 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6770 return false;
6771 }
6772
6773 if (!Entity) {
6774 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6775 << Arg->getSourceRange();
6777 return true;
6778 }
6779
6780 // Cannot refer to non-static data members
6781 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6782 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6783 << Entity << Arg->getSourceRange();
6785 return true;
6786 }
6787
6788 // Cannot refer to non-static member functions
6789 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6790 if (!Method->isStatic()) {
6791 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6792 << Method << Arg->getSourceRange();
6794 return true;
6795 }
6796 }
6797
6798 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6799 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6800 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6801
6802 // A non-type template argument must refer to an object or function.
6803 if (!Func && !Var && !Guid) {
6804 // We found something, but we don't know specifically what it is.
6805 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6806 << Arg->getSourceRange();
6807 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6808 return true;
6809 }
6810
6811 // Address / reference template args must have external linkage in C++98.
6812 if (Entity->getFormalLinkage() == Linkage::Internal) {
6813 S.Diag(Arg->getBeginLoc(),
6814 S.getLangOpts().CPlusPlus11
6815 ? diag::warn_cxx98_compat_template_arg_object_internal
6816 : diag::ext_template_arg_object_internal)
6817 << !Func << Entity << Arg->getSourceRange();
6818 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6819 << !Func;
6820 } else if (!Entity->hasLinkage()) {
6821 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6822 << !Func << Entity << Arg->getSourceRange();
6823 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6824 << !Func;
6825 return true;
6826 }
6827
6828 if (Var) {
6829 // A value of reference type is not an object.
6830 if (Var->getType()->isReferenceType()) {
6831 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6832 << Var->getType() << Arg->getSourceRange();
6834 return true;
6835 }
6836
6837 // A template argument must have static storage duration.
6838 if (Var->getTLSKind()) {
6839 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6840 << Arg->getSourceRange();
6841 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6842 return true;
6843 }
6844 }
6845
6846 if (AddressTaken && ParamType->isReferenceType()) {
6847 // If we originally had an address-of operator, but the
6848 // parameter has reference type, complain and (if things look
6849 // like they will work) drop the address-of operator.
6850 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6851 ParamType.getNonReferenceType())) {
6852 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6853 << ParamType;
6855 return true;
6856 }
6857
6858 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6859 << ParamType
6860 << FixItHint::CreateRemoval(AddrOpLoc);
6862
6863 ArgType = Entity->getType();
6864 }
6865
6866 // If the template parameter has pointer type, either we must have taken the
6867 // address or the argument must decay to a pointer.
6868 if (!AddressTaken && ParamType->isPointerType()) {
6869 if (Func) {
6870 // Function-to-pointer decay.
6871 ArgType = S.Context.getPointerType(Func->getType());
6872 } else if (Entity->getType()->isArrayType()) {
6873 // Array-to-pointer decay.
6874 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6875 } else {
6876 // If the template parameter has pointer type but the address of
6877 // this object was not taken, complain and (possibly) recover by
6878 // taking the address of the entity.
6879 ArgType = S.Context.getPointerType(Entity->getType());
6880 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6881 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6882 << ParamType;
6884 return true;
6885 }
6886
6887 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6888 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6889
6891 }
6892 }
6893
6894 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6895 Arg, ArgType))
6896 return true;
6897
6898 // Create the template argument.
6899 SugaredConverted = TemplateArgument(Entity, ParamType);
6900 CanonicalConverted =
6902 S.Context.getCanonicalType(ParamType));
6903 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6904 return false;
6905}
6906
6907/// Checks whether the given template argument is a pointer to
6908/// member constant according to C++ [temp.arg.nontype]p1.
6910 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6911 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6912 bool Invalid = false;
6913
6914 Expr *Arg = ResultArg;
6915 bool ObjCLifetimeConversion;
6916
6917 // C++ [temp.arg.nontype]p1:
6918 //
6919 // A template-argument for a non-type, non-template
6920 // template-parameter shall be one of: [...]
6921 //
6922 // -- a pointer to member expressed as described in 5.3.1.
6923 DeclRefExpr *DRE = nullptr;
6924
6925 // In C++98/03 mode, give an extension warning on any extra parentheses.
6926 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6927 bool ExtraParens = false;
6928 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6929 if (!Invalid && !ExtraParens) {
6930 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6931 << Arg->getSourceRange();
6932 ExtraParens = true;
6933 }
6934
6935 Arg = Parens->getSubExpr();
6936 }
6937
6938 while (SubstNonTypeTemplateParmExpr *subst =
6939 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6940 Arg = subst->getReplacement()->IgnoreImpCasts();
6941
6942 // A pointer-to-member constant written &Class::member.
6943 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6944 if (UnOp->getOpcode() == UO_AddrOf) {
6945 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6946 if (DRE && !DRE->getQualifier())
6947 DRE = nullptr;
6948 }
6949 }
6950 // A constant of pointer-to-member type.
6951 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6952 ValueDecl *VD = DRE->getDecl();
6953 if (VD->getType()->isMemberPointerType()) {
6955 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6956 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6957 CanonicalConverted =
6958 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6959 } else {
6960 SugaredConverted = TemplateArgument(VD, ParamType);
6961 CanonicalConverted =
6963 S.Context.getCanonicalType(ParamType));
6964 }
6965 return Invalid;
6966 }
6967 }
6968
6969 DRE = nullptr;
6970 }
6971
6972 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6973
6974 // Check for a null pointer value.
6975 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6976 Entity)) {
6977 case NPV_Error:
6978 return true;
6979 case NPV_NullPointer:
6980 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6981 SugaredConverted = TemplateArgument(ParamType,
6982 /*isNullPtr*/ true);
6983 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6984 /*isNullPtr*/ true);
6985 return false;
6986 case NPV_NotNullPointer:
6987 break;
6988 }
6989
6990 if (S.IsQualificationConversion(ResultArg->getType(),
6991 ParamType.getNonReferenceType(), false,
6992 ObjCLifetimeConversion)) {
6993 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6994 ResultArg->getValueKind())
6995 .get();
6996 } else if (!S.Context.hasSameUnqualifiedType(
6997 ResultArg->getType(), ParamType.getNonReferenceType())) {
6998 // We can't perform this conversion.
6999 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7000 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7002 return true;
7003 }
7004
7005 if (!DRE)
7006 return S.Diag(Arg->getBeginLoc(),
7007 diag::err_template_arg_not_pointer_to_member_form)
7008 << Arg->getSourceRange();
7009
7010 if (isa<FieldDecl>(DRE->getDecl()) ||
7012 isa<CXXMethodDecl>(DRE->getDecl())) {
7013 assert((isa<FieldDecl>(DRE->getDecl()) ||
7016 ->isImplicitObjectMemberFunction()) &&
7017 "Only non-static member pointers can make it here");
7018
7019 // Okay: this is the address of a non-static member, and therefore
7020 // a member pointer constant.
7021 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7022 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7023 CanonicalConverted =
7024 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7025 } else {
7026 ValueDecl *D = DRE->getDecl();
7027 SugaredConverted = TemplateArgument(D, ParamType);
7028 CanonicalConverted =
7030 S.Context.getCanonicalType(ParamType));
7031 }
7032 return Invalid;
7033 }
7034
7035 // We found something else, but we don't know specifically what it is.
7036 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7037 << Arg->getSourceRange();
7038 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7039 return true;
7040}
7041
7042/// Check a template argument against its corresponding
7043/// non-type template parameter.
7044///
7045/// This routine implements the semantics of C++ [temp.arg.nontype].
7046/// If an error occurred, it returns ExprError(); otherwise, it
7047/// returns the converted template argument. \p ParamType is the
7048/// type of the non-type template parameter after it has been instantiated.
7050 Expr *Arg,
7051 TemplateArgument &SugaredConverted,
7052 TemplateArgument &CanonicalConverted,
7053 bool StrictCheck,
7055 SourceLocation StartLoc = Arg->getBeginLoc();
7056 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7057 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7058 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7059 DeductionArg = NewDeductionArg;
7060 if (ArgPE) {
7061 // Recreate a pack expansion if we unwrapped one.
7062 Arg = new (Context) PackExpansionExpr(
7063 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7064 } else {
7065 Arg = DeductionArg;
7066 }
7067 };
7068
7069 // If the parameter type somehow involves auto, deduce the type now.
7070 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7071 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7072 // During template argument deduction, we allow 'decltype(auto)' to
7073 // match an arbitrary dependent argument.
7074 // FIXME: The language rules don't say what happens in this case.
7075 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7076 // expression is merely instantiation-dependent; is this enough?
7077 if (DeductionArg->isTypeDependent()) {
7078 auto *AT = dyn_cast<AutoType>(DeducedT);
7079 if (AT && AT->isDecltypeAuto()) {
7080 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7081 CanonicalConverted = TemplateArgument(
7082 Context.getCanonicalTemplateArgument(SugaredConverted));
7083 return Arg;
7084 }
7085 }
7086
7087 // When checking a deduced template argument, deduce from its type even if
7088 // the type is dependent, in order to check the types of non-type template
7089 // arguments line up properly in partial ordering.
7090 TypeSourceInfo *TSI =
7091 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7093 InitializedEntity Entity =
7096 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7097 Expr *Inits[1] = {DeductionArg};
7098 ParamType =
7099 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7100 if (ParamType.isNull())
7101 return ExprError();
7102 } else {
7103 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7104 Param->getTemplateDepth() + 1);
7105 ParamType = QualType();
7107 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7108 /*DependentDeduction=*/true,
7109 // We do not check constraints right now because the
7110 // immediately-declared constraint of the auto type is
7111 // also an associated constraint, and will be checked
7112 // along with the other associated constraints after
7113 // checking the template argument list.
7114 /*IgnoreConstraints=*/true);
7116 return ExprError();
7118 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7119 Diag(Arg->getExprLoc(),
7120 diag::err_non_type_template_parm_type_deduction_failure)
7121 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7122 << Arg->getSourceRange();
7123 }
7125 return ExprError();
7126 }
7127 }
7128 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7129 // an error. The error message normally references the parameter
7130 // declaration, but here we'll pass the argument location because that's
7131 // where the parameter type is deduced.
7132 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7133 if (ParamType.isNull()) {
7135 return ExprError();
7136 }
7137 }
7138
7139 // We should have already dropped all cv-qualifiers by now.
7140 assert(!ParamType.hasQualifiers() &&
7141 "non-type template parameter type cannot be qualified");
7142
7143 // If either the parameter has a dependent type or the argument is
7144 // type-dependent, there's nothing we can check now.
7145 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7146 // Force the argument to the type of the parameter to maintain invariants.
7148 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7149 ParamType->isLValueReferenceType() ? VK_LValue
7150 : ParamType->isRValueReferenceType() ? VK_XValue
7151 : VK_PRValue);
7152 if (E.isInvalid())
7153 return ExprError();
7154 setDeductionArg(E.get());
7155 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7156 CanonicalConverted = TemplateArgument(
7157 Context.getCanonicalTemplateArgument(SugaredConverted));
7158 return Arg;
7159 }
7160
7161 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7162 if (CTAK == CTAK_Deduced && !StrictCheck &&
7163 (ParamType->isReferenceType()
7164 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7165 DeductionArg->getType())
7166 : !Context.hasSameUnqualifiedType(ParamType,
7167 DeductionArg->getType()))) {
7168 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7169 // we should actually be checking the type of the template argument in P,
7170 // not the type of the template argument deduced from A, against the
7171 // template parameter type.
7172 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7173 << Arg->getType() << ParamType.getUnqualifiedType();
7175 return ExprError();
7176 }
7177
7178 // If the argument is a pack expansion, we don't know how many times it would
7179 // expand. If we continue checking the argument, this will make the template
7180 // definition ill-formed if it would be ill-formed for any number of
7181 // expansions during instantiation time. When partial ordering or matching
7182 // template template parameters, this is exactly what we want. Otherwise, the
7183 // normal template rules apply: we accept the template if it would be valid
7184 // for any number of expansions (i.e. none).
7185 if (ArgPE && !StrictCheck) {
7186 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7187 CanonicalConverted = TemplateArgument(
7188 Context.getCanonicalTemplateArgument(SugaredConverted));
7189 return Arg;
7190 }
7191
7192 // Avoid making a copy when initializing a template parameter of class type
7193 // from a template parameter object of the same type. This is going beyond
7194 // the standard, but is required for soundness: in
7195 // template<A a> struct X { X *p; X<a> *q; };
7196 // ... we need p and q to have the same type.
7197 //
7198 // Similarly, don't inject a call to a copy constructor when initializing
7199 // from a template parameter of the same type.
7200 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7201 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7202 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7203 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7204 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7205
7206 SugaredConverted = TemplateArgument(TPO, ParamType);
7207 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7208 ParamType.getCanonicalType());
7209 return Arg;
7210 }
7212 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7213 CanonicalConverted =
7214 Context.getCanonicalTemplateArgument(SugaredConverted);
7215 return Arg;
7216 }
7217 }
7218
7219 // The initialization of the parameter from the argument is
7220 // a constant-evaluated context.
7223
7224 bool IsConvertedConstantExpression = true;
7225 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7227 StartLoc, /*DirectInit=*/false, DeductionArg);
7228 Expr *Inits[1] = {DeductionArg};
7229 InitializedEntity Entity =
7231 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7232 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7233 if (Result.isInvalid() || !Result.get())
7234 return ExprError();
7236 if (Result.isInvalid() || !Result.get())
7237 return ExprError();
7238 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7239 /*DiscardedValue=*/false,
7240 /*IsConstexpr=*/true,
7241 /*IsTemplateArgument=*/true)
7242 .get());
7243 IsConvertedConstantExpression = false;
7244 }
7245
7246 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7247 // C++17 [temp.arg.nontype]p1:
7248 // A template-argument for a non-type template parameter shall be
7249 // a converted constant expression of the type of the template-parameter.
7250 APValue Value;
7251 ExprResult ArgResult;
7252 if (IsConvertedConstantExpression) {
7254 DeductionArg, ParamType,
7255 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7256 assert(!ArgResult.isUnset());
7257 if (ArgResult.isInvalid()) {
7259 return ExprError();
7260 }
7261 } else {
7262 ArgResult = DeductionArg;
7263 }
7264
7265 // For a value-dependent argument, CheckConvertedConstantExpression is
7266 // permitted (and expected) to be unable to determine a value.
7267 if (ArgResult.get()->isValueDependent()) {
7268 setDeductionArg(ArgResult.get());
7269 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7270 CanonicalConverted =
7271 Context.getCanonicalTemplateArgument(SugaredConverted);
7272 return Arg;
7273 }
7274
7275 APValue PreNarrowingValue;
7277 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7278 false, PreNarrowingValue);
7279 if (ArgResult.isInvalid())
7280 return ExprError();
7281 setDeductionArg(ArgResult.get());
7282
7283 if (Value.isLValue()) {
7284 APValue::LValueBase Base = Value.getLValueBase();
7285 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7286 // For a non-type template-parameter of pointer or reference type,
7287 // the value of the constant expression shall not refer to
7288 assert(ParamType->isPointerOrReferenceType() ||
7289 ParamType->isNullPtrType());
7290 // -- a temporary object
7291 // -- a string literal
7292 // -- the result of a typeid expression, or
7293 // -- a predefined __func__ variable
7294 if (Base &&
7295 (!VD ||
7297 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7298 << Arg->getSourceRange();
7299 return ExprError();
7300 }
7301
7302 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7303 VD->getType()->isArrayType() &&
7304 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7305 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7306 if (ArgPE) {
7307 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7308 CanonicalConverted =
7309 Context.getCanonicalTemplateArgument(SugaredConverted);
7310 } else {
7311 SugaredConverted = TemplateArgument(VD, ParamType);
7312 CanonicalConverted =
7314 ParamType.getCanonicalType());
7315 }
7316 return Arg;
7317 }
7318
7319 // -- a subobject [until C++20]
7320 if (!getLangOpts().CPlusPlus20) {
7321 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7322 Value.isLValueOnePastTheEnd()) {
7323 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7324 << Value.getAsString(Context, ParamType);
7325 return ExprError();
7326 }
7327 assert((VD || !ParamType->isReferenceType()) &&
7328 "null reference should not be a constant expression");
7329 assert((!VD || !ParamType->isNullPtrType()) &&
7330 "non-null value of type nullptr_t?");
7331 }
7332 }
7333
7334 if (Value.isAddrLabelDiff())
7335 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7336
7337 if (ArgPE) {
7338 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7339 CanonicalConverted =
7340 Context.getCanonicalTemplateArgument(SugaredConverted);
7341 } else {
7342 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7343 CanonicalConverted =
7345 }
7346 return Arg;
7347 }
7348
7349 // These should have all been handled above using the C++17 rules.
7350 assert(!ArgPE && !StrictCheck);
7351
7352 // C++ [temp.arg.nontype]p5:
7353 // The following conversions are performed on each expression used
7354 // as a non-type template-argument. If a non-type
7355 // template-argument cannot be converted to the type of the
7356 // corresponding template-parameter then the program is
7357 // ill-formed.
7358 if (ParamType->isIntegralOrEnumerationType()) {
7359 // C++11:
7360 // -- for a non-type template-parameter of integral or
7361 // enumeration type, conversions permitted in a converted
7362 // constant expression are applied.
7363 //
7364 // C++98:
7365 // -- for a non-type template-parameter of integral or
7366 // enumeration type, integral promotions (4.5) and integral
7367 // conversions (4.7) are applied.
7368
7369 if (getLangOpts().CPlusPlus11) {
7370 // C++ [temp.arg.nontype]p1:
7371 // A template-argument for a non-type, non-template template-parameter
7372 // shall be one of:
7373 //
7374 // -- for a non-type template-parameter of integral or enumeration
7375 // type, a converted constant expression of the type of the
7376 // template-parameter; or
7377 llvm::APSInt Value;
7379 Arg, ParamType, Value, CCEKind::TemplateArg);
7380 if (ArgResult.isInvalid())
7381 return ExprError();
7382 Arg = ArgResult.get();
7383
7384 // We can't check arbitrary value-dependent arguments.
7385 if (Arg->isValueDependent()) {
7386 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7387 CanonicalConverted =
7388 Context.getCanonicalTemplateArgument(SugaredConverted);
7389 return Arg;
7390 }
7391
7392 // Widen the argument value to sizeof(parameter type). This is almost
7393 // always a no-op, except when the parameter type is bool. In
7394 // that case, this may extend the argument from 1 bit to 8 bits.
7395 QualType IntegerType = ParamType;
7396 if (const auto *ED = IntegerType->getAsEnumDecl())
7397 IntegerType = ED->getIntegerType();
7398 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7399 ? Context.getIntWidth(IntegerType)
7400 : Context.getTypeSize(IntegerType));
7401
7402 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7403 CanonicalConverted =
7404 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7405 return Arg;
7406 }
7407
7408 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7409 if (ArgResult.isInvalid())
7410 return ExprError();
7411 Arg = ArgResult.get();
7412
7413 QualType ArgType = Arg->getType();
7414
7415 // C++ [temp.arg.nontype]p1:
7416 // A template-argument for a non-type, non-template
7417 // template-parameter shall be one of:
7418 //
7419 // -- an integral constant-expression of integral or enumeration
7420 // type; or
7421 // -- the name of a non-type template-parameter; or
7422 llvm::APSInt Value;
7423 if (!ArgType->isIntegralOrEnumerationType()) {
7424 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7425 << ArgType << Arg->getSourceRange();
7427 return ExprError();
7428 }
7429 if (!Arg->isValueDependent()) {
7430 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7431 QualType T;
7432
7433 public:
7434 TmplArgICEDiagnoser(QualType T) : T(T) { }
7435
7436 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7437 SourceLocation Loc) override {
7438 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7439 }
7440 } Diagnoser(ArgType);
7441
7442 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7443 if (!Arg)
7444 return ExprError();
7445 }
7446
7447 // From here on out, all we care about is the unqualified form
7448 // of the argument type.
7449 ArgType = ArgType.getUnqualifiedType();
7450
7451 // Try to convert the argument to the parameter's type.
7452 if (Context.hasSameType(ParamType, ArgType)) {
7453 // Okay: no conversion necessary
7454 } else if (ParamType->isBooleanType()) {
7455 // This is an integral-to-boolean conversion.
7456 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7457 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7458 !ParamType->isEnumeralType()) {
7459 // This is an integral promotion or conversion.
7460 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7461 } else {
7462 // We can't perform this conversion.
7463 Diag(StartLoc, diag::err_template_arg_not_convertible)
7464 << Arg->getType() << ParamType << Arg->getSourceRange();
7466 return ExprError();
7467 }
7468
7469 // Add the value of this argument to the list of converted
7470 // arguments. We use the bitwidth and signedness of the template
7471 // parameter.
7472 if (Arg->isValueDependent()) {
7473 // The argument is value-dependent. Create a new
7474 // TemplateArgument with the converted expression.
7475 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7476 CanonicalConverted =
7477 Context.getCanonicalTemplateArgument(SugaredConverted);
7478 return Arg;
7479 }
7480
7481 QualType IntegerType = ParamType;
7482 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7483 IntegerType = ED->getIntegerType();
7484 }
7485
7486 if (ParamType->isBooleanType()) {
7487 // Value must be zero or one.
7488 Value = Value != 0;
7489 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7490 if (Value.getBitWidth() != AllowedBits)
7491 Value = Value.extOrTrunc(AllowedBits);
7492 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7493 } else {
7494 llvm::APSInt OldValue = Value;
7495
7496 // Coerce the template argument's value to the value it will have
7497 // based on the template parameter's type.
7498 unsigned AllowedBits = IntegerType->isBitIntType()
7499 ? Context.getIntWidth(IntegerType)
7500 : Context.getTypeSize(IntegerType);
7501 if (Value.getBitWidth() != AllowedBits)
7502 Value = Value.extOrTrunc(AllowedBits);
7503 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7504
7505 // Complain if an unsigned parameter received a negative value.
7506 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7507 (OldValue.isSigned() && OldValue.isNegative())) {
7508 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7509 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7510 << Arg->getSourceRange();
7512 }
7513
7514 // Complain if we overflowed the template parameter's type.
7515 unsigned RequiredBits;
7516 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7517 RequiredBits = OldValue.getActiveBits();
7518 else if (OldValue.isUnsigned())
7519 RequiredBits = OldValue.getActiveBits() + 1;
7520 else
7521 RequiredBits = OldValue.getSignificantBits();
7522 if (RequiredBits > AllowedBits) {
7523 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7524 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7525 << Arg->getSourceRange();
7527 }
7528 }
7529
7530 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7531 SugaredConverted = TemplateArgument(Context, Value, T);
7532 CanonicalConverted =
7533 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7534 return Arg;
7535 }
7536
7537 QualType ArgType = Arg->getType();
7538 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7539
7540 // Handle pointer-to-function, reference-to-function, and
7541 // pointer-to-member-function all in (roughly) the same way.
7542 if (// -- For a non-type template-parameter of type pointer to
7543 // function, only the function-to-pointer conversion (4.3) is
7544 // applied. If the template-argument represents a set of
7545 // overloaded functions (or a pointer to such), the matching
7546 // function is selected from the set (13.4).
7547 (ParamType->isPointerType() &&
7548 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7549 // -- For a non-type template-parameter of type reference to
7550 // function, no conversions apply. If the template-argument
7551 // represents a set of overloaded functions, the matching
7552 // function is selected from the set (13.4).
7553 (ParamType->isReferenceType() &&
7554 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7555 // -- For a non-type template-parameter of type pointer to
7556 // member function, no conversions apply. If the
7557 // template-argument represents a set of overloaded member
7558 // functions, the matching member function is selected from
7559 // the set (13.4).
7560 (ParamType->isMemberPointerType() &&
7561 ParamType->castAs<MemberPointerType>()->getPointeeType()
7562 ->isFunctionType())) {
7563
7564 if (Arg->getType() == Context.OverloadTy) {
7565 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7566 true,
7567 FoundResult)) {
7568 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7569 return ExprError();
7570
7571 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7572 if (Res.isInvalid())
7573 return ExprError();
7574 Arg = Res.get();
7575 ArgType = Arg->getType();
7576 } else
7577 return ExprError();
7578 }
7579
7580 if (!ParamType->isMemberPointerType()) {
7582 *this, Param, ParamType, Arg, SugaredConverted,
7583 CanonicalConverted))
7584 return ExprError();
7585 return Arg;
7586 }
7587
7589 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7590 return ExprError();
7591 return Arg;
7592 }
7593
7594 if (ParamType->isPointerType()) {
7595 // -- for a non-type template-parameter of type pointer to
7596 // object, qualification conversions (4.4) and the
7597 // array-to-pointer conversion (4.2) are applied.
7598 // C++0x also allows a value of std::nullptr_t.
7599 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7600 "Only object pointers allowed here");
7601
7603 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7604 return ExprError();
7605 return Arg;
7606 }
7607
7608 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7609 // -- For a non-type template-parameter of type reference to
7610 // object, no conversions apply. The type referred to by the
7611 // reference may be more cv-qualified than the (otherwise
7612 // identical) type of the template-argument. The
7613 // template-parameter is bound directly to the
7614 // template-argument, which must be an lvalue.
7615 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7616 "Only object references allowed here");
7617
7618 if (Arg->getType() == Context.OverloadTy) {
7620 ParamRefType->getPointeeType(),
7621 true,
7622 FoundResult)) {
7623 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7624 return ExprError();
7625 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7626 if (Res.isInvalid())
7627 return ExprError();
7628 Arg = Res.get();
7629 ArgType = Arg->getType();
7630 } else
7631 return ExprError();
7632 }
7633
7635 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7636 return ExprError();
7637 return Arg;
7638 }
7639
7640 // Deal with parameters of type std::nullptr_t.
7641 if (ParamType->isNullPtrType()) {
7642 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7643 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7644 CanonicalConverted =
7645 Context.getCanonicalTemplateArgument(SugaredConverted);
7646 return Arg;
7647 }
7648
7649 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7650 case NPV_NotNullPointer:
7651 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7652 << Arg->getType() << ParamType;
7654 return ExprError();
7655
7656 case NPV_Error:
7657 return ExprError();
7658
7659 case NPV_NullPointer:
7660 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7661 SugaredConverted = TemplateArgument(ParamType,
7662 /*isNullPtr=*/true);
7663 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7664 /*isNullPtr=*/true);
7665 return Arg;
7666 }
7667 }
7668
7669 // -- For a non-type template-parameter of type pointer to data
7670 // member, qualification conversions (4.4) are applied.
7671 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7672
7674 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7675 return ExprError();
7676 return Arg;
7677}
7678
7682
7685 const TemplateArgumentLoc &Arg) {
7686 // C++0x [temp.arg.template]p1:
7687 // A template-argument for a template template-parameter shall be
7688 // the name of a class template or an alias template, expressed as an
7689 // id-expression. When the template-argument names a class template, only
7690 // primary class templates are considered when matching the
7691 // template template argument with the corresponding parameter;
7692 // partial specializations are not considered even if their
7693 // parameter lists match that of the template template parameter.
7694 //
7695
7697 unsigned DiagFoundKind = 0;
7698
7699 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7700 switch (TTP->templateParameterKind()) {
7702 DiagFoundKind = 3;
7703 break;
7705 DiagFoundKind = 2;
7706 break;
7707 default:
7708 DiagFoundKind = 1;
7709 break;
7710 }
7711 Kind = TTP->templateParameterKind();
7712 } else if (isa<ConceptDecl>(Template)) {
7714 DiagFoundKind = 3;
7715 } else if (isa<FunctionTemplateDecl>(Template)) {
7717 DiagFoundKind = 0;
7718 } else if (isa<VarTemplateDecl>(Template)) {
7720 DiagFoundKind = 2;
7721 } else if (isa<ClassTemplateDecl>(Template) ||
7725 DiagFoundKind = 1;
7726 } else {
7727 assert(false && "Unexpected Decl");
7728 }
7729
7730 if (Kind == Param->templateParameterKind()) {
7731 return true;
7732 }
7733
7734 unsigned DiagKind = 0;
7735 switch (Param->templateParameterKind()) {
7737 DiagKind = 2;
7738 break;
7740 DiagKind = 1;
7741 break;
7742 default:
7743 DiagKind = 0;
7744 break;
7745 }
7746 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7747 << DiagKind;
7748 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7749 << DiagFoundKind << Template;
7750 return false;
7751}
7752
7753/// Check a template argument against its corresponding
7754/// template template parameter.
7755///
7756/// This routine implements the semantics of C++ [temp.arg.template].
7757/// It returns true if an error occurred, and false otherwise.
7759 TemplateParameterList *Params,
7761 bool PartialOrdering,
7762 bool *StrictPackMatch) {
7764 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7765 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7766 if (!Template) {
7767 // FIXME: Handle AssumedTemplateNames
7768 // Any dependent template name is fine.
7769 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7770 return false;
7771 }
7772
7773 if (Template->isInvalidDecl())
7774 return true;
7775
7777 return true;
7778 }
7779
7780 // C++1z [temp.arg.template]p3: (DR 150)
7781 // A template-argument matches a template template-parameter P when P
7782 // is at least as specialized as the template-argument A.
7784 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7785 PartialOrdering, StrictPackMatch))
7786 return true;
7787 // P2113
7788 // C++20[temp.func.order]p2
7789 // [...] If both deductions succeed, the partial ordering selects the
7790 // more constrained template (if one exists) as determined below.
7791 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7792 Params->getAssociatedConstraints(ParamsAC);
7793 // C++20[temp.arg.template]p3
7794 // [...] In this comparison, if P is unconstrained, the constraints on A
7795 // are not considered.
7796 if (ParamsAC.empty())
7797 return false;
7798
7799 Template->getAssociatedConstraints(TemplateAC);
7800
7801 bool IsParamAtLeastAsConstrained;
7802 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7803 IsParamAtLeastAsConstrained))
7804 return true;
7805 if (!IsParamAtLeastAsConstrained) {
7806 Diag(Arg.getLocation(),
7807 diag::err_template_template_parameter_not_at_least_as_constrained)
7808 << Template << Param << Arg.getSourceRange();
7809 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7810 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7812 TemplateAC);
7813 return true;
7814 }
7815 return false;
7816}
7817
7819 unsigned HereDiagID,
7820 unsigned ExternalDiagID) {
7821 if (Decl.getLocation().isValid())
7822 return S.Diag(Decl.getLocation(), HereDiagID);
7823
7824 SmallString<128> Str;
7825 llvm::raw_svector_ostream Out(Str);
7827 PP.TerseOutput = 1;
7828 Decl.print(Out, PP);
7829 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7830}
7831
7833 std::optional<SourceRange> ParamRange) {
7835 noteLocation(*this, Decl, diag::note_template_decl_here,
7836 diag::note_template_decl_external);
7837 if (ParamRange && ParamRange->isValid()) {
7838 assert(Decl.getLocation().isValid() &&
7839 "Parameter range has location when Decl does not");
7840 DB << *ParamRange;
7841 }
7842}
7843
7845 noteLocation(*this, Decl, diag::note_template_param_here,
7846 diag::note_template_param_external);
7847}
7848
7849/// Given a non-type template argument that refers to a
7850/// declaration and the type of its corresponding non-type template
7851/// parameter, produce an expression that properly refers to that
7852/// declaration.
7854 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7856 // C++ [temp.param]p8:
7857 //
7858 // A non-type template-parameter of type "array of T" or
7859 // "function returning T" is adjusted to be of type "pointer to
7860 // T" or "pointer to function returning T", respectively.
7861 if (ParamType->isArrayType())
7862 ParamType = Context.getArrayDecayedType(ParamType);
7863 else if (ParamType->isFunctionType())
7864 ParamType = Context.getPointerType(ParamType);
7865
7866 // For a NULL non-type template argument, return nullptr casted to the
7867 // parameter's type.
7868 if (Arg.getKind() == TemplateArgument::NullPtr) {
7869 return ImpCastExprToType(
7870 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7871 ParamType,
7872 ParamType->getAs<MemberPointerType>()
7873 ? CK_NullToMemberPointer
7874 : CK_NullToPointer);
7875 }
7876 assert(Arg.getKind() == TemplateArgument::Declaration &&
7877 "Only declaration template arguments permitted here");
7878
7879 ValueDecl *VD = Arg.getAsDecl();
7880
7881 CXXScopeSpec SS;
7882 if (ParamType->isMemberPointerType()) {
7883 // If this is a pointer to member, we need to use a qualified name to
7884 // form a suitable pointer-to-member constant.
7885 assert(VD->getDeclContext()->isRecord() &&
7886 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7888 CanQualType ClassType =
7889 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7890 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7891 SS.MakeTrivial(Context, Qualifier, Loc);
7892 }
7893
7895 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7896 if (RefExpr.isInvalid())
7897 return ExprError();
7898
7899 // For a pointer, the argument declaration is the pointee. Take its address.
7900 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7901 if (ParamType->isPointerType() && !ElemT.isNull() &&
7902 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7903 // Decay an array argument if we want a pointer to its first element.
7904 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7905 if (RefExpr.isInvalid())
7906 return ExprError();
7907 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7908 // For any other pointer, take the address (or form a pointer-to-member).
7909 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7910 if (RefExpr.isInvalid())
7911 return ExprError();
7912 } else if (ParamType->isRecordType()) {
7913 assert(isa<TemplateParamObjectDecl>(VD) &&
7914 "arg for class template param not a template parameter object");
7915 // No conversions apply in this case.
7916 return RefExpr;
7917 } else {
7918 assert(ParamType->isReferenceType() &&
7919 "unexpected type for decl template argument");
7920 if (NonTypeTemplateParmDecl *NTTP =
7921 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7922 QualType TemplateParamType = NTTP->getType();
7923 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7924 if (AT && AT->isDecltypeAuto()) {
7926 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7927 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7928 /*PackIndex=*/std::nullopt,
7929 /*RefParam=*/true, /*Final=*/true);
7930 }
7931 }
7932 }
7933
7934 // At this point we should have the right value category.
7935 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7936 "value kind mismatch for non-type template argument");
7937
7938 // The type of the template parameter can differ from the type of the
7939 // argument in various ways; convert it now if necessary.
7940 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7941 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7942 CastKind CK;
7943 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7944 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
7945 CK = CK_NoOp;
7946 } else if (ParamType->isVoidPointerType() &&
7947 RefExpr.get()->getType()->isPointerType()) {
7948 CK = CK_BitCast;
7949 } else {
7950 // FIXME: Pointers to members can need conversion derived-to-base or
7951 // base-to-derived conversions. We currently don't retain enough
7952 // information to convert properly (we need to track a cast path or
7953 // subobject number in the template argument).
7954 llvm_unreachable(
7955 "unexpected conversion required for non-type template argument");
7956 }
7957 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7958 RefExpr.get()->getValueKind());
7959 }
7960
7961 return RefExpr;
7962}
7963
7964/// Construct a new expression that refers to the given
7965/// integral template argument with the given source-location
7966/// information.
7967///
7968/// This routine takes care of the mapping from an integral template
7969/// argument (which may have any integral type) to the appropriate
7970/// literal value.
7972 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7973 assert(OrigT->isIntegralOrEnumerationType());
7974
7975 // If this is an enum type that we're instantiating, we need to use an integer
7976 // type the same size as the enumerator. We don't want to build an
7977 // IntegerLiteral with enum type. The integer type of an enum type can be of
7978 // any integral type with C++11 enum classes, make sure we create the right
7979 // type of literal for it.
7980 QualType T = OrigT;
7981 if (const auto *ED = OrigT->getAsEnumDecl())
7982 T = ED->getIntegerType();
7983
7984 Expr *E;
7985 if (T->isAnyCharacterType()) {
7987 if (T->isWideCharType())
7989 else if (T->isChar8Type() && S.getLangOpts().Char8)
7991 else if (T->isChar16Type())
7993 else if (T->isChar32Type())
7995 else
7997
7998 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7999 } else if (T->isBooleanType()) {
8000 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8001 } else {
8002 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8003 }
8004
8005 if (OrigT->isEnumeralType()) {
8006 // FIXME: This is a hack. We need a better way to handle substituted
8007 // non-type template parameters.
8008 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8009 nullptr, S.CurFPFeatureOverrides(),
8010 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8011 Loc, Loc);
8012 }
8013
8014 return E;
8015}
8016
8018 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8019 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8020 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8021 ILE->setType(T);
8022 return ILE;
8023 };
8024
8025 switch (Val.getKind()) {
8027 // This cannot occur in a template argument at all.
8028 case APValue::Array:
8029 case APValue::Struct:
8030 case APValue::Union:
8031 // These can only occur within a template parameter object, which is
8032 // represented as a TemplateArgument::Declaration.
8033 llvm_unreachable("unexpected template argument value");
8034
8035 case APValue::Int:
8037 Loc);
8038
8039 case APValue::Float:
8040 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8041 T, Loc);
8042
8045 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8046 Val.getFixedPoint().getScale());
8047
8048 case APValue::ComplexInt: {
8049 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8051 S, ElemT, Val.getComplexIntReal(), Loc),
8053 S, ElemT, Val.getComplexIntImag(), Loc)});
8054 }
8055
8056 case APValue::ComplexFloat: {
8057 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8058 return MakeInitList(
8060 ElemT, Loc),
8062 ElemT, Loc)});
8063 }
8064
8065 case APValue::Vector: {
8066 QualType ElemT = T->castAs<VectorType>()->getElementType();
8068 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8070 S, ElemT, Val.getVectorElt(I), Loc));
8071 return MakeInitList(Elts);
8072 }
8073
8074 case APValue::None:
8076 llvm_unreachable("Unexpected APValue kind.");
8077 case APValue::LValue:
8079 // There isn't necessarily a valid equivalent source-level syntax for
8080 // these; in particular, a naive lowering might violate access control.
8081 // So for now we lower to a ConstantExpr holding the value, wrapped around
8082 // an OpaqueValueExpr.
8083 // FIXME: We should have a better representation for this.
8085 if (T->isReferenceType()) {
8086 T = T->getPointeeType();
8087 VK = VK_LValue;
8088 }
8089 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8090 return ConstantExpr::Create(S.Context, OVE, Val);
8091 }
8092 llvm_unreachable("Unhandled APValue::ValueKind enum");
8093}
8094
8097 SourceLocation Loc) {
8098 switch (Arg.getKind()) {
8104 llvm_unreachable("not a non-type template argument");
8105
8107 return Arg.getAsExpr();
8108
8112 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8113
8116 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8117
8120 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8121 }
8122 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8123}
8124
8125/// Match two template parameters within template parameter lists.
8127 Sema &S, NamedDecl *New,
8128 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8129 const NamedDecl *OldInstFrom, bool Complain,
8131 // Check the actual kind (type, non-type, template).
8132 if (Old->getKind() != New->getKind()) {
8133 if (Complain) {
8134 unsigned NextDiag = diag::err_template_param_different_kind;
8135 if (TemplateArgLoc.isValid()) {
8136 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8137 NextDiag = diag::note_template_param_different_kind;
8138 }
8139 S.Diag(New->getLocation(), NextDiag)
8140 << (Kind != Sema::TPL_TemplateMatch);
8141 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8142 << (Kind != Sema::TPL_TemplateMatch);
8143 }
8144
8145 return false;
8146 }
8147
8148 // Check that both are parameter packs or neither are parameter packs.
8149 // However, if we are matching a template template argument to a
8150 // template template parameter, the template template parameter can have
8151 // a parameter pack where the template template argument does not.
8152 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8153 if (Complain) {
8154 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8155 if (TemplateArgLoc.isValid()) {
8156 S.Diag(TemplateArgLoc,
8157 diag::err_template_arg_template_params_mismatch);
8158 NextDiag = diag::note_template_parameter_pack_non_pack;
8159 }
8160
8161 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8163 : 2;
8164 S.Diag(New->getLocation(), NextDiag)
8165 << ParamKind << New->isParameterPack();
8166 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8167 << ParamKind << Old->isParameterPack();
8168 }
8169
8170 return false;
8171 }
8172 // For non-type template parameters, check the type of the parameter.
8173 if (NonTypeTemplateParmDecl *OldNTTP =
8174 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8176
8177 // If we are matching a template template argument to a template
8178 // template parameter and one of the non-type template parameter types
8179 // is dependent, then we must wait until template instantiation time
8180 // to actually compare the arguments.
8182 (!OldNTTP->getType()->isDependentType() &&
8183 !NewNTTP->getType()->isDependentType())) {
8184 // C++20 [temp.over.link]p6:
8185 // Two [non-type] template-parameters are equivalent [if] they have
8186 // equivalent types ignoring the use of type-constraints for
8187 // placeholder types
8188 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8189 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8190 if (!S.Context.hasSameType(OldType, NewType)) {
8191 if (Complain) {
8192 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8193 if (TemplateArgLoc.isValid()) {
8194 S.Diag(TemplateArgLoc,
8195 diag::err_template_arg_template_params_mismatch);
8196 NextDiag = diag::note_template_nontype_parm_different_type;
8197 }
8198 S.Diag(NewNTTP->getLocation(), NextDiag)
8199 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8200 S.Diag(OldNTTP->getLocation(),
8201 diag::note_template_nontype_parm_prev_declaration)
8202 << OldNTTP->getType();
8203 }
8204 return false;
8205 }
8206 }
8207 }
8208 // For template template parameters, check the template parameter types.
8209 // The template parameter lists of template template
8210 // parameters must agree.
8211 else if (TemplateTemplateParmDecl *OldTTP =
8212 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8214 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8215 return false;
8217 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8218 OldTTP->getTemplateParameters(), Complain,
8221 : Kind),
8222 TemplateArgLoc))
8223 return false;
8224 }
8225
8229 const Expr *NewC = nullptr, *OldC = nullptr;
8230
8232 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8233 NewC = TC->getImmediatelyDeclaredConstraint();
8234 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8235 OldC = TC->getImmediatelyDeclaredConstraint();
8236 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8237 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8238 ->getPlaceholderTypeConstraint())
8239 NewC = E;
8240 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8241 ->getPlaceholderTypeConstraint())
8242 OldC = E;
8243 } else
8244 llvm_unreachable("unexpected template parameter type");
8245
8246 auto Diagnose = [&] {
8247 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8248 diag::err_template_different_type_constraint);
8249 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8250 diag::note_template_prev_declaration) << /*declaration*/0;
8251 };
8252
8253 if (!NewC != !OldC) {
8254 if (Complain)
8255 Diagnose();
8256 return false;
8257 }
8258
8259 if (NewC) {
8260 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8261 NewC)) {
8262 if (Complain)
8263 Diagnose();
8264 return false;
8265 }
8266 }
8267 }
8268
8269 return true;
8270}
8271
8272/// Diagnose a known arity mismatch when comparing template argument
8273/// lists.
8274static
8279 SourceLocation TemplateArgLoc) {
8280 unsigned NextDiag = diag::err_template_param_list_different_arity;
8281 if (TemplateArgLoc.isValid()) {
8282 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8283 NextDiag = diag::note_template_param_list_different_arity;
8284 }
8285 S.Diag(New->getTemplateLoc(), NextDiag)
8286 << (New->size() > Old->size())
8287 << (Kind != Sema::TPL_TemplateMatch)
8288 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8289 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8290 << (Kind != Sema::TPL_TemplateMatch)
8291 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8292}
8293
8296 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8297 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8298 if (Old->size() != New->size()) {
8299 if (Complain)
8301 TemplateArgLoc);
8302
8303 return false;
8304 }
8305
8306 // C++0x [temp.arg.template]p3:
8307 // A template-argument matches a template template-parameter (call it P)
8308 // when each of the template parameters in the template-parameter-list of
8309 // the template-argument's corresponding class template or alias template
8310 // (call it A) matches the corresponding template parameter in the
8311 // template-parameter-list of P. [...]
8312 TemplateParameterList::iterator NewParm = New->begin();
8313 TemplateParameterList::iterator NewParmEnd = New->end();
8314 for (TemplateParameterList::iterator OldParm = Old->begin(),
8315 OldParmEnd = Old->end();
8316 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8317 if (NewParm == NewParmEnd) {
8318 if (Complain)
8320 TemplateArgLoc);
8321 return false;
8322 }
8323 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8324 OldInstFrom, Complain, Kind,
8325 TemplateArgLoc))
8326 return false;
8327 }
8328
8329 // Make sure we exhausted all of the arguments.
8330 if (NewParm != NewParmEnd) {
8331 if (Complain)
8333 TemplateArgLoc);
8334
8335 return false;
8336 }
8337
8338 if (Kind != TPL_TemplateParamsEquivalent) {
8339 const Expr *NewRC = New->getRequiresClause();
8340 const Expr *OldRC = Old->getRequiresClause();
8341
8342 auto Diagnose = [&] {
8343 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8344 diag::err_template_different_requires_clause);
8345 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8346 diag::note_template_prev_declaration) << /*declaration*/0;
8347 };
8348
8349 if (!NewRC != !OldRC) {
8350 if (Complain)
8351 Diagnose();
8352 return false;
8353 }
8354
8355 if (NewRC) {
8356 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8357 NewRC)) {
8358 if (Complain)
8359 Diagnose();
8360 return false;
8361 }
8362 }
8363 }
8364
8365 return true;
8366}
8367
8368bool
8370 if (!S)
8371 return false;
8372
8373 // Find the nearest enclosing declaration scope.
8374 S = S->getDeclParent();
8375
8376 // C++ [temp.pre]p6: [P2096]
8377 // A template, explicit specialization, or partial specialization shall not
8378 // have C linkage.
8379 DeclContext *Ctx = S->getEntity();
8380 if (Ctx && Ctx->isExternCContext()) {
8381 SourceRange Range =
8382 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8383 ? TemplateParams->getParam(0)->getSourceRange()
8384 : TemplateParams->getSourceRange();
8385 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8386 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8387 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8388 return true;
8389 }
8390 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8391
8392 // C++ [temp]p2:
8393 // A template-declaration can appear only as a namespace scope or
8394 // class scope declaration.
8395 // C++ [temp.expl.spec]p3:
8396 // An explicit specialization may be declared in any scope in which the
8397 // corresponding primary template may be defined.
8398 // C++ [temp.class.spec]p6: [P2096]
8399 // A partial specialization may be declared in any scope in which the
8400 // corresponding primary template may be defined.
8401 if (Ctx) {
8402 if (Ctx->isFileContext())
8403 return false;
8404 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8405 // C++ [temp.mem]p2:
8406 // A local class shall not have member templates.
8407 if (RD->isLocalClass())
8408 return Diag(TemplateParams->getTemplateLoc(),
8409 diag::err_template_inside_local_class)
8410 << TemplateParams->getSourceRange();
8411 else
8412 return false;
8413 }
8414 }
8415
8416 return Diag(TemplateParams->getTemplateLoc(),
8417 diag::err_template_outside_namespace_or_class_scope)
8418 << TemplateParams->getSourceRange();
8419}
8420
8421/// Determine what kind of template specialization the given declaration
8422/// is.
8424 if (!D)
8425 return TSK_Undeclared;
8426
8427 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8428 return Record->getTemplateSpecializationKind();
8429 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8430 return Function->getTemplateSpecializationKind();
8431 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8432 return Var->getTemplateSpecializationKind();
8433
8434 return TSK_Undeclared;
8435}
8436
8437/// Check whether a specialization is well-formed in the current
8438/// context.
8439///
8440/// This routine determines whether a template specialization can be declared
8441/// in the current context (C++ [temp.expl.spec]p2).
8442///
8443/// \param S the semantic analysis object for which this check is being
8444/// performed.
8445///
8446/// \param Specialized the entity being specialized or instantiated, which
8447/// may be a kind of template (class template, function template, etc.) or
8448/// a member of a class template (member function, static data member,
8449/// member class).
8450///
8451/// \param PrevDecl the previous declaration of this entity, if any.
8452///
8453/// \param Loc the location of the explicit specialization or instantiation of
8454/// this entity.
8455///
8456/// \param IsPartialSpecialization whether this is a partial specialization of
8457/// a class template.
8458///
8459/// \returns true if there was an error that we cannot recover from, false
8460/// otherwise.
8462 NamedDecl *Specialized,
8463 NamedDecl *PrevDecl,
8464 SourceLocation Loc,
8466 // Keep these "kind" numbers in sync with the %select statements in the
8467 // various diagnostics emitted by this routine.
8468 int EntityKind = 0;
8469 if (isa<ClassTemplateDecl>(Specialized))
8470 EntityKind = IsPartialSpecialization? 1 : 0;
8471 else if (isa<VarTemplateDecl>(Specialized))
8472 EntityKind = IsPartialSpecialization ? 3 : 2;
8473 else if (isa<FunctionTemplateDecl>(Specialized))
8474 EntityKind = 4;
8475 else if (isa<CXXMethodDecl>(Specialized))
8476 EntityKind = 5;
8477 else if (isa<VarDecl>(Specialized))
8478 EntityKind = 6;
8479 else if (isa<RecordDecl>(Specialized))
8480 EntityKind = 7;
8481 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8482 EntityKind = 8;
8483 else {
8484 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8485 << S.getLangOpts().CPlusPlus11;
8486 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8487 return true;
8488 }
8489
8490 // C++ [temp.expl.spec]p2:
8491 // An explicit specialization may be declared in any scope in which
8492 // the corresponding primary template may be defined.
8494 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8495 << Specialized;
8496 return true;
8497 }
8498
8499 // C++ [temp.class.spec]p6:
8500 // A class template partial specialization may be declared in any
8501 // scope in which the primary template may be defined.
8502 DeclContext *SpecializedContext =
8503 Specialized->getDeclContext()->getRedeclContext();
8505
8506 // Make sure that this redeclaration (or definition) occurs in the same
8507 // scope or an enclosing namespace.
8508 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8509 : DC->Equals(SpecializedContext))) {
8510 if (isa<TranslationUnitDecl>(SpecializedContext))
8511 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8512 << EntityKind << Specialized;
8513 else {
8514 auto *ND = cast<NamedDecl>(SpecializedContext);
8515 int Diag = diag::err_template_spec_redecl_out_of_scope;
8516 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8517 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8518 S.Diag(Loc, Diag) << EntityKind << Specialized
8519 << ND << isa<CXXRecordDecl>(ND);
8520 }
8521
8522 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8523
8524 // Don't allow specializing in the wrong class during error recovery.
8525 // Otherwise, things can go horribly wrong.
8526 if (DC->isRecord())
8527 return true;
8528 }
8529
8530 return false;
8531}
8532
8534 if (!E->isTypeDependent())
8535 return SourceLocation();
8536 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8537 Checker.TraverseStmt(E);
8538 if (Checker.MatchLoc.isInvalid())
8539 return E->getSourceRange();
8540 return Checker.MatchLoc;
8541}
8542
8543static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8544 if (!TL.getType()->isDependentType())
8545 return SourceLocation();
8546 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8547 Checker.TraverseTypeLoc(TL);
8548 if (Checker.MatchLoc.isInvalid())
8549 return TL.getSourceRange();
8550 return Checker.MatchLoc;
8551}
8552
8553/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8554/// that checks non-type template partial specialization arguments.
8556 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8557 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8558 for (unsigned I = 0; I != NumArgs; ++I) {
8559 if (Args[I].getKind() == TemplateArgument::Pack) {
8561 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8562 Args[I].pack_size(), IsDefaultArgument))
8563 return true;
8564
8565 continue;
8566 }
8567
8568 if (Args[I].getKind() != TemplateArgument::Expression)
8569 continue;
8570
8571 Expr *ArgExpr = Args[I].getAsExpr();
8572
8573 // We can have a pack expansion of any of the bullets below.
8574 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8575 ArgExpr = Expansion->getPattern();
8576
8577 // Strip off any implicit casts we added as part of type checking.
8578 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8579 ArgExpr = ICE->getSubExpr();
8580
8581 // C++ [temp.class.spec]p8:
8582 // A non-type argument is non-specialized if it is the name of a
8583 // non-type parameter. All other non-type arguments are
8584 // specialized.
8585 //
8586 // Below, we check the two conditions that only apply to
8587 // specialized non-type arguments, so skip any non-specialized
8588 // arguments.
8589 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8590 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8591 continue;
8592
8593 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8594 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8595 continue;
8596 }
8597
8598 // C++ [temp.class.spec]p9:
8599 // Within the argument list of a class template partial
8600 // specialization, the following restrictions apply:
8601 // -- A partially specialized non-type argument expression
8602 // shall not involve a template parameter of the partial
8603 // specialization except when the argument expression is a
8604 // simple identifier.
8605 // -- The type of a template parameter corresponding to a
8606 // specialized non-type argument shall not be dependent on a
8607 // parameter of the specialization.
8608 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8609 // We implement a compromise between the original rules and DR1315:
8610 // -- A specialized non-type template argument shall not be
8611 // type-dependent and the corresponding template parameter
8612 // shall have a non-dependent type.
8613 SourceRange ParamUseRange =
8614 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8615 if (ParamUseRange.isValid()) {
8616 if (IsDefaultArgument) {
8617 S.Diag(TemplateNameLoc,
8618 diag::err_dependent_non_type_arg_in_partial_spec);
8619 S.Diag(ParamUseRange.getBegin(),
8620 diag::note_dependent_non_type_default_arg_in_partial_spec)
8621 << ParamUseRange;
8622 } else {
8623 S.Diag(ParamUseRange.getBegin(),
8624 diag::err_dependent_non_type_arg_in_partial_spec)
8625 << ParamUseRange;
8626 }
8627 return true;
8628 }
8629
8630 ParamUseRange = findTemplateParameter(
8631 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8632 if (ParamUseRange.isValid()) {
8633 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8634 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8635 << Param->getType();
8637 return true;
8638 }
8639 }
8640
8641 return false;
8642}
8643
8645 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8646 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8647 // We have to be conservative when checking a template in a dependent
8648 // context.
8649 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8650 return false;
8651
8652 TemplateParameterList *TemplateParams =
8653 PrimaryTemplate->getTemplateParameters();
8654 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8656 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8657 if (!Param)
8658 continue;
8659
8660 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8661 Param, &TemplateArgs[I],
8662 1, I >= NumExplicit))
8663 return true;
8664 }
8665
8666 return false;
8667}
8668
8670 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8671 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8673 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8674 assert(TUK != TagUseKind::Reference && "References are not specializations");
8675
8676 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8677 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8678 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8679
8680 // Find the class template we're specializing
8681 TemplateName Name = TemplateId.Template.get();
8683 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8684
8685 if (!ClassTemplate) {
8686 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8687 << (Name.getAsTemplateDecl() &&
8689 return true;
8690 }
8691
8692 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8693 auto Message = DSA->getMessage();
8694 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8695 << ClassTemplate << !Message.empty() << Message;
8696 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8697 }
8698
8699 if (S->isTemplateParamScope())
8700 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8701
8702 DeclContext *DC = ClassTemplate->getDeclContext();
8703
8704 bool isMemberSpecialization = false;
8705 bool isPartialSpecialization = false;
8706
8707 if (SS.isSet()) {
8708 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8709 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8710 TemplateNameLoc, &TemplateId,
8711 /*IsMemberSpecialization=*/false))
8712 return true;
8713 }
8714
8715 // Check the validity of the template headers that introduce this
8716 // template.
8717 // FIXME: We probably shouldn't complain about these headers for
8718 // friend declarations.
8719 bool Invalid = false;
8720 TemplateParameterList *TemplateParams =
8722 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8723 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8724 if (Invalid)
8725 return true;
8726
8727 // Check that we can declare a template specialization here.
8728 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8729 return true;
8730
8731 if (TemplateParams && DC->isDependentContext()) {
8732 ContextRAII SavedContext(*this, DC);
8734 return true;
8735 }
8736
8737 if (TemplateParams && TemplateParams->size() > 0) {
8738 isPartialSpecialization = true;
8739
8740 if (TUK == TagUseKind::Friend) {
8741 Diag(KWLoc, diag::err_partial_specialization_friend)
8742 << SourceRange(LAngleLoc, RAngleLoc);
8743 return true;
8744 }
8745
8746 // C++ [temp.class.spec]p10:
8747 // The template parameter list of a specialization shall not
8748 // contain default template argument values.
8749 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8750 Decl *Param = TemplateParams->getParam(I);
8751 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8752 if (TTP->hasDefaultArgument()) {
8753 Diag(TTP->getDefaultArgumentLoc(),
8754 diag::err_default_arg_in_partial_spec);
8755 TTP->removeDefaultArgument();
8756 }
8757 } else if (NonTypeTemplateParmDecl *NTTP
8758 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8759 if (NTTP->hasDefaultArgument()) {
8760 Diag(NTTP->getDefaultArgumentLoc(),
8761 diag::err_default_arg_in_partial_spec)
8762 << NTTP->getDefaultArgument().getSourceRange();
8763 NTTP->removeDefaultArgument();
8764 }
8765 } else {
8767 if (TTP->hasDefaultArgument()) {
8769 diag::err_default_arg_in_partial_spec)
8771 TTP->removeDefaultArgument();
8772 }
8773 }
8774 }
8775 } else if (TemplateParams) {
8776 if (TUK == TagUseKind::Friend)
8777 Diag(KWLoc, diag::err_template_spec_friend)
8779 SourceRange(TemplateParams->getTemplateLoc(),
8780 TemplateParams->getRAngleLoc()))
8781 << SourceRange(LAngleLoc, RAngleLoc);
8782 } else {
8783 assert(TUK == TagUseKind::Friend &&
8784 "should have a 'template<>' for this decl");
8785 }
8786
8787 // Check that the specialization uses the same tag kind as the
8788 // original template.
8790 assert(Kind != TagTypeKind::Enum &&
8791 "Invalid enum tag in class template spec!");
8792 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8793 TUK == TagUseKind::Definition, KWLoc,
8794 ClassTemplate->getIdentifier())) {
8795 Diag(KWLoc, diag::err_use_with_wrong_tag)
8796 << ClassTemplate
8798 ClassTemplate->getTemplatedDecl()->getKindName());
8799 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8800 diag::note_previous_use);
8801 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8802 }
8803
8804 // Translate the parser's template argument list in our AST format.
8805 TemplateArgumentListInfo TemplateArgs =
8806 makeTemplateArgumentListInfo(*this, TemplateId);
8807
8808 // Check for unexpanded parameter packs in any of the template arguments.
8809 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8810 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8811 isPartialSpecialization
8814 return true;
8815
8816 // Check that the template argument list is well-formed for this
8817 // template.
8819 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8820 /*DefaultArgs=*/{},
8821 /*PartialTemplateArgs=*/false, CTAI,
8822 /*UpdateArgsWithConversions=*/true))
8823 return true;
8824
8825 // Find the class template (partial) specialization declaration that
8826 // corresponds to these arguments.
8827 if (isPartialSpecialization) {
8829 TemplateArgs.size(),
8830 CTAI.CanonicalConverted))
8831 return true;
8832
8833 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8834 // also do it during instantiation.
8835 if (!Name.isDependent() &&
8836 !TemplateSpecializationType::anyDependentTemplateArguments(
8837 TemplateArgs, CTAI.CanonicalConverted)) {
8838 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8839 << ClassTemplate->getDeclName();
8840 isPartialSpecialization = false;
8841 Invalid = true;
8842 }
8843 }
8844
8845 void *InsertPos = nullptr;
8846 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8847
8848 if (isPartialSpecialization)
8849 PrevDecl = ClassTemplate->findPartialSpecialization(
8850 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8851 else
8852 PrevDecl =
8853 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8854
8856
8857 // Check whether we can declare a class template specialization in
8858 // the current scope.
8859 if (TUK != TagUseKind::Friend &&
8861 TemplateNameLoc,
8862 isPartialSpecialization))
8863 return true;
8864
8865 if (!isPartialSpecialization) {
8866 // Create a new class template specialization declaration node for
8867 // this explicit specialization or friend declaration.
8869 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8870 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8871 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8873 if (TemplateParameterLists.size() > 0) {
8874 Specialization->setTemplateParameterListsInfo(Context,
8875 TemplateParameterLists);
8876 }
8877
8878 if (!PrevDecl)
8879 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8880 } else {
8882 Context.getCanonicalTemplateSpecializationType(
8884 TemplateName(ClassTemplate->getCanonicalDecl()),
8885 CTAI.CanonicalConverted));
8886 if (Context.hasSameType(
8887 CanonType,
8888 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8889 (!Context.getLangOpts().CPlusPlus20 ||
8890 !TemplateParams->hasAssociatedConstraints())) {
8891 // C++ [temp.class.spec]p9b3:
8892 //
8893 // -- The argument list of the specialization shall not be identical
8894 // to the implicit argument list of the primary template.
8895 //
8896 // This rule has since been removed, because it's redundant given DR1495,
8897 // but we keep it because it produces better diagnostics and recovery.
8898 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8899 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8900 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8901 return CheckClassTemplate(
8902 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8903 TemplateNameLoc, Attr, TemplateParams, AS_none,
8904 /*ModulePrivateLoc=*/SourceLocation(),
8905 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8906 TemplateParameterLists.data());
8907 }
8908
8909 // Create a new class template partial specialization declaration node.
8911 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8914 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8915 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8916 Partial->setTemplateArgsAsWritten(TemplateArgs);
8917 SetNestedNameSpecifier(*this, Partial, SS);
8918 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8920 Context, TemplateParameterLists.drop_back(1));
8921 }
8922
8923 if (!PrevPartial)
8924 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8925 Specialization = Partial;
8926
8927 // If we are providing an explicit specialization of a member class
8928 // template specialization, make a note of that.
8929 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8930 PrevPartial->setMemberSpecialization();
8931
8933 }
8934
8935 // C++ [temp.expl.spec]p6:
8936 // If a template, a member template or the member of a class template is
8937 // explicitly specialized then that specialization shall be declared
8938 // before the first use of that specialization that would cause an implicit
8939 // instantiation to take place, in every translation unit in which such a
8940 // use occurs; no diagnostic is required.
8941 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8942 bool Okay = false;
8943 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8944 // Is there any previous explicit specialization declaration?
8946 Okay = true;
8947 break;
8948 }
8949 }
8950
8951 if (!Okay) {
8952 SourceRange Range(TemplateNameLoc, RAngleLoc);
8953 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8954 << Context.getCanonicalTagType(Specialization) << Range;
8955
8956 Diag(PrevDecl->getPointOfInstantiation(),
8957 diag::note_instantiation_required_here)
8958 << (PrevDecl->getTemplateSpecializationKind()
8960 return true;
8961 }
8962 }
8963
8964 // If this is not a friend, note that this is an explicit specialization.
8965 if (TUK != TagUseKind::Friend)
8966 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8967
8968 // Check that this isn't a redefinition of this specialization.
8969 if (TUK == TagUseKind::Definition) {
8970 RecordDecl *Def = Specialization->getDefinition();
8971 NamedDecl *Hidden = nullptr;
8972 bool HiddenDefVisible = false;
8973 if (Def && SkipBody &&
8974 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
8975 SkipBody->ShouldSkip = true;
8976 SkipBody->Previous = Def;
8977 if (!HiddenDefVisible && Hidden)
8979 } else if (Def) {
8980 SourceRange Range(TemplateNameLoc, RAngleLoc);
8981 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8982 Diag(Def->getLocation(), diag::note_previous_definition);
8983 Specialization->setInvalidDecl();
8984 return true;
8985 }
8986 }
8987
8990
8991 // Add alignment attributes if necessary; these attributes are checked when
8992 // the ASTContext lays out the structure.
8993 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8994 if (LangOpts.HLSL)
8995 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
8998 }
8999
9000 if (ModulePrivateLoc.isValid())
9001 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9002 << (isPartialSpecialization? 1 : 0)
9003 << FixItHint::CreateRemoval(ModulePrivateLoc);
9004
9005 // C++ [temp.expl.spec]p9:
9006 // A template explicit specialization is in the scope of the
9007 // namespace in which the template was defined.
9008 //
9009 // We actually implement this paragraph where we set the semantic
9010 // context (in the creation of the ClassTemplateSpecializationDecl),
9011 // but we also maintain the lexical context where the actual
9012 // definition occurs.
9013 Specialization->setLexicalDeclContext(CurContext);
9014
9015 // We may be starting the definition of this specialization.
9016 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9017 Specialization->startDefinition();
9018
9019 if (TUK == TagUseKind::Friend) {
9020 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9021 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9022 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9024 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9025 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9026
9027 // Build the fully-sugared type for this class template
9028 // specialization as the user wrote in the specialization
9029 // itself. This means that we'll pretty-print the type retrieved
9030 // from the specialization's declaration the way that the user
9031 // actually wrote the specialization, rather than formatting the
9032 // name based on the "canonical" representation used to store the
9033 // template arguments in the specialization.
9035 TemplateNameLoc,
9036 WrittenTy,
9037 /*FIXME:*/KWLoc);
9038 Friend->setAccess(AS_public);
9039 CurContext->addDecl(Friend);
9040 } else {
9041 // Add the specialization into its lexical context, so that it can
9042 // be seen when iterating through the list of declarations in that
9043 // context. However, specializations are not found by name lookup.
9044 CurContext->addDecl(Specialization);
9045 }
9046
9047 if (SkipBody && SkipBody->ShouldSkip)
9048 return SkipBody->Previous;
9049
9050 Specialization->setInvalidDecl(Invalid);
9052 return Specialization;
9053}
9054
9056 MultiTemplateParamsArg TemplateParameterLists,
9057 Declarator &D) {
9058 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9059 ActOnDocumentableDecl(NewDecl);
9060 return NewDecl;
9061}
9062
9064 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9065 const IdentifierInfo *Name, SourceLocation NameLoc) {
9066 DeclContext *DC = CurContext;
9067
9068 if (!DC->getRedeclContext()->isFileContext()) {
9069 Diag(NameLoc,
9070 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9071 return nullptr;
9072 }
9073
9074 if (TemplateParameterLists.size() > 1) {
9075 Diag(NameLoc, diag::err_concept_extra_headers);
9076 return nullptr;
9077 }
9078
9079 TemplateParameterList *Params = TemplateParameterLists.front();
9080
9081 if (Params->size() == 0) {
9082 Diag(NameLoc, diag::err_concept_no_parameters);
9083 return nullptr;
9084 }
9085
9086 // Ensure that the parameter pack, if present, is the last parameter in the
9087 // template.
9088 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9089 ParamEnd = Params->end();
9090 ParamIt != ParamEnd; ++ParamIt) {
9091 Decl const *Param = *ParamIt;
9092 if (Param->isParameterPack()) {
9093 if (++ParamIt == ParamEnd)
9094 break;
9095 Diag(Param->getLocation(),
9096 diag::err_template_param_pack_must_be_last_template_parameter);
9097 return nullptr;
9098 }
9099 }
9100
9101 ConceptDecl *NewDecl =
9102 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9103
9104 if (NewDecl->hasAssociatedConstraints()) {
9105 // C++2a [temp.concept]p4:
9106 // A concept shall not have associated constraints.
9107 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9108 NewDecl->setInvalidDecl();
9109 }
9110
9111 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9112 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9114 LookupName(Previous, S);
9115 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9116 /*AllowInlineNamespace*/ false);
9117
9118 // We cannot properly handle redeclarations until we parse the constraint
9119 // expression, so only inject the name if we are sure we are not redeclaring a
9120 // symbol
9121 if (Previous.empty())
9122 PushOnScopeChains(NewDecl, S, true);
9123
9124 return NewDecl;
9125}
9126
9128 bool Found = false;
9130 while (F.hasNext()) {
9131 NamedDecl *D = F.next();
9132 if (D == C) {
9133 F.erase();
9134 Found = true;
9135 break;
9136 }
9137 }
9138 F.done();
9139 return Found;
9140}
9141
9144 Expr *ConstraintExpr,
9145 const ParsedAttributesView &Attrs) {
9146 assert(!C->hasDefinition() && "Concept already defined");
9147 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9148 C->setInvalidDecl();
9149 return nullptr;
9150 }
9151 C->setDefinition(ConstraintExpr);
9152 ProcessDeclAttributeList(S, C, Attrs);
9153
9154 // Check for conflicting previous declaration.
9155 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9156 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9158 LookupName(Previous, S);
9159 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9160 /*AllowInlineNamespace*/ false);
9161 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9162 bool AddToScope = true;
9163 CheckConceptRedefinition(C, Previous, AddToScope);
9164
9166 if (!WasAlreadyAdded && AddToScope)
9167 PushOnScopeChains(C, S);
9168
9169 return C;
9170}
9171
9173 LookupResult &Previous, bool &AddToScope) {
9174 AddToScope = true;
9175
9176 if (Previous.empty())
9177 return;
9178
9179 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9180 if (!OldConcept) {
9181 auto *Old = Previous.getRepresentativeDecl();
9182 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9183 << NewDecl->getDeclName();
9184 notePreviousDefinition(Old, NewDecl->getLocation());
9185 AddToScope = false;
9186 return;
9187 }
9188 // Check if we can merge with a concept declaration.
9189 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9190 if (!IsSame) {
9191 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9192 << NewDecl->getDeclName();
9193 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9194 AddToScope = false;
9195 return;
9196 }
9197 if (hasReachableDefinition(OldConcept) &&
9198 IsRedefinitionInModule(NewDecl, OldConcept)) {
9199 Diag(NewDecl->getLocation(), diag::err_redefinition)
9200 << NewDecl->getDeclName();
9201 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9202 AddToScope = false;
9203 return;
9204 }
9205 if (!Previous.isSingleResult()) {
9206 // FIXME: we should produce an error in case of ambig and failed lookups.
9207 // Other decls (e.g. namespaces) also have this shortcoming.
9208 return;
9209 }
9210 // We unwrap canonical decl late to check for module visibility.
9211 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9212}
9213
9215 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9216 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9217 Diag(Loc, diag::err_recursive_concept) << CE;
9218 Diag(CE->getLocation(), diag::note_declared_at);
9219 return true;
9220 }
9221 // Concept template parameters don't have a definition and can't
9222 // be defined recursively.
9223 return false;
9224}
9225
9226/// \brief Strips various properties off an implicit instantiation
9227/// that has just been explicitly specialized.
9228static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9229 if (MinGW || (isa<FunctionDecl>(D) &&
9230 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9231 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9232
9233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9234 FD->setInlineSpecified(false);
9235}
9236
9237/// Compute the diagnostic location for an explicit instantiation
9238// declaration or definition.
9240 NamedDecl* D, SourceLocation PointOfInstantiation) {
9241 // Explicit instantiations following a specialization have no effect and
9242 // hence no PointOfInstantiation. In that case, walk decl backwards
9243 // until a valid name loc is found.
9244 SourceLocation PrevDiagLoc = PointOfInstantiation;
9245 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9246 Prev = Prev->getPreviousDecl()) {
9247 PrevDiagLoc = Prev->getLocation();
9248 }
9249 assert(PrevDiagLoc.isValid() &&
9250 "Explicit instantiation without point of instantiation?");
9251 return PrevDiagLoc;
9252}
9253
9254bool
9257 NamedDecl *PrevDecl,
9259 SourceLocation PrevPointOfInstantiation,
9260 bool &HasNoEffect) {
9261 HasNoEffect = false;
9262
9263 switch (NewTSK) {
9264 case TSK_Undeclared:
9266 assert(
9267 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9268 "previous declaration must be implicit!");
9269 return false;
9270
9272 switch (PrevTSK) {
9273 case TSK_Undeclared:
9275 // Okay, we're just specializing something that is either already
9276 // explicitly specialized or has merely been mentioned without any
9277 // instantiation.
9278 return false;
9279
9281 if (PrevPointOfInstantiation.isInvalid()) {
9282 // The declaration itself has not actually been instantiated, so it is
9283 // still okay to specialize it.
9285 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9286 return false;
9287 }
9288 // Fall through
9289 [[fallthrough]];
9290
9293 assert((PrevTSK == TSK_ImplicitInstantiation ||
9294 PrevPointOfInstantiation.isValid()) &&
9295 "Explicit instantiation without point of instantiation?");
9296
9297 // C++ [temp.expl.spec]p6:
9298 // If a template, a member template or the member of a class template
9299 // is explicitly specialized then that specialization shall be declared
9300 // before the first use of that specialization that would cause an
9301 // implicit instantiation to take place, in every translation unit in
9302 // which such a use occurs; no diagnostic is required.
9303 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9304 // Is there any previous explicit specialization declaration?
9306 return false;
9307 }
9308
9309 Diag(NewLoc, diag::err_specialization_after_instantiation)
9310 << PrevDecl;
9311 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9312 << (PrevTSK != TSK_ImplicitInstantiation);
9313
9314 return true;
9315 }
9316 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9317
9319 switch (PrevTSK) {
9321 // This explicit instantiation declaration is redundant (that's okay).
9322 HasNoEffect = true;
9323 return false;
9324
9325 case TSK_Undeclared:
9327 // We're explicitly instantiating something that may have already been
9328 // implicitly instantiated; that's fine.
9329 return false;
9330
9332 // C++0x [temp.explicit]p4:
9333 // For a given set of template parameters, if an explicit instantiation
9334 // of a template appears after a declaration of an explicit
9335 // specialization for that template, the explicit instantiation has no
9336 // effect.
9337 HasNoEffect = true;
9338 return false;
9339
9341 // C++0x [temp.explicit]p10:
9342 // If an entity is the subject of both an explicit instantiation
9343 // declaration and an explicit instantiation definition in the same
9344 // translation unit, the definition shall follow the declaration.
9345 Diag(NewLoc,
9346 diag::err_explicit_instantiation_declaration_after_definition);
9347
9348 // Explicit instantiations following a specialization have no effect and
9349 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9350 // until a valid name loc is found.
9351 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9352 diag::note_explicit_instantiation_definition_here);
9353 HasNoEffect = true;
9354 return false;
9355 }
9356 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9357
9359 switch (PrevTSK) {
9360 case TSK_Undeclared:
9362 // We're explicitly instantiating something that may have already been
9363 // implicitly instantiated; that's fine.
9364 return false;
9365
9367 // C++ DR 259, C++0x [temp.explicit]p4:
9368 // For a given set of template parameters, if an explicit
9369 // instantiation of a template appears after a declaration of
9370 // an explicit specialization for that template, the explicit
9371 // instantiation has no effect.
9372 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9373 << PrevDecl;
9374 Diag(PrevDecl->getLocation(),
9375 diag::note_previous_template_specialization);
9376 HasNoEffect = true;
9377 return false;
9378
9380 // We're explicitly instantiating a definition for something for which we
9381 // were previously asked to suppress instantiations. That's fine.
9382
9383 // C++0x [temp.explicit]p4:
9384 // For a given set of template parameters, if an explicit instantiation
9385 // of a template appears after a declaration of an explicit
9386 // specialization for that template, the explicit instantiation has no
9387 // effect.
9388 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9389 // Is there any previous explicit specialization declaration?
9391 HasNoEffect = true;
9392 break;
9393 }
9394 }
9395
9396 return false;
9397
9399 // C++0x [temp.spec]p5:
9400 // For a given template and a given set of template-arguments,
9401 // - an explicit instantiation definition shall appear at most once
9402 // in a program,
9403
9404 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9405 Diag(NewLoc, (getLangOpts().MSVCCompat)
9406 ? diag::ext_explicit_instantiation_duplicate
9407 : diag::err_explicit_instantiation_duplicate)
9408 << PrevDecl;
9409 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9410 diag::note_previous_explicit_instantiation);
9411 HasNoEffect = true;
9412 return false;
9413 }
9414 }
9415
9416 llvm_unreachable("Missing specialization/instantiation case?");
9417}
9418
9420 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9422 // Remove anything from Previous that isn't a function template in
9423 // the correct context.
9424 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9425 LookupResult::Filter F = Previous.makeFilter();
9426 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9427 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9428 while (F.hasNext()) {
9429 NamedDecl *D = F.next()->getUnderlyingDecl();
9430 if (!isa<FunctionTemplateDecl>(D)) {
9431 F.erase();
9432 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9433 continue;
9434 }
9435
9436 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9438 F.erase();
9439 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9440 continue;
9441 }
9442 }
9443 F.done();
9444
9445 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9446 if (Previous.empty()) {
9447 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9448 << IsFriend;
9449 for (auto &P : DiscardedCandidates)
9450 Diag(P.second->getLocation(),
9451 diag::note_dependent_function_template_spec_discard_reason)
9452 << P.first << IsFriend;
9453 return true;
9454 }
9455
9457 ExplicitTemplateArgs);
9458 return false;
9459}
9460
9462 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9463 LookupResult &Previous, bool QualifiedFriend) {
9464 // The set of function template specializations that could match this
9465 // explicit function template specialization.
9466 UnresolvedSet<8> Candidates;
9467 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9468 /*ForTakingAddress=*/false);
9469
9470 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9471 ConvertedTemplateArgs;
9472
9473 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9474 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9475 I != E; ++I) {
9476 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9477 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9478 // Only consider templates found within the same semantic lookup scope as
9479 // FD.
9480 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9482 continue;
9483
9484 QualType FT = FD->getType();
9485 // C++11 [dcl.constexpr]p8:
9486 // A constexpr specifier for a non-static member function that is not
9487 // a constructor declares that member function to be const.
9488 //
9489 // When matching a constexpr member function template specialization
9490 // against the primary template, we don't yet know whether the
9491 // specialization has an implicit 'const' (because we don't know whether
9492 // it will be a static member function until we know which template it
9493 // specializes). This rule was removed in C++14.
9494 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9495 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9497 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9498 if (OldMD && OldMD->isConst()) {
9499 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9501 EPI.TypeQuals.addConst();
9502 FT = Context.getFunctionType(FPT->getReturnType(),
9503 FPT->getParamTypes(), EPI);
9504 }
9505 }
9506
9508 if (ExplicitTemplateArgs)
9509 Args = *ExplicitTemplateArgs;
9510
9511 // C++ [temp.expl.spec]p11:
9512 // A trailing template-argument can be left unspecified in the
9513 // template-id naming an explicit function template specialization
9514 // provided it can be deduced from the function argument type.
9515 // Perform template argument deduction to determine whether we may be
9516 // specializing this template.
9517 // FIXME: It is somewhat wasteful to build
9518 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9519 FunctionDecl *Specialization = nullptr;
9521 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9522 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9524 // Template argument deduction failed; record why it failed, so
9525 // that we can provide nifty diagnostics.
9526 FailedCandidates.addCandidate().set(
9527 I.getPair(), FunTmpl->getTemplatedDecl(),
9528 MakeDeductionFailureInfo(Context, TDK, Info));
9529 (void)TDK;
9530 continue;
9531 }
9532
9533 // Target attributes are part of the cuda function signature, so
9534 // the deduced template's cuda target must match that of the
9535 // specialization. Given that C++ template deduction does not
9536 // take target attributes into account, we reject candidates
9537 // here that have a different target.
9538 if (LangOpts.CUDA &&
9539 CUDA().IdentifyTarget(Specialization,
9540 /* IgnoreImplicitHDAttr = */ true) !=
9541 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9542 FailedCandidates.addCandidate().set(
9543 I.getPair(), FunTmpl->getTemplatedDecl(),
9546 continue;
9547 }
9548
9549 // Record this candidate.
9550 if (ExplicitTemplateArgs)
9551 ConvertedTemplateArgs[Specialization] = std::move(Args);
9552 Candidates.addDecl(Specialization, I.getAccess());
9553 }
9554 }
9555
9556 // For a qualified friend declaration (with no explicit marker to indicate
9557 // that a template specialization was intended), note all (template and
9558 // non-template) candidates.
9559 if (QualifiedFriend && Candidates.empty()) {
9560 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9561 << FD->getDeclName() << FDLookupContext;
9562 // FIXME: We should form a single candidate list and diagnose all
9563 // candidates at once, to get proper sorting and limiting.
9564 for (auto *OldND : Previous) {
9565 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9566 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9567 }
9568 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9569 return true;
9570 }
9571
9572 // Find the most specialized function template.
9574 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9575 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9576 PDiag(diag::err_function_template_spec_ambiguous)
9577 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9578 PDiag(diag::note_function_template_spec_matched));
9579
9580 if (Result == Candidates.end())
9581 return true;
9582
9583 // Ignore access information; it doesn't figure into redeclaration checking.
9585
9586 if (const auto *PT = Specialization->getPrimaryTemplate();
9587 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9588 auto Message = DSA->getMessage();
9589 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9590 << PT << !Message.empty() << Message;
9591 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9592 }
9593
9594 // C++23 [except.spec]p13:
9595 // An exception specification is considered to be needed when:
9596 // - [...]
9597 // - the exception specification is compared to that of another declaration
9598 // (e.g., an explicit specialization or an overriding virtual function);
9599 // - [...]
9600 //
9601 // The exception specification of a defaulted function is evaluated as
9602 // described above only when needed; similarly, the noexcept-specifier of a
9603 // specialization of a function template or member function of a class
9604 // template is instantiated only when needed.
9605 //
9606 // The standard doesn't specify what the "comparison with another declaration"
9607 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9608 // not state which properties of an explicit specialization must match the
9609 // primary template.
9610 //
9611 // We assume that an explicit specialization must correspond with (per
9612 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9613 // the declaration produced by substitution into the function template.
9614 //
9615 // Since the determination whether two function declarations correspond does
9616 // not consider exception specification, we only need to instantiate it once
9617 // we determine the primary template when comparing types per
9618 // [basic.link]p11.1.
9619 auto *SpecializationFPT =
9620 Specialization->getType()->castAs<FunctionProtoType>();
9621 // If the function has a dependent exception specification, resolve it after
9622 // we have selected the primary template so we can check whether it matches.
9623 if (getLangOpts().CPlusPlus17 &&
9624 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9625 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9626 return true;
9627
9629 = Specialization->getTemplateSpecializationInfo();
9630 assert(SpecInfo && "Function template specialization info missing?");
9631
9632 // Note: do not overwrite location info if previous template
9633 // specialization kind was explicit.
9635 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9636 Specialization->setLocation(FD->getLocation());
9637 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9638 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9639 // function can differ from the template declaration with respect to
9640 // the constexpr specifier.
9641 // FIXME: We need an update record for this AST mutation.
9642 // FIXME: What if there are multiple such prior declarations (for instance,
9643 // from different modules)?
9644 Specialization->setConstexprKind(FD->getConstexprKind());
9645 }
9646
9647 // FIXME: Check if the prior specialization has a point of instantiation.
9648 // If so, we have run afoul of .
9649
9650 // If this is a friend declaration, then we're not really declaring
9651 // an explicit specialization.
9652 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9653
9654 // Check the scope of this explicit specialization.
9655 if (!isFriend &&
9657 Specialization->getPrimaryTemplate(),
9659 false))
9660 return true;
9661
9662 // C++ [temp.expl.spec]p6:
9663 // If a template, a member template or the member of a class template is
9664 // explicitly specialized then that specialization shall be declared
9665 // before the first use of that specialization that would cause an implicit
9666 // instantiation to take place, in every translation unit in which such a
9667 // use occurs; no diagnostic is required.
9668 bool HasNoEffect = false;
9669 if (!isFriend &&
9674 SpecInfo->getPointOfInstantiation(),
9675 HasNoEffect))
9676 return true;
9677
9678 // Mark the prior declaration as an explicit specialization, so that later
9679 // clients know that this is an explicit specialization.
9680 // A dependent friend specialization which has a definition should be treated
9681 // as explicit specialization, despite being invalid.
9682 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9683 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9684 // Since explicit specializations do not inherit '=delete' from their
9685 // primary function template - check if the 'specialization' that was
9686 // implicitly generated (during template argument deduction for partial
9687 // ordering) from the most specialized of all the function templates that
9688 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9689 // first check that it was implicitly generated during template argument
9690 // deduction by making sure it wasn't referenced, and then reset the deleted
9691 // flag to not-deleted, so that we can inherit that information from 'FD'.
9692 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9693 !Specialization->getCanonicalDecl()->isReferenced()) {
9694 // FIXME: This assert will not hold in the presence of modules.
9695 assert(
9696 Specialization->getCanonicalDecl() == Specialization &&
9697 "This must be the only existing declaration of this specialization");
9698 // FIXME: We need an update record for this AST mutation.
9699 Specialization->setDeletedAsWritten(false);
9700 }
9701 // FIXME: We need an update record for this AST mutation.
9704 }
9705
9706 // Turn the given function declaration into a function template
9707 // specialization, with the template arguments from the previous
9708 // specialization.
9709 // Take copies of (semantic and syntactic) template argument lists.
9711 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9712 FD->setFunctionTemplateSpecialization(
9713 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9715 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9716
9717 // A function template specialization inherits the target attributes
9718 // of its template. (We require the attributes explicitly in the
9719 // code to match, but a template may have implicit attributes by
9720 // virtue e.g. of being constexpr, and it passes these implicit
9721 // attributes on to its specializations.)
9722 if (LangOpts.CUDA)
9723 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9724
9725 // The "previous declaration" for this function template specialization is
9726 // the prior function template specialization.
9727 Previous.clear();
9728 Previous.addDecl(Specialization);
9729 return false;
9730}
9731
9732bool
9734 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9735 "Only for non-template members");
9736
9737 // Try to find the member we are instantiating.
9738 NamedDecl *FoundInstantiation = nullptr;
9739 NamedDecl *Instantiation = nullptr;
9740 NamedDecl *InstantiatedFrom = nullptr;
9741 MemberSpecializationInfo *MSInfo = nullptr;
9742
9743 if (Previous.empty()) {
9744 // Nowhere to look anyway.
9745 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9746 UnresolvedSet<8> Candidates;
9747 for (NamedDecl *Candidate : Previous) {
9748 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9749 // Ignore any candidates that aren't member functions.
9750 if (!Method)
9751 continue;
9752
9753 QualType Adjusted = Function->getType();
9754 if (!hasExplicitCallingConv(Adjusted))
9755 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9756 // Ignore any candidates with the wrong type.
9757 // This doesn't handle deduced return types, but both function
9758 // declarations should be undeduced at this point.
9759 // FIXME: The exception specification should probably be ignored when
9760 // comparing the types.
9761 if (!Context.hasSameType(Adjusted, Method->getType()))
9762 continue;
9763
9764 // Ignore any candidates with unsatisfied constraints.
9765 if (ConstraintSatisfaction Satisfaction;
9766 Method->getTrailingRequiresClause() &&
9767 (CheckFunctionConstraints(Method, Satisfaction,
9768 /*UsageLoc=*/Member->getLocation(),
9769 /*ForOverloadResolution=*/true) ||
9770 !Satisfaction.IsSatisfied))
9771 continue;
9772
9773 Candidates.addDecl(Candidate);
9774 }
9775
9776 // If we have no viable candidates left after filtering, we are done.
9777 if (Candidates.empty())
9778 return false;
9779
9780 // Find the function that is more constrained than every other function it
9781 // has been compared to.
9782 UnresolvedSetIterator Best = Candidates.begin();
9783 CXXMethodDecl *BestMethod = nullptr;
9784 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9785 I != E; ++I) {
9786 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9787 if (I == Best ||
9788 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9789 Best = I;
9790 BestMethod = Method;
9791 }
9792 }
9793
9794 FoundInstantiation = *Best;
9795 Instantiation = BestMethod;
9796 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9797 MSInfo = BestMethod->getMemberSpecializationInfo();
9798
9799 // Make sure the best candidate is more constrained than all of the others.
9800 bool Ambiguous = false;
9801 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9802 I != E; ++I) {
9803 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9804 if (I != Best &&
9805 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9806 Ambiguous = true;
9807 break;
9808 }
9809 }
9810
9811 if (Ambiguous) {
9812 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9813 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9814 for (NamedDecl *Candidate : Candidates) {
9815 Candidate = Candidate->getUnderlyingDecl();
9816 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9817 << Candidate;
9818 }
9819 return true;
9820 }
9821 } else if (isa<VarDecl>(Member)) {
9822 VarDecl *PrevVar;
9823 if (Previous.isSingleResult() &&
9824 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9825 if (PrevVar->isStaticDataMember()) {
9826 FoundInstantiation = Previous.getRepresentativeDecl();
9827 Instantiation = PrevVar;
9828 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9829 MSInfo = PrevVar->getMemberSpecializationInfo();
9830 }
9831 } else if (isa<RecordDecl>(Member)) {
9832 CXXRecordDecl *PrevRecord;
9833 if (Previous.isSingleResult() &&
9834 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9835 FoundInstantiation = Previous.getRepresentativeDecl();
9836 Instantiation = PrevRecord;
9837 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9838 MSInfo = PrevRecord->getMemberSpecializationInfo();
9839 }
9840 } else if (isa<EnumDecl>(Member)) {
9841 EnumDecl *PrevEnum;
9842 if (Previous.isSingleResult() &&
9843 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9844 FoundInstantiation = Previous.getRepresentativeDecl();
9845 Instantiation = PrevEnum;
9846 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9847 MSInfo = PrevEnum->getMemberSpecializationInfo();
9848 }
9849 }
9850
9851 if (!Instantiation) {
9852 // There is no previous declaration that matches. Since member
9853 // specializations are always out-of-line, the caller will complain about
9854 // this mismatch later.
9855 return false;
9856 }
9857
9858 // A member specialization in a friend declaration isn't really declaring
9859 // an explicit specialization, just identifying a specific (possibly implicit)
9860 // specialization. Don't change the template specialization kind.
9861 //
9862 // FIXME: Is this really valid? Other compilers reject.
9863 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9864 // Preserve instantiation information.
9865 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9866 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9867 cast<CXXMethodDecl>(InstantiatedFrom),
9869 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9870 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9871 cast<CXXRecordDecl>(InstantiatedFrom),
9873 }
9874
9875 Previous.clear();
9876 Previous.addDecl(FoundInstantiation);
9877 return false;
9878 }
9879
9880 // Make sure that this is a specialization of a member.
9881 if (!InstantiatedFrom) {
9882 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9883 << Member;
9884 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9885 return true;
9886 }
9887
9888 // C++ [temp.expl.spec]p6:
9889 // If a template, a member template or the member of a class template is
9890 // explicitly specialized then that specialization shall be declared
9891 // before the first use of that specialization that would cause an implicit
9892 // instantiation to take place, in every translation unit in which such a
9893 // use occurs; no diagnostic is required.
9894 assert(MSInfo && "Member specialization info missing?");
9895
9896 bool HasNoEffect = false;
9899 Instantiation,
9901 MSInfo->getPointOfInstantiation(),
9902 HasNoEffect))
9903 return true;
9904
9905 // Check the scope of this explicit specialization.
9907 InstantiatedFrom,
9908 Instantiation, Member->getLocation(),
9909 false))
9910 return true;
9911
9912 // Note that this member specialization is an "instantiation of" the
9913 // corresponding member of the original template.
9914 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9915 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9916 if (InstantiationFunction->getTemplateSpecializationKind() ==
9918 // Explicit specializations of member functions of class templates do not
9919 // inherit '=delete' from the member function they are specializing.
9920 if (InstantiationFunction->isDeleted()) {
9921 // FIXME: This assert will not hold in the presence of modules.
9922 assert(InstantiationFunction->getCanonicalDecl() ==
9923 InstantiationFunction);
9924 // FIXME: We need an update record for this AST mutation.
9925 InstantiationFunction->setDeletedAsWritten(false);
9926 }
9927 }
9928
9929 MemberFunction->setInstantiationOfMemberFunction(
9931 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9932 MemberVar->setInstantiationOfStaticDataMember(
9933 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9934 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9935 MemberClass->setInstantiationOfMemberClass(
9937 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9938 MemberEnum->setInstantiationOfMemberEnum(
9939 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9940 } else {
9941 llvm_unreachable("unknown member specialization kind");
9942 }
9943
9944 // Save the caller the trouble of having to figure out which declaration
9945 // this specialization matches.
9946 Previous.clear();
9947 Previous.addDecl(FoundInstantiation);
9948 return false;
9949}
9950
9951/// Complete the explicit specialization of a member of a class template by
9952/// updating the instantiated member to be marked as an explicit specialization.
9953///
9954/// \param OrigD The member declaration instantiated from the template.
9955/// \param Loc The location of the explicit specialization of the member.
9956template<typename DeclT>
9957static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9958 SourceLocation Loc) {
9959 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9960 return;
9961
9962 // FIXME: Inform AST mutation listeners of this AST mutation.
9963 // FIXME: If there are multiple in-class declarations of the member (from
9964 // multiple modules, or a declaration and later definition of a member type),
9965 // should we update all of them?
9966 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9967 OrigD->setLocation(Loc);
9968}
9969
9972 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9973 if (Instantiation == Member)
9974 return;
9975
9976 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9977 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9978 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9979 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9980 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9981 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9982 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9983 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9984 else
9985 llvm_unreachable("unknown member specialization kind");
9986}
9987
9988/// Check the scope of an explicit instantiation.
9989///
9990/// \returns true if a serious error occurs, false otherwise.
9992 SourceLocation InstLoc,
9993 bool WasQualifiedName) {
9995 DeclContext *CurContext = S.CurContext->getRedeclContext();
9996
9997 if (CurContext->isRecord()) {
9998 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9999 << D;
10000 return true;
10001 }
10002
10003 // C++11 [temp.explicit]p3:
10004 // An explicit instantiation shall appear in an enclosing namespace of its
10005 // template. If the name declared in the explicit instantiation is an
10006 // unqualified name, the explicit instantiation shall appear in the
10007 // namespace where its template is declared or, if that namespace is inline
10008 // (7.3.1), any namespace from its enclosing namespace set.
10009 //
10010 // This is DR275, which we do not retroactively apply to C++98/03.
10011 if (WasQualifiedName) {
10012 if (CurContext->Encloses(OrigContext))
10013 return false;
10014 } else {
10015 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10016 return false;
10017 }
10018
10019 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10020 if (WasQualifiedName)
10021 S.Diag(InstLoc,
10022 S.getLangOpts().CPlusPlus11?
10023 diag::err_explicit_instantiation_out_of_scope :
10024 diag::warn_explicit_instantiation_out_of_scope_0x)
10025 << D << NS;
10026 else
10027 S.Diag(InstLoc,
10028 S.getLangOpts().CPlusPlus11?
10029 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10030 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10031 << D << NS;
10032 } else
10033 S.Diag(InstLoc,
10034 S.getLangOpts().CPlusPlus11?
10035 diag::err_explicit_instantiation_must_be_global :
10036 diag::warn_explicit_instantiation_must_be_global_0x)
10037 << D;
10038 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10039 return false;
10040}
10041
10042/// Common checks for whether an explicit instantiation of \p D is valid.
10044 SourceLocation InstLoc,
10045 bool WasQualifiedName,
10047 // C++ [temp.explicit]p13:
10048 // An explicit instantiation declaration shall not name a specialization of
10049 // a template with internal linkage.
10052 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10053 return true;
10054 }
10055
10056 // C++11 [temp.explicit]p3: [DR 275]
10057 // An explicit instantiation shall appear in an enclosing namespace of its
10058 // template.
10059 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10060 return true;
10061
10062 return false;
10063}
10064
10065/// Determine whether the given scope specifier has a template-id in it.
10067 // C++11 [temp.explicit]p3:
10068 // If the explicit instantiation is for a member function, a member class
10069 // or a static data member of a class template specialization, the name of
10070 // the class template specialization in the qualified-id for the member
10071 // name shall be a simple-template-id.
10072 //
10073 // C++98 has the same restriction, just worded differently.
10074 for (NestedNameSpecifier NNS = SS.getScopeRep();
10076 /**/) {
10077 const Type *T = NNS.getAsType();
10079 return true;
10080 NNS = T->getPrefix();
10081 }
10082 return false;
10083}
10084
10085/// Make a dllexport or dllimport attr on a class template specialization take
10086/// effect.
10089 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10090 assert(A && "dllExportImportClassTemplateSpecialization called "
10091 "on Def without dllexport or dllimport");
10092
10093 // We reject explicit instantiations in class scope, so there should
10094 // never be any delayed exported classes to worry about.
10095 assert(S.DelayedDllExportClasses.empty() &&
10096 "delayed exports present at explicit instantiation");
10098
10099 // Propagate attribute to base class templates.
10100 for (auto &B : Def->bases()) {
10101 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10102 B.getType()->getAsCXXRecordDecl()))
10104 }
10105
10107}
10108
10110 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10111 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10112 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10113 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10114 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10115 // Find the class template we're specializing
10116 TemplateName Name = TemplateD.get();
10117 TemplateDecl *TD = Name.getAsTemplateDecl();
10118 // Check that the specialization uses the same tag kind as the
10119 // original template.
10121 assert(Kind != TagTypeKind::Enum &&
10122 "Invalid enum tag in class template explicit instantiation!");
10123
10124 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10125
10126 if (!ClassTemplate) {
10127 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10128 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10129 Diag(TD->getLocation(), diag::note_previous_use);
10130 return true;
10131 }
10132
10133 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10134 Kind, /*isDefinition*/false, KWLoc,
10135 ClassTemplate->getIdentifier())) {
10136 Diag(KWLoc, diag::err_use_with_wrong_tag)
10137 << ClassTemplate
10139 ClassTemplate->getTemplatedDecl()->getKindName());
10140 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10141 diag::note_previous_use);
10142 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10143 }
10144
10145 // C++0x [temp.explicit]p2:
10146 // There are two forms of explicit instantiation: an explicit instantiation
10147 // definition and an explicit instantiation declaration. An explicit
10148 // instantiation declaration begins with the extern keyword. [...]
10149 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10152
10154 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10155 // Check for dllexport class template instantiation declarations,
10156 // except for MinGW mode.
10157 for (const ParsedAttr &AL : Attr) {
10158 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10159 Diag(ExternLoc,
10160 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10161 Diag(AL.getLoc(), diag::note_attribute);
10162 break;
10163 }
10164 }
10165
10166 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10167 Diag(ExternLoc,
10168 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10169 Diag(A->getLocation(), diag::note_attribute);
10170 }
10171 }
10172
10173 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10174 // instantiation declarations for most purposes.
10175 bool DLLImportExplicitInstantiationDef = false;
10177 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10178 // Check for dllimport class template instantiation definitions.
10179 bool DLLImport =
10180 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10181 for (const ParsedAttr &AL : Attr) {
10182 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10183 DLLImport = true;
10184 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10185 // dllexport trumps dllimport here.
10186 DLLImport = false;
10187 break;
10188 }
10189 }
10190 if (DLLImport) {
10192 DLLImportExplicitInstantiationDef = true;
10193 }
10194 }
10195
10196 // Translate the parser's template argument list in our AST format.
10197 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10198 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10199
10200 // Check that the template argument list is well-formed for this
10201 // template.
10203 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10204 /*DefaultArgs=*/{}, false, CTAI,
10205 /*UpdateArgsWithConversions=*/true,
10206 /*ConstraintsNotSatisfied=*/nullptr))
10207 return true;
10208
10209 // Find the class template specialization declaration that
10210 // corresponds to these arguments.
10211 void *InsertPos = nullptr;
10213 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10214
10215 TemplateSpecializationKind PrevDecl_TSK
10216 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10217
10218 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10219 Context.getTargetInfo().getTriple().isOSCygMing()) {
10220 // Check for dllexport class template instantiation definitions in MinGW
10221 // mode, if a previous declaration of the instantiation was seen.
10222 for (const ParsedAttr &AL : Attr) {
10223 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10224 Diag(AL.getLoc(),
10225 diag::warn_attribute_dllexport_explicit_instantiation_def);
10226 break;
10227 }
10228 }
10229 }
10230
10231 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10232 SS.isSet(), TSK))
10233 return true;
10234
10236
10237 bool HasNoEffect = false;
10238 if (PrevDecl) {
10239 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10240 PrevDecl, PrevDecl_TSK,
10241 PrevDecl->getPointOfInstantiation(),
10242 HasNoEffect))
10243 return PrevDecl;
10244
10245 // Even though HasNoEffect == true means that this explicit instantiation
10246 // has no effect on semantics, we go on to put its syntax in the AST.
10247
10248 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10249 PrevDecl_TSK == TSK_Undeclared) {
10250 // Since the only prior class template specialization with these
10251 // arguments was referenced but not declared, reuse that
10252 // declaration node as our own, updating the source location
10253 // for the template name to reflect our new declaration.
10254 // (Other source locations will be updated later.)
10255 Specialization = PrevDecl;
10256 Specialization->setLocation(TemplateNameLoc);
10257 PrevDecl = nullptr;
10258 }
10259
10260 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10261 DLLImportExplicitInstantiationDef) {
10262 // The new specialization might add a dllimport attribute.
10263 HasNoEffect = false;
10264 }
10265 }
10266
10267 if (!Specialization) {
10268 // Create a new class template specialization declaration node for
10269 // this explicit specialization.
10271 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10272 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10274
10275 // A MSInheritanceAttr attached to the previous declaration must be
10276 // propagated to the new node prior to instantiation.
10277 if (PrevDecl) {
10278 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10279 auto *Clone = A->clone(getASTContext());
10280 Clone->setInherited(true);
10281 Specialization->addAttr(Clone);
10282 Consumer.AssignInheritanceModel(Specialization);
10283 }
10284 }
10285
10286 if (!HasNoEffect && !PrevDecl) {
10287 // Insert the new specialization.
10288 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10289 }
10290 }
10291
10292 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10293
10294 // Set source locations for keywords.
10295 Specialization->setExternKeywordLoc(ExternLoc);
10296 Specialization->setTemplateKeywordLoc(TemplateLoc);
10297 Specialization->setBraceRange(SourceRange());
10298
10299 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10302
10303 // Add the explicit instantiation into its lexical context. However,
10304 // since explicit instantiations are never found by name lookup, we
10305 // just put it into the declaration context directly.
10306 Specialization->setLexicalDeclContext(CurContext);
10307 CurContext->addDecl(Specialization);
10308
10309 // Syntax is now OK, so return if it has no other effect on semantics.
10310 if (HasNoEffect) {
10311 // Set the template specialization kind.
10312 Specialization->setTemplateSpecializationKind(TSK);
10313 return Specialization;
10314 }
10315
10316 // C++ [temp.explicit]p3:
10317 // A definition of a class template or class member template
10318 // shall be in scope at the point of the explicit instantiation of
10319 // the class template or class member template.
10320 //
10321 // This check comes when we actually try to perform the
10322 // instantiation.
10324 = cast_or_null<ClassTemplateSpecializationDecl>(
10325 Specialization->getDefinition());
10326 if (!Def)
10328 /*Complain=*/true,
10329 CTAI.StrictPackMatch);
10330 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10331 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10332 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10333 }
10334
10335 // Instantiate the members of this class template specialization.
10336 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10337 Specialization->getDefinition());
10338 if (Def) {
10340 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10341 // TSK_ExplicitInstantiationDefinition
10342 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10344 DLLImportExplicitInstantiationDef)) {
10345 // FIXME: Need to notify the ASTMutationListener that we did this.
10347
10348 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10349 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10350 // An explicit instantiation definition can add a dll attribute to a
10351 // template with a previous instantiation declaration. MinGW doesn't
10352 // allow this.
10353 auto *A = cast<InheritableAttr>(
10355 A->setInherited(true);
10356 Def->addAttr(A);
10358 }
10359 }
10360
10361 // Fix a TSK_ImplicitInstantiation followed by a
10362 // TSK_ExplicitInstantiationDefinition
10363 bool NewlyDLLExported =
10364 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10365 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10366 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10367 // An explicit instantiation definition can add a dll attribute to a
10368 // template with a previous implicit instantiation. MinGW doesn't allow
10369 // this. We limit clang to only adding dllexport, to avoid potentially
10370 // strange codegen behavior. For example, if we extend this conditional
10371 // to dllimport, and we have a source file calling a method on an
10372 // implicitly instantiated template class instance and then declaring a
10373 // dllimport explicit instantiation definition for the same template
10374 // class, the codegen for the method call will not respect the dllimport,
10375 // while it will with cl. The Def will already have the DLL attribute,
10376 // since the Def and Specialization will be the same in the case of
10377 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10378 // attribute to the Specialization; we just need to make it take effect.
10379 assert(Def == Specialization &&
10380 "Def and Specialization should match for implicit instantiation");
10382 }
10383
10384 // In MinGW mode, export the template instantiation if the declaration
10385 // was marked dllexport.
10386 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10387 Context.getTargetInfo().getTriple().isOSCygMing() &&
10388 PrevDecl->hasAttr<DLLExportAttr>()) {
10390 }
10391
10392 // Set the template specialization kind. Make sure it is set before
10393 // instantiating the members which will trigger ASTConsumer callbacks.
10394 Specialization->setTemplateSpecializationKind(TSK);
10395 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10396 } else {
10397
10398 // Set the template specialization kind.
10399 Specialization->setTemplateSpecializationKind(TSK);
10400 }
10401
10402 return Specialization;
10403}
10404
10407 SourceLocation TemplateLoc, unsigned TagSpec,
10408 SourceLocation KWLoc, CXXScopeSpec &SS,
10409 IdentifierInfo *Name, SourceLocation NameLoc,
10410 const ParsedAttributesView &Attr) {
10411
10412 bool Owned = false;
10413 bool IsDependent = false;
10414 Decl *TagD =
10415 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10416 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10417 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10418 false, TypeResult(), /*IsTypeSpecifier*/ false,
10419 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10420 .get();
10421 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10422
10423 if (!TagD)
10424 return true;
10425
10426 TagDecl *Tag = cast<TagDecl>(TagD);
10427 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10428
10429 if (Tag->isInvalidDecl())
10430 return true;
10431
10433 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10434 if (!Pattern) {
10435 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10436 << Context.getCanonicalTagType(Record);
10437 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10438 return true;
10439 }
10440
10441 // C++0x [temp.explicit]p2:
10442 // If the explicit instantiation is for a class or member class, the
10443 // elaborated-type-specifier in the declaration shall include a
10444 // simple-template-id.
10445 //
10446 // C++98 has the same restriction, just worded differently.
10448 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10449 << Record << SS.getRange();
10450
10451 // C++0x [temp.explicit]p2:
10452 // There are two forms of explicit instantiation: an explicit instantiation
10453 // definition and an explicit instantiation declaration. An explicit
10454 // instantiation declaration begins with the extern keyword. [...]
10458
10459 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10460
10461 // Verify that it is okay to explicitly instantiate here.
10462 CXXRecordDecl *PrevDecl
10463 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10464 if (!PrevDecl && Record->getDefinition())
10465 PrevDecl = Record;
10466 if (PrevDecl) {
10468 bool HasNoEffect = false;
10469 assert(MSInfo && "No member specialization information?");
10470 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10471 PrevDecl,
10473 MSInfo->getPointOfInstantiation(),
10474 HasNoEffect))
10475 return true;
10476 if (HasNoEffect)
10477 return TagD;
10478 }
10479
10480 CXXRecordDecl *RecordDef
10481 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10482 if (!RecordDef) {
10483 // C++ [temp.explicit]p3:
10484 // A definition of a member class of a class template shall be in scope
10485 // at the point of an explicit instantiation of the member class.
10486 CXXRecordDecl *Def
10487 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10488 if (!Def) {
10489 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10490 << 0 << Record->getDeclName() << Record->getDeclContext();
10491 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10492 << Pattern;
10493 return true;
10494 } else {
10495 if (InstantiateClass(NameLoc, Record, Def,
10497 TSK))
10498 return true;
10499
10500 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10501 if (!RecordDef)
10502 return true;
10503 }
10504 }
10505
10506 // Instantiate all of the members of the class.
10507 InstantiateClassMembers(NameLoc, RecordDef,
10509
10511 MarkVTableUsed(NameLoc, RecordDef, true);
10512
10513 // FIXME: We don't have any representation for explicit instantiations of
10514 // member classes. Such a representation is not needed for compilation, but it
10515 // should be available for clients that want to see all of the declarations in
10516 // the source code.
10517 return TagD;
10518}
10519
10521 SourceLocation ExternLoc,
10522 SourceLocation TemplateLoc,
10523 Declarator &D) {
10524 // Explicit instantiations always require a name.
10525 // TODO: check if/when DNInfo should replace Name.
10527 DeclarationName Name = NameInfo.getName();
10528 if (!Name) {
10529 if (!D.isInvalidType())
10531 diag::err_explicit_instantiation_requires_name)
10533
10534 return true;
10535 }
10536
10537 // Get the innermost enclosing declaration scope.
10538 S = S->getDeclParent();
10539
10540 // Determine the type of the declaration.
10542 QualType R = T->getType();
10543 if (R.isNull())
10544 return true;
10545
10546 // C++ [dcl.stc]p1:
10547 // A storage-class-specifier shall not be specified in [...] an explicit
10548 // instantiation (14.7.2) directive.
10550 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10551 << Name;
10552 return true;
10553 } else if (D.getDeclSpec().getStorageClassSpec()
10555 // Complain about then remove the storage class specifier.
10556 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10558
10560 }
10561
10562 // C++0x [temp.explicit]p1:
10563 // [...] An explicit instantiation of a function template shall not use the
10564 // inline or constexpr specifiers.
10565 // Presumably, this also applies to member functions of class templates as
10566 // well.
10570 diag::err_explicit_instantiation_inline :
10571 diag::warn_explicit_instantiation_inline_0x)
10574 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10575 // not already specified.
10577 diag::err_explicit_instantiation_constexpr);
10578
10579 // A deduction guide is not on the list of entities that can be explicitly
10580 // instantiated.
10582 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10583 << /*explicit instantiation*/ 0;
10584 return true;
10585 }
10586
10587 // C++0x [temp.explicit]p2:
10588 // There are two forms of explicit instantiation: an explicit instantiation
10589 // definition and an explicit instantiation declaration. An explicit
10590 // instantiation declaration begins with the extern keyword. [...]
10594
10595 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10597 /*ObjectType=*/QualType());
10598
10599 if (!R->isFunctionType()) {
10600 // C++ [temp.explicit]p1:
10601 // A [...] static data member of a class template can be explicitly
10602 // instantiated from the member definition associated with its class
10603 // template.
10604 // C++1y [temp.explicit]p1:
10605 // A [...] variable [...] template specialization can be explicitly
10606 // instantiated from its template.
10607 if (Previous.isAmbiguous())
10608 return true;
10609
10610 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10611 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10612
10613 if (!PrevTemplate) {
10614 if (!Prev || !Prev->isStaticDataMember()) {
10615 // We expect to see a static data member here.
10616 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10617 << Name;
10618 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10619 P != PEnd; ++P)
10620 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10621 return true;
10622 }
10623
10625 // FIXME: Check for explicit specialization?
10627 diag::err_explicit_instantiation_data_member_not_instantiated)
10628 << Prev;
10629 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10630 // FIXME: Can we provide a note showing where this was declared?
10631 return true;
10632 }
10633 } else {
10634 // Explicitly instantiate a variable template.
10635
10636 // C++1y [dcl.spec.auto]p6:
10637 // ... A program that uses auto or decltype(auto) in a context not
10638 // explicitly allowed in this section is ill-formed.
10639 //
10640 // This includes auto-typed variable template instantiations.
10641 if (R->isUndeducedType()) {
10642 Diag(T->getTypeLoc().getBeginLoc(),
10643 diag::err_auto_not_allowed_var_inst);
10644 return true;
10645 }
10646
10648 // C++1y [temp.explicit]p3:
10649 // If the explicit instantiation is for a variable, the unqualified-id
10650 // in the declaration shall be a template-id.
10652 diag::err_explicit_instantiation_without_template_id)
10653 << PrevTemplate;
10654 Diag(PrevTemplate->getLocation(),
10655 diag::note_explicit_instantiation_here);
10656 return true;
10657 }
10658
10659 // Translate the parser's template argument list into our AST format.
10660 TemplateArgumentListInfo TemplateArgs =
10662
10663 DeclResult Res =
10664 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10665 TemplateArgs, /*SetWrittenArgs=*/true);
10666 if (Res.isInvalid())
10667 return true;
10668
10669 if (!Res.isUsable()) {
10670 // We somehow specified dependent template arguments in an explicit
10671 // instantiation. This should probably only happen during error
10672 // recovery.
10673 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10674 return true;
10675 }
10676
10677 // Ignore access control bits, we don't need them for redeclaration
10678 // checking.
10679 Prev = cast<VarDecl>(Res.get());
10680 }
10681
10682 // C++0x [temp.explicit]p2:
10683 // If the explicit instantiation is for a member function, a member class
10684 // or a static data member of a class template specialization, the name of
10685 // the class template specialization in the qualified-id for the member
10686 // name shall be a simple-template-id.
10687 //
10688 // C++98 has the same restriction, just worded differently.
10689 //
10690 // This does not apply to variable template specializations, where the
10691 // template-id is in the unqualified-id instead.
10692 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10694 diag::ext_explicit_instantiation_without_qualified_id)
10695 << Prev << D.getCXXScopeSpec().getRange();
10696
10697 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10698
10699 // Verify that it is okay to explicitly instantiate here.
10702 bool HasNoEffect = false;
10704 PrevTSK, POI, HasNoEffect))
10705 return true;
10706
10707 if (!HasNoEffect) {
10708 // Instantiate static data member or variable template.
10710 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10711 VTSD->setExternKeywordLoc(ExternLoc);
10712 VTSD->setTemplateKeywordLoc(TemplateLoc);
10713 }
10714
10715 // Merge attributes.
10717 if (PrevTemplate)
10718 ProcessAPINotes(Prev);
10719
10722 }
10723
10724 // Check the new variable specialization against the parsed input.
10725 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10726 Diag(T->getTypeLoc().getBeginLoc(),
10727 diag::err_invalid_var_template_spec_type)
10728 << 0 << PrevTemplate << R << Prev->getType();
10729 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10730 << 2 << PrevTemplate->getDeclName();
10731 return true;
10732 }
10733
10734 // FIXME: Create an ExplicitInstantiation node?
10735 return (Decl*) nullptr;
10736 }
10737
10738 // If the declarator is a template-id, translate the parser's template
10739 // argument list into our AST format.
10740 bool HasExplicitTemplateArgs = false;
10741 TemplateArgumentListInfo TemplateArgs;
10743 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10744 HasExplicitTemplateArgs = true;
10745 }
10746
10747 // C++ [temp.explicit]p1:
10748 // A [...] function [...] can be explicitly instantiated from its template.
10749 // A member function [...] of a class template can be explicitly
10750 // instantiated from the member definition associated with its class
10751 // template.
10752 UnresolvedSet<8> TemplateMatches;
10753 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10755 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10756 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10757 P != PEnd; ++P) {
10758 NamedDecl *Prev = *P;
10759 if (!HasExplicitTemplateArgs) {
10760 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10761 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10762 /*AdjustExceptionSpec*/true);
10763 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10764 if (Method->getPrimaryTemplate()) {
10765 TemplateMatches.addDecl(Method, P.getAccess());
10766 } else {
10767 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10768 C.FoundDecl = P.getPair();
10769 C.Function = Method;
10770 C.Viable = true;
10772 if (Method->getTrailingRequiresClause() &&
10774 /*ForOverloadResolution=*/true) ||
10775 !S.IsSatisfied)) {
10776 C.Viable = false;
10778 }
10779 }
10780 }
10781 }
10782 }
10783
10784 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10785 if (!FunTmpl)
10786 continue;
10787
10788 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10789 FunctionDecl *Specialization = nullptr;
10791 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10792 Specialization, Info);
10794 // Keep track of almost-matches.
10795 FailedTemplateCandidates.addCandidate().set(
10796 P.getPair(), FunTmpl->getTemplatedDecl(),
10797 MakeDeductionFailureInfo(Context, TDK, Info));
10798 (void)TDK;
10799 continue;
10800 }
10801
10802 // Target attributes are part of the cuda function signature, so
10803 // the cuda target of the instantiated function must match that of its
10804 // template. Given that C++ template deduction does not take
10805 // target attributes into account, we reject candidates here that
10806 // have a different target.
10807 if (LangOpts.CUDA &&
10808 CUDA().IdentifyTarget(Specialization,
10809 /* IgnoreImplicitHDAttr = */ true) !=
10810 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10811 FailedTemplateCandidates.addCandidate().set(
10812 P.getPair(), FunTmpl->getTemplatedDecl(),
10815 continue;
10816 }
10817
10818 TemplateMatches.addDecl(Specialization, P.getAccess());
10819 }
10820
10821 FunctionDecl *Specialization = nullptr;
10822 if (!NonTemplateMatches.empty()) {
10823 unsigned Msg = 0;
10824 OverloadCandidateDisplayKind DisplayKind;
10826 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10827 Best)) {
10828 case OR_Success:
10829 case OR_Deleted:
10830 Specialization = cast<FunctionDecl>(Best->Function);
10831 break;
10832 case OR_Ambiguous:
10833 Msg = diag::err_explicit_instantiation_ambiguous;
10834 DisplayKind = OCD_AmbiguousCandidates;
10835 break;
10837 Msg = diag::err_explicit_instantiation_no_candidate;
10838 DisplayKind = OCD_AllCandidates;
10839 break;
10840 }
10841 if (Msg) {
10842 PartialDiagnostic Diag = PDiag(Msg) << Name;
10843 NonTemplateMatches.NoteCandidates(
10844 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10845 {});
10846 return true;
10847 }
10848 }
10849
10850 if (!Specialization) {
10851 // Find the most specialized function template specialization.
10853 TemplateMatches.begin(), TemplateMatches.end(),
10854 FailedTemplateCandidates, D.getIdentifierLoc(),
10855 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10856 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10857 PDiag(diag::note_explicit_instantiation_candidate));
10858
10859 if (Result == TemplateMatches.end())
10860 return true;
10861
10862 // Ignore access control bits, we don't need them for redeclaration checking.
10864 }
10865
10866 // C++11 [except.spec]p4
10867 // In an explicit instantiation an exception-specification may be specified,
10868 // but is not required.
10869 // If an exception-specification is specified in an explicit instantiation
10870 // directive, it shall be compatible with the exception-specifications of
10871 // other declarations of that function.
10872 if (auto *FPT = R->getAs<FunctionProtoType>())
10873 if (FPT->hasExceptionSpec()) {
10874 unsigned DiagID =
10875 diag::err_mismatched_exception_spec_explicit_instantiation;
10876 if (getLangOpts().MicrosoftExt)
10877 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10879 PDiag(DiagID) << Specialization->getType(),
10880 PDiag(diag::note_explicit_instantiation_here),
10881 Specialization->getType()->getAs<FunctionProtoType>(),
10882 Specialization->getLocation(), FPT, D.getBeginLoc());
10883 // In Microsoft mode, mismatching exception specifications just cause a
10884 // warning.
10885 if (!getLangOpts().MicrosoftExt && Result)
10886 return true;
10887 }
10888
10889 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10891 diag::err_explicit_instantiation_member_function_not_instantiated)
10893 << (Specialization->getTemplateSpecializationKind() ==
10895 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10896 return true;
10897 }
10898
10899 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10900 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10901 PrevDecl = Specialization;
10902
10903 if (PrevDecl) {
10904 bool HasNoEffect = false;
10906 PrevDecl,
10908 PrevDecl->getPointOfInstantiation(),
10909 HasNoEffect))
10910 return true;
10911
10912 // FIXME: We may still want to build some representation of this
10913 // explicit specialization.
10914 if (HasNoEffect)
10915 return (Decl*) nullptr;
10916 }
10917
10918 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10919 // functions
10920 // valarray<size_t>::valarray(size_t) and
10921 // valarray<size_t>::~valarray()
10922 // that it declared to have internal linkage with the internal_linkage
10923 // attribute. Ignore the explicit instantiation declaration in this case.
10924 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10926 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10927 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10928 RD->isInStdNamespace())
10929 return (Decl*) nullptr;
10930 }
10931
10934
10935 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10936 // instantiation declarations.
10938 Specialization->hasAttr<DLLImportAttr>() &&
10939 Context.getTargetInfo().getCXXABI().isMicrosoft())
10941
10942 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10943
10944 if (Specialization->isDefined()) {
10945 // Let the ASTConsumer know that this function has been explicitly
10946 // instantiated now, and its linkage might have changed.
10947 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10948 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10950
10951 // C++0x [temp.explicit]p2:
10952 // If the explicit instantiation is for a member function, a member class
10953 // or a static data member of a class template specialization, the name of
10954 // the class template specialization in the qualified-id for the member
10955 // name shall be a simple-template-id.
10956 //
10957 // C++98 has the same restriction, just worded differently.
10958 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10959 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10960 D.getCXXScopeSpec().isSet() &&
10963 diag::ext_explicit_instantiation_without_qualified_id)
10965
10967 *this,
10968 FunTmpl ? (NamedDecl *)FunTmpl
10969 : Specialization->getInstantiatedFromMemberFunction(),
10970 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10971
10972 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10973 return (Decl*) nullptr;
10974}
10975
10977 const CXXScopeSpec &SS,
10978 const IdentifierInfo *Name,
10979 SourceLocation TagLoc,
10980 SourceLocation NameLoc) {
10981 // This has to hold, because SS is expected to be defined.
10982 assert(Name && "Expected a name in a dependent tag");
10983
10985 if (!NNS)
10986 return true;
10987
10989
10990 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10991 Diag(NameLoc, diag::err_dependent_tag_decl)
10992 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
10993 return true;
10994 }
10995
10996 // Create the resulting type.
10998 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10999
11000 // Create type-source location information for this type.
11001 TypeLocBuilder TLB;
11003 TL.setElaboratedKeywordLoc(TagLoc);
11005 TL.setNameLoc(NameLoc);
11007}
11008
11010 const CXXScopeSpec &SS,
11011 const IdentifierInfo &II,
11012 SourceLocation IdLoc,
11013 ImplicitTypenameContext IsImplicitTypename) {
11014 if (SS.isInvalid())
11015 return true;
11016
11017 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11018 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11019 << FixItHint::CreateRemoval(TypenameLoc);
11020
11022 TypeSourceInfo *TSI = nullptr;
11023 QualType T =
11026 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11027 /*DeducedTSTContext=*/true);
11028 if (T.isNull())
11029 return true;
11030 return CreateParsedType(T, TSI);
11031}
11032
11035 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11036 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11037 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11038 ASTTemplateArgsPtr TemplateArgsIn,
11039 SourceLocation RAngleLoc) {
11040 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11041 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11042 ? diag::compat_cxx11_typename_outside_of_template
11043 : diag::compat_pre_cxx11_typename_outside_of_template)
11044 << FixItHint::CreateRemoval(TypenameLoc);
11045
11046 // Strangely, non-type results are not ignored by this lookup, so the
11047 // program is ill-formed if it finds an injected-class-name.
11048 if (TypenameLoc.isValid()) {
11049 auto *LookupRD =
11050 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11051 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11052 Diag(TemplateIILoc,
11053 diag::ext_out_of_line_qualified_id_type_names_constructor)
11054 << TemplateII << 0 /*injected-class-name used as template name*/
11055 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11056 }
11057 }
11058
11059 // Translate the parser's template argument list in our AST format.
11060 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11061 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11062
11066 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11067 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11068 if (T.isNull())
11069 return true;
11070
11071 // Provide source-location information for the template specialization type.
11072 TypeLocBuilder Builder;
11074 = Builder.push<TemplateSpecializationTypeLoc>(T);
11075 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11076 TemplateIILoc, TemplateArgs);
11077 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11078 return CreateParsedType(T, TSI);
11079}
11080
11081/// Determine whether this failed name lookup should be treated as being
11082/// disabled by a usage of std::enable_if.
11084 SourceRange &CondRange, Expr *&Cond) {
11085 // We must be looking for a ::type...
11086 if (!II.isStr("type"))
11087 return false;
11088
11089 // ... within an explicitly-written template specialization...
11091 return false;
11092
11093 // FIXME: Look through sugar.
11094 auto EnableIfTSTLoc =
11096 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11097 return false;
11098 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11099
11100 // ... which names a complete class template declaration...
11101 const TemplateDecl *EnableIfDecl =
11102 EnableIfTST->getTemplateName().getAsTemplateDecl();
11103 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11104 return false;
11105
11106 // ... called "enable_if".
11107 const IdentifierInfo *EnableIfII =
11108 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11109 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11110 return false;
11111
11112 // Assume the first template argument is the condition.
11113 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11114
11115 // Dig out the condition.
11116 Cond = nullptr;
11117 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11119 return true;
11120
11121 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11122
11123 // Ignore Boolean literals; they add no value.
11124 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11125 Cond = nullptr;
11126
11127 return true;
11128}
11129
11132 SourceLocation KeywordLoc,
11133 NestedNameSpecifierLoc QualifierLoc,
11134 const IdentifierInfo &II,
11135 SourceLocation IILoc,
11136 TypeSourceInfo **TSI,
11137 bool DeducedTSTContext) {
11138 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11139 DeducedTSTContext);
11140 if (T.isNull())
11141 return QualType();
11142
11143 TypeLocBuilder TLB;
11145 auto TL = TLB.push<DependentNameTypeLoc>(T);
11146 TL.setElaboratedKeywordLoc(KeywordLoc);
11147 TL.setQualifierLoc(QualifierLoc);
11148 TL.setNameLoc(IILoc);
11151 TL.setElaboratedKeywordLoc(KeywordLoc);
11152 TL.setQualifierLoc(QualifierLoc);
11153 TL.setNameLoc(IILoc);
11154 } else if (isa<TemplateTypeParmType>(T)) {
11155 // FIXME: There might be a 'typename' keyword here, but we just drop it
11156 // as it can't be represented.
11157 assert(!QualifierLoc);
11158 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11159 } else if (isa<TagType>(T)) {
11160 auto TL = TLB.push<TagTypeLoc>(T);
11161 TL.setElaboratedKeywordLoc(KeywordLoc);
11162 TL.setQualifierLoc(QualifierLoc);
11163 TL.setNameLoc(IILoc);
11164 } else if (isa<TypedefType>(T)) {
11165 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11166 } else {
11167 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11168 }
11169 *TSI = TLB.getTypeSourceInfo(Context, T);
11170 return T;
11171}
11172
11173/// Build the type that describes a C++ typename specifier,
11174/// e.g., "typename T::type".
11177 SourceLocation KeywordLoc,
11178 NestedNameSpecifierLoc QualifierLoc,
11179 const IdentifierInfo &II,
11180 SourceLocation IILoc, bool DeducedTSTContext) {
11181 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11182
11183 CXXScopeSpec SS;
11184 SS.Adopt(QualifierLoc);
11185
11186 DeclContext *Ctx = nullptr;
11187 if (QualifierLoc) {
11188 Ctx = computeDeclContext(SS);
11189 if (!Ctx) {
11190 // If the nested-name-specifier is dependent and couldn't be
11191 // resolved to a type, build a typename type.
11192 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11193 return Context.getDependentNameType(Keyword,
11194 QualifierLoc.getNestedNameSpecifier(),
11195 &II);
11196 }
11197
11198 // If the nested-name-specifier refers to the current instantiation,
11199 // the "typename" keyword itself is superfluous. In C++03, the
11200 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11201 // allows such extraneous "typename" keywords, and we retroactively
11202 // apply this DR to C++03 code with only a warning. In any case we continue.
11203
11204 if (RequireCompleteDeclContext(SS, Ctx))
11205 return QualType();
11206 }
11207
11208 DeclarationName Name(&II);
11209 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11210 if (Ctx)
11211 LookupQualifiedName(Result, Ctx, SS);
11212 else
11213 LookupName(Result, CurScope);
11214 unsigned DiagID = 0;
11215 Decl *Referenced = nullptr;
11216 switch (Result.getResultKind()) {
11218 // If we're looking up 'type' within a template named 'enable_if', produce
11219 // a more specific diagnostic.
11220 SourceRange CondRange;
11221 Expr *Cond = nullptr;
11222 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11223 // If we have a condition, narrow it down to the specific failed
11224 // condition.
11225 if (Cond) {
11226 Expr *FailedCond;
11227 std::string FailedDescription;
11228 std::tie(FailedCond, FailedDescription) =
11230
11231 Diag(FailedCond->getExprLoc(),
11232 diag::err_typename_nested_not_found_requirement)
11233 << FailedDescription
11234 << FailedCond->getSourceRange();
11235 return QualType();
11236 }
11237
11238 Diag(CondRange.getBegin(),
11239 diag::err_typename_nested_not_found_enable_if)
11240 << Ctx << CondRange;
11241 return QualType();
11242 }
11243
11244 DiagID = Ctx ? diag::err_typename_nested_not_found
11245 : diag::err_unknown_typename;
11246 break;
11247 }
11248
11250 // We found a using declaration that is a value. Most likely, the using
11251 // declaration itself is meant to have the 'typename' keyword.
11252 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11253 IILoc);
11254 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11255 << Name << Ctx << FullRange;
11256 if (UnresolvedUsingValueDecl *Using
11257 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11258 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11259 Diag(Loc, diag::note_using_value_decl_missing_typename)
11260 << FixItHint::CreateInsertion(Loc, "typename ");
11261 }
11262 }
11263 // Fall through to create a dependent typename type, from which we can
11264 // recover better.
11265 [[fallthrough]];
11266
11268 // Okay, it's a member of an unknown instantiation.
11269 return Context.getDependentNameType(Keyword,
11270 QualifierLoc.getNestedNameSpecifier(),
11271 &II);
11272
11274 // FXIME: Missing support for UsingShadowDecl on this path?
11275 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11276 // C++ [class.qual]p2:
11277 // In a lookup in which function names are not ignored and the
11278 // nested-name-specifier nominates a class C, if the name specified
11279 // after the nested-name-specifier, when looked up in C, is the
11280 // injected-class-name of C [...] then the name is instead considered
11281 // to name the constructor of class C.
11282 //
11283 // Unlike in an elaborated-type-specifier, function names are not ignored
11284 // in typename-specifier lookup. However, they are ignored in all the
11285 // contexts where we form a typename type with no keyword (that is, in
11286 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11287 //
11288 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11289 // ignore functions, but that appears to be an oversight.
11294 Type, IILoc);
11295 // FIXME: This appears to be the only case where a template type parameter
11296 // can have an elaborated keyword. We should preserve it somehow.
11299 assert(!QualifierLoc);
11301 }
11302 return Context.getTypeDeclType(
11303 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11304 }
11305
11306 // C++ [dcl.type.simple]p2:
11307 // A type-specifier of the form
11308 // typename[opt] nested-name-specifier[opt] template-name
11309 // is a placeholder for a deduced class type [...].
11310 if (getLangOpts().CPlusPlus17) {
11311 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11312 if (!DeducedTSTContext) {
11313 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11314 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11315 Diag(IILoc, diag::err_dependent_deduced_tst)
11317 << QualType(Qualifier.getAsType(), 0);
11318 else
11319 Diag(IILoc, diag::err_deduced_tst)
11322 return QualType();
11323 }
11324 TemplateName Name = Context.getQualifiedTemplateName(
11325 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11326 TemplateName(TD));
11327 return Context.getDeducedTemplateSpecializationType(
11328 Keyword, Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11329 }
11330 }
11331
11332 DiagID = Ctx ? diag::err_typename_nested_not_type
11333 : diag::err_typename_not_type;
11334 Referenced = Result.getFoundDecl();
11335 break;
11336
11338 DiagID = Ctx ? diag::err_typename_nested_not_type
11339 : diag::err_typename_not_type;
11340 Referenced = *Result.begin();
11341 break;
11342
11344 return QualType();
11345 }
11346
11347 // If we get here, it's because name lookup did not find a
11348 // type. Emit an appropriate diagnostic and return an error.
11349 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11350 IILoc);
11351 if (Ctx)
11352 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11353 else
11354 Diag(IILoc, DiagID) << FullRange << Name;
11355 if (Referenced)
11356 Diag(Referenced->getLocation(),
11357 Ctx ? diag::note_typename_member_refers_here
11358 : diag::note_typename_refers_here)
11359 << Name;
11360 return QualType();
11361}
11362
11363namespace {
11364 // See Sema::RebuildTypeInCurrentInstantiation
11365 class CurrentInstantiationRebuilder
11366 : public TreeTransform<CurrentInstantiationRebuilder> {
11367 SourceLocation Loc;
11368 DeclarationName Entity;
11369
11370 public:
11372
11373 CurrentInstantiationRebuilder(Sema &SemaRef,
11374 SourceLocation Loc,
11375 DeclarationName Entity)
11376 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11377 Loc(Loc), Entity(Entity) { }
11378
11379 /// Determine whether the given type \p T has already been
11380 /// transformed.
11381 ///
11382 /// For the purposes of type reconstruction, a type has already been
11383 /// transformed if it is NULL or if it is not dependent.
11384 bool AlreadyTransformed(QualType T) {
11385 return T.isNull() || !T->isInstantiationDependentType();
11386 }
11387
11388 /// Returns the location of the entity whose type is being
11389 /// rebuilt.
11390 SourceLocation getBaseLocation() { return Loc; }
11391
11392 /// Returns the name of the entity whose type is being rebuilt.
11393 DeclarationName getBaseEntity() { return Entity; }
11394
11395 /// Sets the "base" location and entity when that
11396 /// information is known based on another transformation.
11397 void setBase(SourceLocation Loc, DeclarationName Entity) {
11398 this->Loc = Loc;
11399 this->Entity = Entity;
11400 }
11401
11402 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11403 // Lambdas never need to be transformed.
11404 return E;
11405 }
11406 };
11407} // end anonymous namespace
11408
11410 SourceLocation Loc,
11411 DeclarationName Name) {
11412 if (!T || !T->getType()->isInstantiationDependentType())
11413 return T;
11414
11415 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11416 return Rebuilder.TransformType(T);
11417}
11418
11420 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11421 DeclarationName());
11422 return Rebuilder.TransformExpr(E);
11423}
11424
11426 if (SS.isInvalid())
11427 return true;
11428
11430 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11431 DeclarationName());
11433 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11434 if (!Rebuilt)
11435 return true;
11436
11437 SS.Adopt(Rebuilt);
11438 return false;
11439}
11440
11442 TemplateParameterList *Params) {
11443 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11444 Decl *Param = Params->getParam(I);
11445
11446 // There is nothing to rebuild in a type parameter.
11447 if (isa<TemplateTypeParmDecl>(Param))
11448 continue;
11449
11450 // Rebuild the template parameter list of a template template parameter.
11452 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11454 TTP->getTemplateParameters()))
11455 return true;
11456
11457 continue;
11458 }
11459
11460 // Rebuild the type of a non-type template parameter.
11462 TypeSourceInfo *NewTSI
11464 NTTP->getLocation(),
11465 NTTP->getDeclName());
11466 if (!NewTSI)
11467 return true;
11468
11469 if (NewTSI->getType()->isUndeducedType()) {
11470 // C++17 [temp.dep.expr]p3:
11471 // An id-expression is type-dependent if it contains
11472 // - an identifier associated by name lookup with a non-type
11473 // template-parameter declared with a type that contains a
11474 // placeholder type (7.1.7.4),
11475 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11476 }
11477
11478 if (NewTSI != NTTP->getTypeSourceInfo()) {
11479 NTTP->setTypeSourceInfo(NewTSI);
11480 NTTP->setType(NewTSI->getType());
11481 }
11482 }
11483
11484 return false;
11485}
11486
11487std::string
11489 const TemplateArgumentList &Args) {
11490 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11491}
11492
11493std::string
11495 const TemplateArgument *Args,
11496 unsigned NumArgs) {
11497 SmallString<128> Str;
11498 llvm::raw_svector_ostream Out(Str);
11499
11500 if (!Params || Params->size() == 0 || NumArgs == 0)
11501 return std::string();
11502
11503 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11504 if (I >= NumArgs)
11505 break;
11506
11507 if (I == 0)
11508 Out << "[with ";
11509 else
11510 Out << ", ";
11511
11512 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11513 Out << Id->getName();
11514 } else {
11515 Out << '$' << I;
11516 }
11517
11518 Out << " = ";
11519 Args[I].print(getPrintingPolicy(), Out,
11521 getPrintingPolicy(), Params, I));
11522 }
11523
11524 Out << ']';
11525 return std::string(Out.str());
11526}
11527
11529 CachedTokens &Toks) {
11530 if (!FD)
11531 return;
11532
11533 auto LPT = std::make_unique<LateParsedTemplate>();
11534
11535 // Take tokens to avoid allocations
11536 LPT->Toks.swap(Toks);
11537 LPT->D = FnD;
11538 LPT->FPO = getCurFPFeatures();
11539 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11540
11541 FD->setLateTemplateParsed(true);
11542}
11543
11545 if (!FD)
11546 return;
11547 FD->setLateTemplateParsed(false);
11548}
11549
11551 DeclContext *DC = CurContext;
11552
11553 while (DC) {
11554 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11555 const FunctionDecl *FD = RD->isLocalClass();
11556 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11557 } else if (DC->isTranslationUnit() || DC->isNamespace())
11558 return false;
11559
11560 DC = DC->getParent();
11561 }
11562 return false;
11563}
11564
11565namespace {
11566/// Walk the path from which a declaration was instantiated, and check
11567/// that every explicit specialization along that path is visible. This enforces
11568/// C++ [temp.expl.spec]/6:
11569///
11570/// If a template, a member template or a member of a class template is
11571/// explicitly specialized then that specialization shall be declared before
11572/// the first use of that specialization that would cause an implicit
11573/// instantiation to take place, in every translation unit in which such a
11574/// use occurs; no diagnostic is required.
11575///
11576/// and also C++ [temp.class.spec]/1:
11577///
11578/// A partial specialization shall be declared before the first use of a
11579/// class template specialization that would make use of the partial
11580/// specialization as the result of an implicit or explicit instantiation
11581/// in every translation unit in which such a use occurs; no diagnostic is
11582/// required.
11583class ExplicitSpecializationVisibilityChecker {
11584 Sema &S;
11585 SourceLocation Loc;
11588
11589public:
11590 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11592 : S(S), Loc(Loc), Kind(Kind) {}
11593
11594 void check(NamedDecl *ND) {
11595 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11596 return checkImpl(FD);
11597 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11598 return checkImpl(RD);
11599 if (auto *VD = dyn_cast<VarDecl>(ND))
11600 return checkImpl(VD);
11601 if (auto *ED = dyn_cast<EnumDecl>(ND))
11602 return checkImpl(ED);
11603 }
11604
11605private:
11606 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11607 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11608 : Sema::MissingImportKind::ExplicitSpecialization;
11609 const bool Recover = true;
11610
11611 // If we got a custom set of modules (because only a subset of the
11612 // declarations are interesting), use them, otherwise let
11613 // diagnoseMissingImport intelligently pick some.
11614 if (Modules.empty())
11615 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11616 else
11617 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11618 }
11619
11620 bool CheckMemberSpecialization(const NamedDecl *D) {
11621 return Kind == Sema::AcceptableKind::Visible
11624 }
11625
11626 bool CheckExplicitSpecialization(const NamedDecl *D) {
11627 return Kind == Sema::AcceptableKind::Visible
11630 }
11631
11632 bool CheckDeclaration(const NamedDecl *D) {
11633 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11635 }
11636
11637 // Check a specific declaration. There are three problematic cases:
11638 //
11639 // 1) The declaration is an explicit specialization of a template
11640 // specialization.
11641 // 2) The declaration is an explicit specialization of a member of an
11642 // templated class.
11643 // 3) The declaration is an instantiation of a template, and that template
11644 // is an explicit specialization of a member of a templated class.
11645 //
11646 // We don't need to go any deeper than that, as the instantiation of the
11647 // surrounding class / etc is not triggered by whatever triggered this
11648 // instantiation, and thus should be checked elsewhere.
11649 template<typename SpecDecl>
11650 void checkImpl(SpecDecl *Spec) {
11651 bool IsHiddenExplicitSpecialization = false;
11652 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11653 // Some invalid friend declarations are written as specializations but are
11654 // instantiated implicitly.
11655 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11656 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11657 if (SpecKind == TSK_ExplicitSpecialization) {
11658 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11659 ? !CheckMemberSpecialization(Spec)
11660 : !CheckExplicitSpecialization(Spec);
11661 } else {
11662 checkInstantiated(Spec);
11663 }
11664
11665 if (IsHiddenExplicitSpecialization)
11666 diagnose(Spec->getMostRecentDecl(), false);
11667 }
11668
11669 void checkInstantiated(FunctionDecl *FD) {
11670 if (auto *TD = FD->getPrimaryTemplate())
11671 checkTemplate(TD);
11672 }
11673
11674 void checkInstantiated(CXXRecordDecl *RD) {
11675 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11676 if (!SD)
11677 return;
11678
11679 auto From = SD->getSpecializedTemplateOrPartial();
11680 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11681 checkTemplate(TD);
11682 else if (auto *TD =
11683 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11684 if (!CheckDeclaration(TD))
11685 diagnose(TD, true);
11686 checkTemplate(TD);
11687 }
11688 }
11689
11690 void checkInstantiated(VarDecl *RD) {
11691 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11692 if (!SD)
11693 return;
11694
11695 auto From = SD->getSpecializedTemplateOrPartial();
11696 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11697 checkTemplate(TD);
11698 else if (auto *TD =
11699 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11700 if (!CheckDeclaration(TD))
11701 diagnose(TD, true);
11702 checkTemplate(TD);
11703 }
11704 }
11705
11706 void checkInstantiated(EnumDecl *FD) {}
11707
11708 template<typename TemplDecl>
11709 void checkTemplate(TemplDecl *TD) {
11710 if (TD->isMemberSpecialization()) {
11711 if (!CheckMemberSpecialization(TD))
11712 diagnose(TD->getMostRecentDecl(), false);
11713 }
11714 }
11715};
11716} // end anonymous namespace
11717
11719 if (!getLangOpts().Modules)
11720 return;
11721
11722 ExplicitSpecializationVisibilityChecker(*this, Loc,
11724 .check(Spec);
11725}
11726
11728 NamedDecl *Spec) {
11729 if (!getLangOpts().CPlusPlusModules)
11730 return checkSpecializationVisibility(Loc, Spec);
11731
11732 ExplicitSpecializationVisibilityChecker(*this, Loc,
11734 .check(Spec);
11735}
11736
11739 return N->getLocation();
11740 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11742 return FD->getLocation();
11745 return N->getLocation();
11746 }
11747 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11748 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11749 continue;
11750 return CSC.PointOfInstantiation;
11751 }
11752 return N->getLocation();
11753}
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
APSInt & getComplexIntImag()
Definition APValue.h:527
ValueKind getKind() const
Definition APValue.h:461
APFixedPoint & getFixedPoint()
Definition APValue.h:511
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isMemberPointer() const
Definition APValue.h:477
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isNullPointer() const
Definition APValue.cpp:1019
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
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:3890
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition Attr.h:44
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2373
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2391
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2441
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2434
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2409
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2415
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2421
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8137
Pointer to a block type.
Definition TypeBase.h:3540
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
BuiltinTemplateKind getBuiltinTemplateKind() const
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition Expr.cpp:2099
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:735
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3864
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2020
base_class_range bases()
Definition DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2061
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1069
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:438
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4371
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
bool isNamespace() const
Definition DeclBase.h:2198
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1371
ValueDecl * getDecl()
Definition Expr.h:1338
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:244
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:234
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:364
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:813
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2700
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
bool hasEllipsis() const
Definition DeclSpec.h:2699
bool isInvalidType() const
Definition DeclSpec.h:2688
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4059
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3504
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4009
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4099
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4430
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4225
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateName(TemplateName Template)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4004
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4267
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:827
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3065
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:4042
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4265
Represents a member of a struct/union/class.
Definition Decl.h:3157
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:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1072
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Represents a function declaration or definition.
Definition Decl.h:1999
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2475
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4146
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4455
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4113
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2539
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
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:4319
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2361
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4842
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
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:4800
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3907
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
Describes an C or C++ initializer list.
Definition Expr.h:5233
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3615
Represents a linkage specification.
Definition DeclCXX.h:3015
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:365
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4398
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
QualType getPointeeType() const
Definition TypeBase.h:3669
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:260
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
NamedDecl * getMostRecentDecl()
Definition Decl.h:500
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:591
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.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7847
Represents a pointer to an Objective C object.
Definition TypeBase.h:7903
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1416
bool isVarDeclReference() const
Definition ExprCXX.h:3296
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3312
bool isConceptReference() const
Definition ExprCXX.h:3285
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3331
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:4357
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8103
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
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:8470
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3549
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3633
Represents a struct/union/class.
Definition Decl.h:4309
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5309
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
QualType getPointeeType() const
Definition TypeBase.h:3589
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
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:13504
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
A RAII object to temporarily push a declaration context.
Definition Sema.h:3476
Whether and why a template name is required in this lookup.
Definition Sema.h:11349
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11357
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12367
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12400
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7676
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13438
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12944
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9287
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9291
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9299
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9294
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:9601
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:1445
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)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
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:4134
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:2049
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:11320
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:11900
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:11903
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:11907
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1283
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:925
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition Sema.h:11310
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12073
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12091
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12081
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12101
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:11370
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11377
@ None
This is not assumed to be a template name.
Definition Sema.h:11372
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11374
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:11303
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:168
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:920
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14275
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14263
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14272
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14266
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14290
const LangOptions & getLangOpts() const
Definition Sema.h:918
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition Sema.h:14716
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1282
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1281
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
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:1418
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
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:15286
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ASTConsumer & Consumer
Definition Sema.h:1284
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4630
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:6696
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6675
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 RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11347
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:509
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:11530
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11540
@ TPC_FriendFunctionTemplate
Definition Sema.h:11538
@ TPC_ClassTemplateMember
Definition Sema.h:11536
@ TPC_FunctionTemplate
Definition Sema.h:11535
@ TPC_FriendClassTemplate
Definition Sema.h:11537
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11539
friend class InitializationSequence
Definition Sema.h:1560
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6246
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6383
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1275
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3469
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11312
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:143
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:9610
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12787
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8609
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:358
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:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4658
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
StringRef getKindName() const
Definition Decl.h:3904
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:4921
TagKind getTagKind() const
Definition Decl.h:3908
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:678
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3685
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:223
Represents a declaration of a type.
Definition Decl.h:3510
const Type * getTypeForDecl() const
Definition Decl.h:3535
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3544
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:913
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:6175
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBooleanType() const
Definition TypeBase.h:9008
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isRValueReferenceType() const
Definition TypeBase.h:8554
bool isVoidPointerType() const
Definition Type.cpp:712
bool isArrayType() const
Definition TypeBase.h:8621
bool isPointerType() const
Definition TypeBase.h:8522
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:471
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8699
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isLValueReferenceType() const
Definition TypeBase.h:8550
bool isBitIntType() const
Definition TypeBase.h:8787
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2056
bool isMemberPointerType() const
Definition TypeBase.h:8603
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
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:4904
bool isPointerOrReferenceType() const
Definition TypeBase.h:8526
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isVectorType() const
Definition TypeBase.h:8661
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
QualType getUnderlyingType() const
Definition Decl.h:3614
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
QualType desugar() const
Definition Type.cpp:4041
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1210
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3384
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:787
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5980
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3940
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
Represents a variable declaration or definition.
Definition Decl.h:925
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2907
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2800
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Represents a GCC generic vector type.
Definition TypeBase.h:4173
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.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:913
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Extern
Definition Specifiers.h:251
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:448
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5888
@ Enum
The "enum" keyword.
Definition TypeBase.h:5902
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:366
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:414
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:418
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:420
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5863
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5881
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2247
CharacterLiteralKind
Definition Expr.h:1603
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5349
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3276
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3241
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11938
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:11934
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:11927
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:11924
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11924
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12961
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13068
A stack object to be created when performing template instantiation.
Definition Sema.h:13152
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13312
NamedDecl * Previous
Definition Sema.h:353
Location information for a TemplateArgument.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009