clang 19.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"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Scope.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/StringExtras.h"
42
43#include <iterator>
44#include <optional>
45using namespace clang;
46using namespace sema;
47
48// Exported for use by Parser.
51 unsigned N) {
52 if (!N) return SourceRange();
53 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
54}
55
56unsigned Sema::getTemplateDepth(Scope *S) const {
57 unsigned Depth = 0;
58
59 // Each template parameter scope represents one level of template parameter
60 // depth.
61 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
62 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
63 ++Depth;
64 }
65
66 // Note that there are template parameters with the given depth.
67 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
68
69 // Look for parameters of an enclosing generic lambda. We don't create a
70 // template parameter scope for these.
72 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
73 if (!LSI->TemplateParams.empty()) {
74 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
75 break;
76 }
77 if (LSI->GLTemplateParameterList) {
78 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
79 break;
80 }
81 }
82 }
83
84 // Look for parameters of an enclosing terse function template. We don't
85 // create a template parameter scope for these either.
86 for (const InventedTemplateParameterInfo &Info :
88 if (!Info.TemplateParams.empty()) {
89 ParamsAtDepth(Info.AutoTemplateParameterDepth);
90 break;
91 }
92 }
93
94 return Depth;
95}
96
97/// \brief Determine whether the declaration found is acceptable as the name
98/// of a template and, if so, return that template declaration. Otherwise,
99/// returns null.
100///
101/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
102/// is true. In all other cases it will return a TemplateDecl (or null).
104 bool AllowFunctionTemplates,
105 bool AllowDependent) {
106 D = D->getUnderlyingDecl();
107
108 if (isa<TemplateDecl>(D)) {
109 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
110 return nullptr;
111
112 return D;
113 }
114
115 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
116 // C++ [temp.local]p1:
117 // Like normal (non-template) classes, class templates have an
118 // injected-class-name (Clause 9). The injected-class-name
119 // can be used with or without a template-argument-list. When
120 // it is used without a template-argument-list, it is
121 // equivalent to the injected-class-name followed by the
122 // template-parameters of the class template enclosed in
123 // <>. When it is used with a template-argument-list, it
124 // refers to the specified class template specialization,
125 // which could be the current specialization or another
126 // specialization.
127 if (Record->isInjectedClassName()) {
128 Record = cast<CXXRecordDecl>(Record->getDeclContext());
129 if (Record->getDescribedClassTemplate())
130 return Record->getDescribedClassTemplate();
131
132 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
133 return Spec->getSpecializedTemplate();
134 }
135
136 return nullptr;
137 }
138
139 // 'using Dependent::foo;' can resolve to a template name.
140 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
141 // injected-class-name).
142 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
143 return D;
144
145 return nullptr;
146}
147
149 bool AllowFunctionTemplates,
150 bool AllowDependent) {
151 LookupResult::Filter filter = R.makeFilter();
152 while (filter.hasNext()) {
153 NamedDecl *Orig = filter.next();
154 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
155 filter.erase();
156 }
157 filter.done();
158}
159
161 bool AllowFunctionTemplates,
162 bool AllowDependent,
163 bool AllowNonTemplateFunctions) {
164 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
165 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
166 return true;
167 if (AllowNonTemplateFunctions &&
168 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
169 return true;
170 }
171
172 return false;
173}
174
176 CXXScopeSpec &SS,
177 bool hasTemplateKeyword,
178 const UnqualifiedId &Name,
179 ParsedType ObjectTypePtr,
180 bool EnteringContext,
181 TemplateTy &TemplateResult,
182 bool &MemberOfUnknownSpecialization,
183 bool Disambiguation) {
184 assert(getLangOpts().CPlusPlus && "No template names in C!");
185
186 DeclarationName TName;
187 MemberOfUnknownSpecialization = false;
188
189 switch (Name.getKind()) {
191 TName = DeclarationName(Name.Identifier);
192 break;
193
196 Name.OperatorFunctionId.Operator);
197 break;
198
200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201 break;
202
203 default:
204 return TNK_Non_template;
205 }
206
207 QualType ObjectType = ObjectTypePtr.get();
208
209 AssumedTemplateKind AssumedTemplate;
210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212 MemberOfUnknownSpecialization, SourceLocation(),
213 &AssumedTemplate,
214 /*AllowTypoCorrection=*/!Disambiguation))
215 return TNK_Non_template;
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238 if (isa<FunctionTemplateDecl>(FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
265 TemplateName Template;
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
277 } else {
278 if (!D) {
280 assert(D && "unambiguous result is not a template name");
281 }
282
283 if (isa<UnresolvedUsingValueDecl>(D)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
289 TemplateDecl *TD = cast<TemplateDecl>(D);
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (SS.isSet() && !SS.isInvalid()) {
294 NestedNameSpecifier *Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296 Template);
297 }
298
299 if (isa<FunctionTemplateDecl>(TD)) {
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
304 } else {
305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308 TemplateKind =
309 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
310 isa<ConceptDecl>(TD) ? TNK_Concept_template :
312 }
313 }
314
315 TemplateResult = TemplateTy::make(Template);
316 return TemplateKind;
317}
318
320 SourceLocation NameLoc, CXXScopeSpec &SS,
321 ParsedTemplateTy *Template /*=nullptr*/) {
322 bool MemberOfUnknownSpecialization = false;
323
324 // We could use redeclaration lookup here, but we don't need to: the
325 // syntactic form of a deduction guide is enough to identify it even
326 // if we can't look up the template name at all.
327 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
328 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
329 /*EnteringContext*/ false,
330 MemberOfUnknownSpecialization))
331 return false;
332
333 if (R.empty()) return false;
334 if (R.isAmbiguous()) {
335 // FIXME: Diagnose an ambiguity if we find at least one template.
337 return false;
338 }
339
340 // We only treat template-names that name type templates as valid deduction
341 // guide names.
343 if (!TD || !getAsTypeTemplateDecl(TD))
344 return false;
345
346 if (Template)
347 *Template = TemplateTy::make(TemplateName(TD));
348 return true;
349}
350
352 SourceLocation IILoc,
353 Scope *S,
354 const CXXScopeSpec *SS,
355 TemplateTy &SuggestedTemplate,
356 TemplateNameKind &SuggestedKind) {
357 // We can't recover unless there's a dependent scope specifier preceding the
358 // template name.
359 // FIXME: Typo correction?
360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
362 return false;
363
364 // The code is missing a 'template' keyword prior to the dependent template
365 // name.
367 Diag(IILoc, diag::err_template_kw_missing)
368 << Qualifier << II.getName()
369 << FixItHint::CreateInsertion(IILoc, "template ");
370 SuggestedTemplate
372 SuggestedKind = TNK_Dependent_template_name;
373 return true;
374}
375
377 Scope *S, CXXScopeSpec &SS,
378 QualType ObjectType,
379 bool EnteringContext,
380 bool &MemberOfUnknownSpecialization,
381 RequiredTemplateKind RequiredTemplate,
383 bool AllowTypoCorrection) {
384 if (ATK)
386
387 if (SS.isInvalid())
388 return true;
389
390 Found.setTemplateNameLookup(true);
391
392 // Determine where to perform name lookup
393 MemberOfUnknownSpecialization = false;
394 DeclContext *LookupCtx = nullptr;
395 bool IsDependent = false;
396 if (!ObjectType.isNull()) {
397 // This nested-name-specifier occurs in a member access expression, e.g.,
398 // x->B::f, and we are looking into the type of the object.
399 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
400 LookupCtx = computeDeclContext(ObjectType);
401 IsDependent = !LookupCtx && ObjectType->isDependentType();
402 assert((IsDependent || !ObjectType->isIncompleteType() ||
403 !ObjectType->getAs<TagType>() ||
404 ObjectType->castAs<TagType>()->isBeingDefined()) &&
405 "Caller should have completed object type");
406
407 // Template names cannot appear inside an Objective-C class or object type
408 // or a vector type.
409 //
410 // FIXME: This is wrong. For example:
411 //
412 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
413 // Vec<int> vi;
414 // vi.Vec<int>::~Vec<int>();
415 //
416 // ... should be accepted but we will not treat 'Vec' as a template name
417 // here. The right thing to do would be to check if the name is a valid
418 // vector component name, and look up a template name if not. And similarly
419 // for lookups into Objective-C class and object types, where the same
420 // problem can arise.
421 if (ObjectType->isObjCObjectOrInterfaceType() ||
422 ObjectType->isVectorType()) {
423 Found.clear();
424 return false;
425 }
426 } else if (SS.isNotEmpty()) {
427 // This nested-name-specifier occurs after another nested-name-specifier,
428 // so long into the context associated with the prior nested-name-specifier.
429 LookupCtx = computeDeclContext(SS, EnteringContext);
430 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
431
432 // The declaration context must be complete.
433 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
434 return true;
435 }
436
437 bool ObjectTypeSearchedInScope = false;
438 bool AllowFunctionTemplatesInLookup = true;
439 if (LookupCtx) {
440 // Perform "qualified" name lookup into the declaration context we
441 // computed, which is either the type of the base of a member access
442 // expression or the declaration context associated with a prior
443 // nested-name-specifier.
444 LookupQualifiedName(Found, LookupCtx);
445
446 // FIXME: The C++ standard does not clearly specify what happens in the
447 // case where the object type is dependent, and implementations vary. In
448 // Clang, we treat a name after a . or -> as a template-name if lookup
449 // finds a non-dependent member or member of the current instantiation that
450 // is a type template, or finds no such members and lookup in the context
451 // of the postfix-expression finds a type template. In the latter case, the
452 // name is nonetheless dependent, and we may resolve it to a member of an
453 // unknown specialization when we come to instantiate the template.
454 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
455 }
456
457 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
458 // C++ [basic.lookup.classref]p1:
459 // In a class member access expression (5.2.5), if the . or -> token is
460 // immediately followed by an identifier followed by a <, the
461 // identifier must be looked up to determine whether the < is the
462 // beginning of a template argument list (14.2) or a less-than operator.
463 // The identifier is first looked up in the class of the object
464 // expression. If the identifier is not found, it is then looked up in
465 // the context of the entire postfix-expression and shall name a class
466 // template.
467 if (S)
468 LookupName(Found, S);
469
470 if (!ObjectType.isNull()) {
471 // FIXME: We should filter out all non-type templates here, particularly
472 // variable templates and concepts. But the exclusion of alias templates
473 // and template template parameters is a wording defect.
474 AllowFunctionTemplatesInLookup = false;
475 ObjectTypeSearchedInScope = true;
476 }
477
478 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
479 }
480
481 if (Found.isAmbiguous())
482 return false;
483
484 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
485 !RequiredTemplate.hasTemplateKeyword()) {
486 // C++2a [temp.names]p2:
487 // A name is also considered to refer to a template if it is an
488 // unqualified-id followed by a < and name lookup finds either one or more
489 // functions or finds nothing.
490 //
491 // To keep our behavior consistent, we apply the "finds nothing" part in
492 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
493 // successfully form a call to an undeclared template-id.
494 bool AllFunctions =
495 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
496 return isa<FunctionDecl>(ND->getUnderlyingDecl());
497 });
498 if (AllFunctions || (Found.empty() && !IsDependent)) {
499 // If lookup found any functions, or if this is a name that can only be
500 // used for a function, then strongly assume this is a function
501 // template-id.
502 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
505 Found.clear();
506 return false;
507 }
508 }
509
510 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
511 // If we did not find any names, and this is not a disambiguation, attempt
512 // to correct any typos.
513 DeclarationName Name = Found.getLookupName();
514 Found.clear();
515 // Simple filter callback that, for keywords, only accepts the C++ *_cast
516 DefaultFilterCCC FilterCCC{};
517 FilterCCC.WantTypeSpecifiers = false;
518 FilterCCC.WantExpressionKeywords = false;
519 FilterCCC.WantRemainingKeywords = false;
520 FilterCCC.WantCXXNamedCasts = true;
521 if (TypoCorrection Corrected =
522 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
523 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
524 if (auto *ND = Corrected.getFoundDecl())
525 Found.addDecl(ND);
527 if (Found.isAmbiguous()) {
528 Found.clear();
529 } else if (!Found.empty()) {
530 Found.setLookupName(Corrected.getCorrection());
531 if (LookupCtx) {
532 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
533 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
534 Name.getAsString() == CorrectedStr;
535 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
536 << Name << LookupCtx << DroppedSpecifier
537 << SS.getRange());
538 } else {
539 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
540 }
541 }
542 }
543 }
544
545 NamedDecl *ExampleLookupResult =
546 Found.empty() ? nullptr : Found.getRepresentativeDecl();
547 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
548 if (Found.empty()) {
549 if (IsDependent) {
550 MemberOfUnknownSpecialization = true;
551 return false;
552 }
553
554 // If a 'template' keyword was used, a lookup that finds only non-template
555 // names is an error.
556 if (ExampleLookupResult && RequiredTemplate) {
557 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
558 << Found.getLookupName() << SS.getRange()
559 << RequiredTemplate.hasTemplateKeyword()
560 << RequiredTemplate.getTemplateKeywordLoc();
561 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
562 diag::note_template_kw_refers_to_non_template)
563 << Found.getLookupName();
564 return true;
565 }
566
567 return false;
568 }
569
570 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
572 // C++03 [basic.lookup.classref]p1:
573 // [...] If the lookup in the class of the object expression finds a
574 // template, the name is also looked up in the context of the entire
575 // postfix-expression and [...]
576 //
577 // Note: C++11 does not perform this second lookup.
578 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
580 FoundOuter.setTemplateNameLookup(true);
581 LookupName(FoundOuter, S);
582 // FIXME: We silently accept an ambiguous lookup here, in violation of
583 // [basic.lookup]/1.
584 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
585
586 NamedDecl *OuterTemplate;
587 if (FoundOuter.empty()) {
588 // - if the name is not found, the name found in the class of the
589 // object expression is used, otherwise
590 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
591 !(OuterTemplate =
592 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
593 // - if the name is found in the context of the entire
594 // postfix-expression and does not name a class template, the name
595 // found in the class of the object expression is used, otherwise
596 FoundOuter.clear();
597 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
598 // - if the name found is a class template, it must refer to the same
599 // entity as the one found in the class of the object expression,
600 // otherwise the program is ill-formed.
601 if (!Found.isSingleResult() ||
603 OuterTemplate->getCanonicalDecl()) {
604 Diag(Found.getNameLoc(),
605 diag::ext_nested_name_member_ref_lookup_ambiguous)
606 << Found.getLookupName()
607 << ObjectType;
609 diag::note_ambig_member_ref_object_type)
610 << ObjectType;
611 Diag(FoundOuter.getFoundDecl()->getLocation(),
612 diag::note_ambig_member_ref_scope);
613
614 // Recover by taking the template that we found in the object
615 // expression's type.
616 }
617 }
618 }
619
620 return false;
621}
622
626 if (TemplateName.isInvalid())
627 return;
628
629 DeclarationNameInfo NameInfo;
630 CXXScopeSpec SS;
631 LookupNameKind LookupKind;
632
633 DeclContext *LookupCtx = nullptr;
634 NamedDecl *Found = nullptr;
635 bool MissingTemplateKeyword = false;
636
637 // Figure out what name we looked up.
638 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
639 NameInfo = DRE->getNameInfo();
640 SS.Adopt(DRE->getQualifierLoc());
641 LookupKind = LookupOrdinaryName;
642 Found = DRE->getFoundDecl();
643 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
644 NameInfo = ME->getMemberNameInfo();
645 SS.Adopt(ME->getQualifierLoc());
646 LookupKind = LookupMemberName;
647 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
648 Found = ME->getMemberDecl();
649 } else if (auto *DSDRE =
650 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
651 NameInfo = DSDRE->getNameInfo();
652 SS.Adopt(DSDRE->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else if (auto *DSME =
655 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
656 NameInfo = DSME->getMemberNameInfo();
657 SS.Adopt(DSME->getQualifierLoc());
658 MissingTemplateKeyword = true;
659 } else {
660 llvm_unreachable("unexpected kind of potential template name");
661 }
662
663 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
664 // was missing.
665 if (MissingTemplateKeyword) {
666 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
667 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
668 return;
669 }
670
671 // Try to correct the name by looking for templates and C++ named casts.
672 struct TemplateCandidateFilter : CorrectionCandidateCallback {
673 Sema &S;
674 TemplateCandidateFilter(Sema &S) : S(S) {
675 WantTypeSpecifiers = false;
676 WantExpressionKeywords = false;
677 WantRemainingKeywords = false;
678 WantCXXNamedCasts = true;
679 };
680 bool ValidateCandidate(const TypoCorrection &Candidate) override {
681 if (auto *ND = Candidate.getCorrectionDecl())
682 return S.getAsTemplateNameDecl(ND);
683 return Candidate.isKeyword();
684 }
685
686 std::unique_ptr<CorrectionCandidateCallback> clone() override {
687 return std::make_unique<TemplateCandidateFilter>(*this);
688 }
689 };
690
691 DeclarationName Name = NameInfo.getName();
692 TemplateCandidateFilter CCC(*this);
693 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
694 CTK_ErrorRecovery, LookupCtx)) {
695 auto *ND = Corrected.getFoundDecl();
696 if (ND)
697 ND = getAsTemplateNameDecl(ND);
698 if (ND || Corrected.isKeyword()) {
699 if (LookupCtx) {
700 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702 Name.getAsString() == CorrectedStr;
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_member_template_id_suggest)
705 << Name << LookupCtx << DroppedSpecifier
706 << SS.getRange(), false);
707 } else {
708 diagnoseTypo(Corrected,
709 PDiag(diag::err_non_template_in_template_id_suggest)
710 << Name, false);
711 }
712 if (Found)
713 Diag(Found->getLocation(),
714 diag::note_non_template_in_template_id_found);
715 return;
716 }
717 }
718
719 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
720 << Name << SourceRange(Less, Greater);
721 if (Found)
722 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
723}
724
725/// ActOnDependentIdExpression - Handle a dependent id-expression that
726/// was just parsed. This is only possible with an explicit scope
727/// specifier naming a dependent type.
730 SourceLocation TemplateKWLoc,
731 const DeclarationNameInfo &NameInfo,
732 bool isAddressOfOperand,
733 const TemplateArgumentListInfo *TemplateArgs) {
735
736 // C++11 [expr.prim.general]p12:
737 // An id-expression that denotes a non-static data member or non-static
738 // member function of a class can only be used:
739 // (...)
740 // - if that id-expression denotes a non-static data member and it
741 // appears in an unevaluated operand.
742 //
743 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
744 // CXXDependentScopeMemberExpr. The former can instantiate to either
745 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
746 // always a MemberExpr.
747 bool MightBeCxx11UnevalField =
748 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
749
750 // Check if the nested name specifier is an enum type.
751 bool IsEnum = false;
752 if (NestedNameSpecifier *NNS = SS.getScopeRep())
753 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
754
755 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
756 isa<CXXMethodDecl>(DC) &&
757 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
758 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
759
760 // Since the 'this' expression is synthesized, we don't need to
761 // perform the double-lookup check.
762 NamedDecl *FirstQualifierInScope = nullptr;
763
765 Context, /*This=*/nullptr, ThisType,
766 /*IsArrow=*/!Context.getLangOpts().HLSL,
767 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
768 FirstQualifierInScope, NameInfo, TemplateArgs);
769 }
770
771 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
772}
773
776 SourceLocation TemplateKWLoc,
777 const DeclarationNameInfo &NameInfo,
778 const TemplateArgumentListInfo *TemplateArgs) {
779 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
781 if (!QualifierLoc)
782 return ExprError();
783
785 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
786}
787
788
789/// Determine whether we would be unable to instantiate this template (because
790/// it either has no definition, or is in the process of being instantiated).
792 NamedDecl *Instantiation,
793 bool InstantiatedFromMember,
794 const NamedDecl *Pattern,
795 const NamedDecl *PatternDef,
797 bool Complain /*= true*/) {
798 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
799 isa<VarDecl>(Instantiation));
800
801 bool IsEntityBeingDefined = false;
802 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
803 IsEntityBeingDefined = TD->isBeingDefined();
804
805 if (PatternDef && !IsEntityBeingDefined) {
806 NamedDecl *SuggestedDef = nullptr;
807 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
808 &SuggestedDef,
809 /*OnlyNeedComplete*/ false)) {
810 // If we're allowed to diagnose this and recover, do so.
811 bool Recover = Complain && !isSFINAEContext();
812 if (Complain)
813 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
815 return !Recover;
816 }
817 return false;
818 }
819
820 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
821 return true;
822
823 QualType InstantiationTy;
824 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
825 InstantiationTy = Context.getTypeDeclType(TD);
826 if (PatternDef) {
827 Diag(PointOfInstantiation,
828 diag::err_template_instantiate_within_definition)
829 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
830 << InstantiationTy;
831 // Not much point in noting the template declaration here, since
832 // we're lexically inside it.
833 Instantiation->setInvalidDecl();
834 } else if (InstantiatedFromMember) {
835 if (isa<FunctionDecl>(Instantiation)) {
836 Diag(PointOfInstantiation,
837 diag::err_explicit_instantiation_undefined_member)
838 << /*member function*/ 1 << Instantiation->getDeclName()
839 << Instantiation->getDeclContext();
840 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
841 } else {
842 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
843 Diag(PointOfInstantiation,
844 diag::err_implicit_instantiate_member_undefined)
845 << InstantiationTy;
846 Diag(Pattern->getLocation(), diag::note_member_declared_at);
847 }
848 } else {
849 if (isa<FunctionDecl>(Instantiation)) {
850 Diag(PointOfInstantiation,
851 diag::err_explicit_instantiation_undefined_func_template)
852 << Pattern;
853 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
854 } else if (isa<TagDecl>(Instantiation)) {
855 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
856 << (TSK != TSK_ImplicitInstantiation)
857 << InstantiationTy;
858 NoteTemplateLocation(*Pattern);
859 } else {
860 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
861 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
862 Diag(PointOfInstantiation,
863 diag::err_explicit_instantiation_undefined_var_template)
864 << Instantiation;
865 Instantiation->setInvalidDecl();
866 } else
867 Diag(PointOfInstantiation,
868 diag::err_explicit_instantiation_undefined_member)
869 << /*static data member*/ 2 << Instantiation->getDeclName()
870 << Instantiation->getDeclContext();
871 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
872 }
873 }
874
875 // In general, Instantiation isn't marked invalid to get more than one
876 // error for multiple undefined instantiations. But the code that does
877 // explicit declaration -> explicit definition conversion can't handle
878 // invalid declarations, so mark as invalid in that case.
880 Instantiation->setInvalidDecl();
881 return true;
882}
883
885 bool SupportedForCompatibility) {
886 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
887
888 // C++23 [temp.local]p6:
889 // The name of a template-parameter shall not be bound to any following.
890 // declaration whose locus is contained by the scope to which the
891 // template-parameter belongs.
892 //
893 // When MSVC compatibility is enabled, the diagnostic is always a warning
894 // by default. Otherwise, it an error unless SupportedForCompatibility is
895 // true, in which case it is a default-to-error warning.
896 unsigned DiagId =
897 getLangOpts().MSVCCompat
898 ? diag::ext_template_param_shadow
899 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
900 : diag::err_template_param_shadow);
901 const auto *ND = cast<NamedDecl>(PrevDecl);
902 Diag(Loc, DiagId) << ND->getDeclName();
904}
905
906/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
907/// the parameter D to reference the templated declaration and return a pointer
908/// to the template declaration. Otherwise, do nothing to D and return null.
910 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
911 D = Temp->getTemplatedDecl();
912 return Temp;
913 }
914 return nullptr;
915}
916
918 SourceLocation EllipsisLoc) const {
919 assert(Kind == Template &&
920 "Only template template arguments can be pack expansions here");
921 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
922 "Template template argument pack expansion without packs");
924 Result.EllipsisLoc = EllipsisLoc;
925 return Result;
926}
927
929 const ParsedTemplateArgument &Arg) {
930
931 switch (Arg.getKind()) {
933 TypeSourceInfo *DI;
934 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
935 if (!DI)
936 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
938 }
939
941 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
943 }
944
946 TemplateName Template = Arg.getAsTemplate().get();
947 TemplateArgument TArg;
948 if (Arg.getEllipsisLoc().isValid())
949 TArg = TemplateArgument(Template, std::optional<unsigned int>());
950 else
951 TArg = Template;
952 return TemplateArgumentLoc(
953 SemaRef.Context, TArg,
955 Arg.getLocation(), Arg.getEllipsisLoc());
956 }
957 }
958
959 llvm_unreachable("Unhandled parsed template argument");
960}
961
962/// Translates template arguments as provided by the parser
963/// into template arguments used by semantic analysis.
965 TemplateArgumentListInfo &TemplateArgs) {
966 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
967 TemplateArgs.addArgument(translateTemplateArgument(*this,
968 TemplateArgsIn[I]));
969}
970
972 SourceLocation Loc,
973 IdentifierInfo *Name) {
974 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
976 if (PrevDecl && PrevDecl->isTemplateParameter())
977 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
978}
979
980/// Convert a parsed type into a parsed template argument. This is mostly
981/// trivial, except that we may have parsed a C++17 deduced class template
982/// specialization type, in which case we should form a template template
983/// argument instead of a type template argument.
985 TypeSourceInfo *TInfo;
987 if (T.isNull())
988 return ParsedTemplateArgument();
989 assert(TInfo && "template argument with no location");
990
991 // If we might have formed a deduced template specialization type, convert
992 // it to a template template argument.
993 if (getLangOpts().CPlusPlus17) {
994 TypeLoc TL = TInfo->getTypeLoc();
995 SourceLocation EllipsisLoc;
996 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
997 EllipsisLoc = PET.getEllipsisLoc();
998 TL = PET.getPatternLoc();
999 }
1000
1001 CXXScopeSpec SS;
1002 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1003 SS.Adopt(ET.getQualifierLoc());
1004 TL = ET.getNamedTypeLoc();
1005 }
1006
1007 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1008 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1009 if (SS.isSet())
1011 /*HasTemplateKeyword=*/false,
1012 Name);
1014 DTST.getTemplateNameLoc());
1015 if (EllipsisLoc.isValid())
1016 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1017 return Result;
1018 }
1019 }
1020
1021 // This is a normal type template argument. Note, if the type template
1022 // argument is an injected-class-name for a template, it has a dual nature
1023 // and can be used as either a type or a template. We handle that in
1024 // convertTypeTemplateArgumentToTemplate.
1027 TInfo->getTypeLoc().getBeginLoc());
1028}
1029
1030/// ActOnTypeParameter - Called when a C++ template type parameter
1031/// (e.g., "typename T") has been parsed. Typename specifies whether
1032/// the keyword "typename" was used to declare the type parameter
1033/// (otherwise, "class" was used), and KeyLoc is the location of the
1034/// "class" or "typename" keyword. ParamName is the name of the
1035/// parameter (NULL indicates an unnamed template parameter) and
1036/// ParamNameLoc is the location of the parameter name (if any).
1037/// If the type parameter has a default argument, it will be added
1038/// later via ActOnTypeParameterDefault.
1040 SourceLocation EllipsisLoc,
1041 SourceLocation KeyLoc,
1042 IdentifierInfo *ParamName,
1043 SourceLocation ParamNameLoc,
1044 unsigned Depth, unsigned Position,
1045 SourceLocation EqualLoc,
1046 ParsedType DefaultArg,
1047 bool HasTypeConstraint) {
1048 assert(S->isTemplateParamScope() &&
1049 "Template type parameter not in template parameter scope!");
1050
1051 bool IsParameterPack = EllipsisLoc.isValid();
1054 KeyLoc, ParamNameLoc, Depth, Position,
1055 ParamName, Typename, IsParameterPack,
1056 HasTypeConstraint);
1057 Param->setAccess(AS_public);
1058
1059 if (Param->isParameterPack())
1060 if (auto *LSI = getEnclosingLambda())
1061 LSI->LocalPacks.push_back(Param);
1062
1063 if (ParamName) {
1064 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1065
1066 // Add the template parameter into the current scope.
1067 S->AddDecl(Param);
1068 IdResolver.AddDecl(Param);
1069 }
1070
1071 // C++0x [temp.param]p9:
1072 // A default template-argument may be specified for any kind of
1073 // template-parameter that is not a template parameter pack.
1074 if (DefaultArg && IsParameterPack) {
1075 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1076 DefaultArg = nullptr;
1077 }
1078
1079 // Handle the default argument, if provided.
1080 if (DefaultArg) {
1081 TypeSourceInfo *DefaultTInfo;
1082 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1083
1084 assert(DefaultTInfo && "expected source information for type");
1085
1086 // Check for unexpanded parameter packs.
1087 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1089 return Param;
1090
1091 // Check the template argument itself.
1092 if (CheckTemplateArgument(DefaultTInfo)) {
1093 Param->setInvalidDecl();
1094 return Param;
1095 }
1096
1097 Param->setDefaultArgument(DefaultTInfo);
1098 }
1099
1100 return Param;
1101}
1102
1103/// Convert the parser's template argument list representation into our form.
1106 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1107 TemplateId.RAngleLoc);
1108 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1109 TemplateId.NumArgs);
1110 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1111 return TemplateArgs;
1112}
1113
1115
1116 TemplateName TN = TypeConstr->Template.get();
1117 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1118
1119 // C++2a [temp.param]p4:
1120 // [...] The concept designated by a type-constraint shall be a type
1121 // concept ([temp.concept]).
1122 if (!CD->isTypeConcept()) {
1123 Diag(TypeConstr->TemplateNameLoc,
1124 diag::err_type_constraint_non_type_concept);
1125 return true;
1126 }
1127
1128 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1129
1130 if (!WereArgsSpecified &&
1132 Diag(TypeConstr->TemplateNameLoc,
1133 diag::err_type_constraint_missing_arguments)
1134 << CD;
1135 return true;
1136 }
1137 return false;
1138}
1139
1141 TemplateIdAnnotation *TypeConstr,
1142 TemplateTypeParmDecl *ConstrainedParameter,
1143 SourceLocation EllipsisLoc) {
1144 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1145 false);
1146}
1147
1149 TemplateIdAnnotation *TypeConstr,
1150 TemplateTypeParmDecl *ConstrainedParameter,
1151 SourceLocation EllipsisLoc,
1152 bool AllowUnexpandedPack) {
1153
1154 if (CheckTypeConstraint(TypeConstr))
1155 return true;
1156
1157 TemplateName TN = TypeConstr->Template.get();
1158 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1160
1161 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1162 TypeConstr->TemplateNameLoc);
1163
1164 TemplateArgumentListInfo TemplateArgs;
1165 if (TypeConstr->LAngleLoc.isValid()) {
1166 TemplateArgs =
1167 makeTemplateArgumentListInfo(*this, *TypeConstr);
1168
1169 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1170 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1172 return true;
1173 }
1174 }
1175 }
1176 return AttachTypeConstraint(
1178 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1179 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1180 ConstrainedParameter, EllipsisLoc);
1181}
1182
1183template <typename ArgumentLocAppender>
1186 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1187 SourceLocation RAngleLoc, QualType ConstrainedType,
1188 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1189 SourceLocation EllipsisLoc) {
1190
1191 TemplateArgumentListInfo ConstraintArgs;
1192 ConstraintArgs.addArgument(
1194 /*NTTPType=*/QualType(), ParamNameLoc));
1195
1196 ConstraintArgs.setRAngleLoc(RAngleLoc);
1197 ConstraintArgs.setLAngleLoc(LAngleLoc);
1198 Appender(ConstraintArgs);
1199
1200 // C++2a [temp.param]p4:
1201 // [...] This constraint-expression E is called the immediately-declared
1202 // constraint of T. [...]
1203 CXXScopeSpec SS;
1204 SS.Adopt(NS);
1205 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1206 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1207 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1208 &ConstraintArgs);
1209 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1210 return ImmediatelyDeclaredConstraint;
1211
1212 // C++2a [temp.param]p4:
1213 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1214 //
1215 // We have the following case:
1216 //
1217 // template<typename T> concept C1 = true;
1218 // template<C1... T> struct s1;
1219 //
1220 // The constraint: (C1<T> && ...)
1221 //
1222 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1223 // any unqualified lookups for 'operator&&' here.
1224 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1225 /*LParenLoc=*/SourceLocation(),
1226 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1227 EllipsisLoc, /*RHS=*/nullptr,
1228 /*RParenLoc=*/SourceLocation(),
1229 /*NumExpansions=*/std::nullopt);
1230}
1231
1232/// Attach a type-constraint to a template parameter.
1233/// \returns true if an error occurred. This can happen if the
1234/// immediately-declared constraint could not be formed (e.g. incorrect number
1235/// of arguments for the named concept).
1237 DeclarationNameInfo NameInfo,
1238 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1239 const TemplateArgumentListInfo *TemplateArgs,
1240 TemplateTypeParmDecl *ConstrainedParameter,
1241 SourceLocation EllipsisLoc) {
1242 // C++2a [temp.param]p4:
1243 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1244 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1245 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1247 *TemplateArgs) : nullptr;
1248
1249 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1250
1251 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1252 *this, NS, NameInfo, NamedConcept, FoundDecl,
1253 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1254 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1255 ParamAsArgument, ConstrainedParameter->getLocation(),
1256 [&](TemplateArgumentListInfo &ConstraintArgs) {
1257 if (TemplateArgs)
1258 for (const auto &ArgLoc : TemplateArgs->arguments())
1259 ConstraintArgs.addArgument(ArgLoc);
1260 },
1261 EllipsisLoc);
1262 if (ImmediatelyDeclaredConstraint.isInvalid())
1263 return true;
1264
1265 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1266 /*TemplateKWLoc=*/SourceLocation{},
1267 /*ConceptNameInfo=*/NameInfo,
1268 /*FoundDecl=*/FoundDecl,
1269 /*NamedConcept=*/NamedConcept,
1270 /*ArgsWritten=*/ArgsAsWritten);
1271 ConstrainedParameter->setTypeConstraint(CL,
1272 ImmediatelyDeclaredConstraint.get());
1273 return false;
1274}
1275
1277 NonTypeTemplateParmDecl *NewConstrainedParm,
1278 NonTypeTemplateParmDecl *OrigConstrainedParm,
1279 SourceLocation EllipsisLoc) {
1280 if (NewConstrainedParm->getType() != TL.getType() ||
1282 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1283 diag::err_unsupported_placeholder_constraint)
1284 << NewConstrainedParm->getTypeSourceInfo()
1285 ->getTypeLoc()
1286 .getSourceRange();
1287 return true;
1288 }
1289 // FIXME: Concepts: This should be the type of the placeholder, but this is
1290 // unclear in the wording right now.
1291 DeclRefExpr *Ref =
1292 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1293 VK_PRValue, OrigConstrainedParm->getLocation());
1294 if (!Ref)
1295 return true;
1296 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1298 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1300 OrigConstrainedParm->getLocation(),
1301 [&](TemplateArgumentListInfo &ConstraintArgs) {
1302 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1303 ConstraintArgs.addArgument(TL.getArgLoc(I));
1304 },
1305 EllipsisLoc);
1306 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1307 !ImmediatelyDeclaredConstraint.isUsable())
1308 return true;
1309
1310 NewConstrainedParm->setPlaceholderTypeConstraint(
1311 ImmediatelyDeclaredConstraint.get());
1312 return false;
1313}
1314
1315/// Check that the type of a non-type template parameter is
1316/// well-formed.
1317///
1318/// \returns the (possibly-promoted) parameter type if valid;
1319/// otherwise, produces a diagnostic and returns a NULL type.
1321 SourceLocation Loc) {
1322 if (TSI->getType()->isUndeducedType()) {
1323 // C++17 [temp.dep.expr]p3:
1324 // An id-expression is type-dependent if it contains
1325 // - an identifier associated by name lookup with a non-type
1326 // template-parameter declared with a type that contains a
1327 // placeholder type (7.1.7.4),
1329 }
1330
1331 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1332}
1333
1334/// Require the given type to be a structural type, and diagnose if it is not.
1335///
1336/// \return \c true if an error was produced.
1338 if (T->isDependentType())
1339 return false;
1340
1341 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1342 return true;
1343
1344 if (T->isStructuralType())
1345 return false;
1346
1347 // Structural types are required to be object types or lvalue references.
1348 if (T->isRValueReferenceType()) {
1349 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1350 return true;
1351 }
1352
1353 // Don't mention structural types in our diagnostic prior to C++20. Also,
1354 // there's not much more we can say about non-scalar non-class types --
1355 // because we can't see functions or arrays here, those can only be language
1356 // extensions.
1357 if (!getLangOpts().CPlusPlus20 ||
1358 (!T->isScalarType() && !T->isRecordType())) {
1359 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1360 return true;
1361 }
1362
1363 // Structural types are required to be literal types.
1364 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1365 return true;
1366
1367 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1368
1369 // Drill down into the reason why the class is non-structural.
1370 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1371 // All members are required to be public and non-mutable, and can't be of
1372 // rvalue reference type. Check these conditions first to prefer a "local"
1373 // reason over a more distant one.
1374 for (const FieldDecl *FD : RD->fields()) {
1375 if (FD->getAccess() != AS_public) {
1376 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1377 return true;
1378 }
1379 if (FD->isMutable()) {
1380 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1381 return true;
1382 }
1383 if (FD->getType()->isRValueReferenceType()) {
1384 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1385 << T;
1386 return true;
1387 }
1388 }
1389
1390 // All bases are required to be public.
1391 for (const auto &BaseSpec : RD->bases()) {
1392 if (BaseSpec.getAccessSpecifier() != AS_public) {
1393 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1394 << T << 1;
1395 return true;
1396 }
1397 }
1398
1399 // All subobjects are required to be of structural types.
1400 SourceLocation SubLoc;
1401 QualType SubType;
1402 int Kind = -1;
1403
1404 for (const FieldDecl *FD : RD->fields()) {
1405 QualType T = Context.getBaseElementType(FD->getType());
1406 if (!T->isStructuralType()) {
1407 SubLoc = FD->getLocation();
1408 SubType = T;
1409 Kind = 0;
1410 break;
1411 }
1412 }
1413
1414 if (Kind == -1) {
1415 for (const auto &BaseSpec : RD->bases()) {
1416 QualType T = BaseSpec.getType();
1417 if (!T->isStructuralType()) {
1418 SubLoc = BaseSpec.getBaseTypeLoc();
1419 SubType = T;
1420 Kind = 1;
1421 break;
1422 }
1423 }
1424 }
1425
1426 assert(Kind != -1 && "couldn't find reason why type is not structural");
1427 Diag(SubLoc, diag::note_not_structural_subobject)
1428 << T << Kind << SubType;
1429 T = SubType;
1430 RD = T->getAsCXXRecordDecl();
1431 }
1432
1433 return true;
1434}
1435
1437 SourceLocation Loc) {
1438 // We don't allow variably-modified types as the type of non-type template
1439 // parameters.
1440 if (T->isVariablyModifiedType()) {
1441 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1442 << T;
1443 return QualType();
1444 }
1445
1446 // C++ [temp.param]p4:
1447 //
1448 // A non-type template-parameter shall have one of the following
1449 // (optionally cv-qualified) types:
1450 //
1451 // -- integral or enumeration type,
1452 if (T->isIntegralOrEnumerationType() ||
1453 // -- pointer to object or pointer to function,
1454 T->isPointerType() ||
1455 // -- lvalue reference to object or lvalue reference to function,
1456 T->isLValueReferenceType() ||
1457 // -- pointer to member,
1458 T->isMemberPointerType() ||
1459 // -- std::nullptr_t, or
1460 T->isNullPtrType() ||
1461 // -- a type that contains a placeholder type.
1462 T->isUndeducedType()) {
1463 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1464 // are ignored when determining its type.
1465 return T.getUnqualifiedType();
1466 }
1467
1468 // C++ [temp.param]p8:
1469 //
1470 // A non-type template-parameter of type "array of T" or
1471 // "function returning T" is adjusted to be of type "pointer to
1472 // T" or "pointer to function returning T", respectively.
1473 if (T->isArrayType() || T->isFunctionType())
1474 return Context.getDecayedType(T);
1475
1476 // If T is a dependent type, we can't do the check now, so we
1477 // assume that it is well-formed. Note that stripping off the
1478 // qualifiers here is not really correct if T turns out to be
1479 // an array type, but we'll recompute the type everywhere it's
1480 // used during instantiation, so that should be OK. (Using the
1481 // qualified type is equally wrong.)
1482 if (T->isDependentType())
1483 return T.getUnqualifiedType();
1484
1485 // C++20 [temp.param]p6:
1486 // -- a structural type
1487 if (RequireStructuralType(T, Loc))
1488 return QualType();
1489
1490 if (!getLangOpts().CPlusPlus20) {
1491 // FIXME: Consider allowing structural types as an extension in C++17. (In
1492 // earlier language modes, the template argument evaluation rules are too
1493 // inflexible.)
1494 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1495 return QualType();
1496 }
1497
1498 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1499 return T.getUnqualifiedType();
1500}
1501
1503 unsigned Depth,
1504 unsigned Position,
1505 SourceLocation EqualLoc,
1506 Expr *Default) {
1508
1509 // Check that we have valid decl-specifiers specified.
1510 auto CheckValidDeclSpecifiers = [this, &D] {
1511 // C++ [temp.param]
1512 // p1
1513 // template-parameter:
1514 // ...
1515 // parameter-declaration
1516 // p2
1517 // ... A storage class shall not be specified in a template-parameter
1518 // declaration.
1519 // [dcl.typedef]p1:
1520 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1521 // of a parameter-declaration
1522 const DeclSpec &DS = D.getDeclSpec();
1523 auto EmitDiag = [this](SourceLocation Loc) {
1524 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1526 };
1528 EmitDiag(DS.getStorageClassSpecLoc());
1529
1531 EmitDiag(DS.getThreadStorageClassSpecLoc());
1532
1533 // [dcl.inline]p1:
1534 // The inline specifier can be applied only to the declaration or
1535 // definition of a variable or function.
1536
1537 if (DS.isInlineSpecified())
1538 EmitDiag(DS.getInlineSpecLoc());
1539
1540 // [dcl.constexpr]p1:
1541 // The constexpr specifier shall be applied only to the definition of a
1542 // variable or variable template or the declaration of a function or
1543 // function template.
1544
1545 if (DS.hasConstexprSpecifier())
1546 EmitDiag(DS.getConstexprSpecLoc());
1547
1548 // [dcl.fct.spec]p1:
1549 // Function-specifiers can be used only in function declarations.
1550
1551 if (DS.isVirtualSpecified())
1552 EmitDiag(DS.getVirtualSpecLoc());
1553
1554 if (DS.hasExplicitSpecifier())
1555 EmitDiag(DS.getExplicitSpecLoc());
1556
1557 if (DS.isNoreturnSpecified())
1558 EmitDiag(DS.getNoreturnSpecLoc());
1559 };
1560
1561 CheckValidDeclSpecifiers();
1562
1563 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1564 if (isa<AutoType>(T))
1566 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1567 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1568
1569 assert(S->isTemplateParamScope() &&
1570 "Non-type template parameter not in template parameter scope!");
1571 bool Invalid = false;
1572
1574 if (T.isNull()) {
1575 T = Context.IntTy; // Recover with an 'int' type.
1576 Invalid = true;
1577 }
1578
1580
1581 IdentifierInfo *ParamName = D.getIdentifier();
1582 bool IsParameterPack = D.hasEllipsis();
1585 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1586 TInfo);
1587 Param->setAccess(AS_public);
1588
1590 if (TL.isConstrained())
1591 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1592 Invalid = true;
1593
1594 if (Invalid)
1595 Param->setInvalidDecl();
1596
1597 if (Param->isParameterPack())
1598 if (auto *LSI = getEnclosingLambda())
1599 LSI->LocalPacks.push_back(Param);
1600
1601 if (ParamName) {
1603 ParamName);
1604
1605 // Add the template parameter into the current scope.
1606 S->AddDecl(Param);
1607 IdResolver.AddDecl(Param);
1608 }
1609
1610 // C++0x [temp.param]p9:
1611 // A default template-argument may be specified for any kind of
1612 // template-parameter that is not a template parameter pack.
1613 if (Default && IsParameterPack) {
1614 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1615 Default = nullptr;
1616 }
1617
1618 // Check the well-formedness of the default template argument, if provided.
1619 if (Default) {
1620 // Check for unexpanded parameter packs.
1622 return Param;
1623
1625 }
1626
1627 return Param;
1628}
1629
1630/// ActOnTemplateTemplateParameter - Called when a C++ template template
1631/// parameter (e.g. T in template <template <typename> class T> class array)
1632/// has been parsed. S is the current scope.
1634 SourceLocation TmpLoc,
1635 TemplateParameterList *Params,
1636 SourceLocation EllipsisLoc,
1637 IdentifierInfo *Name,
1638 SourceLocation NameLoc,
1639 unsigned Depth,
1640 unsigned Position,
1641 SourceLocation EqualLoc,
1643 assert(S->isTemplateParamScope() &&
1644 "Template template parameter not in template parameter scope!");
1645
1646 // Construct the parameter object.
1647 bool IsParameterPack = EllipsisLoc.isValid();
1650 NameLoc.isInvalid()? TmpLoc : NameLoc,
1651 Depth, Position, IsParameterPack,
1652 Name, Params);
1653 Param->setAccess(AS_public);
1654
1655 if (Param->isParameterPack())
1656 if (auto *LSI = getEnclosingLambda())
1657 LSI->LocalPacks.push_back(Param);
1658
1659 // If the template template parameter has a name, then link the identifier
1660 // into the scope and lookup mechanisms.
1661 if (Name) {
1662 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1663
1664 S->AddDecl(Param);
1665 IdResolver.AddDecl(Param);
1666 }
1667
1668 if (Params->size() == 0) {
1669 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1670 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1671 Param->setInvalidDecl();
1672 }
1673
1674 // C++0x [temp.param]p9:
1675 // A default template-argument may be specified for any kind of
1676 // template-parameter that is not a template parameter pack.
1677 if (IsParameterPack && !Default.isInvalid()) {
1678 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1680 }
1681
1682 if (!Default.isInvalid()) {
1683 // Check only that we have a template template argument. We don't want to
1684 // try to check well-formedness now, because our template template parameter
1685 // might have dependent types in its template parameters, which we wouldn't
1686 // be able to match now.
1687 //
1688 // If none of the template template parameter's template arguments mention
1689 // other template parameters, we could actually perform more checking here.
1690 // However, it isn't worth doing.
1692 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1693 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1694 << DefaultArg.getSourceRange();
1695 return Param;
1696 }
1697
1698 // Check for unexpanded parameter packs.
1700 DefaultArg.getArgument().getAsTemplate(),
1702 return Param;
1703
1704 Param->setDefaultArgument(Context, DefaultArg);
1705 }
1706
1707 return Param;
1708}
1709
1710namespace {
1711class ConstraintRefersToContainingTemplateChecker
1712 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1713 bool Result = false;
1714 const FunctionDecl *Friend = nullptr;
1715 unsigned TemplateDepth = 0;
1716
1717 // Check a record-decl that we've seen to see if it is a lexical parent of the
1718 // Friend, likely because it was referred to without its template arguments.
1719 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1720 CheckingRD = CheckingRD->getMostRecentDecl();
1721 if (!CheckingRD->isTemplated())
1722 return;
1723
1724 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1725 DC && !DC->isFileContext(); DC = DC->getParent())
1726 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1727 if (CheckingRD == RD->getMostRecentDecl())
1728 Result = true;
1729 }
1730
1731 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1732 assert(D->getDepth() <= TemplateDepth &&
1733 "Nothing should reference a value below the actual template depth, "
1734 "depth is likely wrong");
1735 if (D->getDepth() != TemplateDepth)
1736 Result = true;
1737
1738 // Necessary because the type of the NTTP might be what refers to the parent
1739 // constriant.
1740 TransformType(D->getType());
1741 }
1742
1743public:
1745
1746 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1747 const FunctionDecl *Friend,
1748 unsigned TemplateDepth)
1749 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1750 bool getResult() const { return Result; }
1751
1752 // This should be the only template parm type that we have to deal with.
1753 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1754 // FunctionParmPackExpr are all partially substituted, which cannot happen
1755 // with concepts at this point in translation.
1756 using inherited::TransformTemplateTypeParmType;
1757 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1758 TemplateTypeParmTypeLoc TL, bool) {
1759 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1760 "Nothing should reference a value below the actual template depth, "
1761 "depth is likely wrong");
1762 if (TL.getDecl()->getDepth() != TemplateDepth)
1763 Result = true;
1764 return inherited::TransformTemplateTypeParmType(
1765 TLB, TL,
1766 /*SuppressObjCLifetime=*/false);
1767 }
1768
1769 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1770 if (!D)
1771 return D;
1772 // FIXME : This is possibly an incomplete list, but it is unclear what other
1773 // Decl kinds could be used to refer to the template parameters. This is a
1774 // best guess so far based on examples currently available, but the
1775 // unreachable should catch future instances/cases.
1776 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1777 TransformType(TD->getUnderlyingType());
1778 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1779 CheckNonTypeTemplateParmDecl(NTTPD);
1780 else if (auto *VD = dyn_cast<ValueDecl>(D))
1781 TransformType(VD->getType());
1782 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1783 TransformTemplateParameterList(TD->getTemplateParameters());
1784 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1785 CheckIfContainingRecord(RD);
1786 else if (isa<NamedDecl>(D)) {
1787 // No direct types to visit here I believe.
1788 } else
1789 llvm_unreachable("Don't know how to handle this declaration type yet");
1790 return D;
1791 }
1792};
1793} // namespace
1794
1796 const FunctionDecl *Friend, unsigned TemplateDepth,
1797 const Expr *Constraint) {
1798 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1799 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1800 TemplateDepth);
1801 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1802 return Checker.getResult();
1803}
1804
1805/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1806/// constrained by RequiresClause, that contains the template parameters in
1807/// Params.
1810 SourceLocation ExportLoc,
1811 SourceLocation TemplateLoc,
1812 SourceLocation LAngleLoc,
1813 ArrayRef<NamedDecl *> Params,
1814 SourceLocation RAngleLoc,
1815 Expr *RequiresClause) {
1816 if (ExportLoc.isValid())
1817 Diag(ExportLoc, diag::warn_template_export_unsupported);
1818
1819 for (NamedDecl *P : Params)
1821
1823 Context, TemplateLoc, LAngleLoc,
1824 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1825}
1826
1828 const CXXScopeSpec &SS) {
1829 if (SS.isSet())
1831}
1832
1833// Returns the template parameter list with all default template argument
1834// information.
1836 // Make sure we get the template parameter list from the most
1837 // recent declaration, since that is the only one that is guaranteed to
1838 // have all the default template argument information.
1839 return cast<TemplateDecl>(TD->getMostRecentDecl())->getTemplateParameters();
1840}
1841
1843 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1844 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1845 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1846 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1847 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1848 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1849 assert(TemplateParams && TemplateParams->size() > 0 &&
1850 "No template parameters");
1851 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1852 bool Invalid = false;
1853
1854 // Check that we can declare a template here.
1855 if (CheckTemplateDeclScope(S, TemplateParams))
1856 return true;
1857
1859 assert(Kind != TagTypeKind::Enum &&
1860 "can't build template of enumerated type");
1861
1862 // There is no such thing as an unnamed class template.
1863 if (!Name) {
1864 Diag(KWLoc, diag::err_template_unnamed_class);
1865 return true;
1866 }
1867
1868 // Find any previous declaration with this name. For a friend with no
1869 // scope explicitly specified, we only look for tag declarations (per
1870 // C++11 [basic.lookup.elab]p2).
1871 DeclContext *SemanticContext;
1872 LookupResult Previous(*this, Name, NameLoc,
1873 (SS.isEmpty() && TUK == TUK_Friend)
1876 if (SS.isNotEmpty() && !SS.isInvalid()) {
1877 SemanticContext = computeDeclContext(SS, true);
1878 if (!SemanticContext) {
1879 // FIXME: Horrible, horrible hack! We can't currently represent this
1880 // in the AST, and historically we have just ignored such friend
1881 // class templates, so don't complain here.
1882 Diag(NameLoc, TUK == TUK_Friend
1883 ? diag::warn_template_qualified_friend_ignored
1884 : diag::err_template_qualified_declarator_no_match)
1885 << SS.getScopeRep() << SS.getRange();
1886 return TUK != TUK_Friend;
1887 }
1888
1889 if (RequireCompleteDeclContext(SS, SemanticContext))
1890 return true;
1891
1892 // If we're adding a template to a dependent context, we may need to
1893 // rebuilding some of the types used within the template parameter list,
1894 // now that we know what the current instantiation is.
1895 if (SemanticContext->isDependentContext()) {
1896 ContextRAII SavedContext(*this, SemanticContext);
1898 Invalid = true;
1899 }
1900
1901 if (TUK != TUK_Friend && TUK != TUK_Reference)
1902 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1903 /*TemplateId-*/ nullptr,
1904 /*IsMemberSpecialization*/ false);
1905
1906 LookupQualifiedName(Previous, SemanticContext);
1907 } else {
1908 SemanticContext = CurContext;
1909
1910 // C++14 [class.mem]p14:
1911 // If T is the name of a class, then each of the following shall have a
1912 // name different from T:
1913 // -- every member template of class T
1914 if (TUK != TUK_Friend &&
1915 DiagnoseClassNameShadow(SemanticContext,
1916 DeclarationNameInfo(Name, NameLoc)))
1917 return true;
1918
1919 LookupName(Previous, S);
1920 }
1921
1922 if (Previous.isAmbiguous())
1923 return true;
1924
1925 NamedDecl *PrevDecl = nullptr;
1926 if (Previous.begin() != Previous.end())
1927 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1928
1929 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1930 // Maybe we will complain about the shadowed template parameter.
1931 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1932 // Just pretend that we didn't see the previous declaration.
1933 PrevDecl = nullptr;
1934 }
1935
1936 // If there is a previous declaration with the same name, check
1937 // whether this is a valid redeclaration.
1938 ClassTemplateDecl *PrevClassTemplate =
1939 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1940
1941 // We may have found the injected-class-name of a class template,
1942 // class template partial specialization, or class template specialization.
1943 // In these cases, grab the template that is being defined or specialized.
1944 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1945 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1946 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1947 PrevClassTemplate
1948 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1949 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1950 PrevClassTemplate
1951 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1952 ->getSpecializedTemplate();
1953 }
1954 }
1955
1956 if (TUK == TUK_Friend) {
1957 // C++ [namespace.memdef]p3:
1958 // [...] When looking for a prior declaration of a class or a function
1959 // declared as a friend, and when the name of the friend class or
1960 // function is neither a qualified name nor a template-id, scopes outside
1961 // the innermost enclosing namespace scope are not considered.
1962 if (!SS.isSet()) {
1963 DeclContext *OutermostContext = CurContext;
1964 while (!OutermostContext->isFileContext())
1965 OutermostContext = OutermostContext->getLookupParent();
1966
1967 if (PrevDecl &&
1968 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1969 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1970 SemanticContext = PrevDecl->getDeclContext();
1971 } else {
1972 // Declarations in outer scopes don't matter. However, the outermost
1973 // context we computed is the semantic context for our new
1974 // declaration.
1975 PrevDecl = PrevClassTemplate = nullptr;
1976 SemanticContext = OutermostContext;
1977
1978 // Check that the chosen semantic context doesn't already contain a
1979 // declaration of this name as a non-tag type.
1981 DeclContext *LookupContext = SemanticContext;
1982 while (LookupContext->isTransparentContext())
1983 LookupContext = LookupContext->getLookupParent();
1984 LookupQualifiedName(Previous, LookupContext);
1985
1986 if (Previous.isAmbiguous())
1987 return true;
1988
1989 if (Previous.begin() != Previous.end())
1990 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1991 }
1992 }
1993 } else if (PrevDecl &&
1994 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1995 S, SS.isValid()))
1996 PrevDecl = PrevClassTemplate = nullptr;
1997
1998 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1999 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2000 if (SS.isEmpty() &&
2001 !(PrevClassTemplate &&
2002 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2003 SemanticContext->getRedeclContext()))) {
2004 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2005 Diag(Shadow->getTargetDecl()->getLocation(),
2006 diag::note_using_decl_target);
2007 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2008 // Recover by ignoring the old declaration.
2009 PrevDecl = PrevClassTemplate = nullptr;
2010 }
2011 }
2012
2013 if (PrevClassTemplate) {
2014 // Ensure that the template parameter lists are compatible. Skip this check
2015 // for a friend in a dependent context: the template parameter list itself
2016 // could be dependent.
2017 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2019 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2020 : CurContext,
2021 CurContext, KWLoc),
2022 TemplateParams, PrevClassTemplate,
2023 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2025 return true;
2026
2027 // C++ [temp.class]p4:
2028 // In a redeclaration, partial specialization, explicit
2029 // specialization or explicit instantiation of a class template,
2030 // the class-key shall agree in kind with the original class
2031 // template declaration (7.1.5.3).
2032 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2033 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2034 TUK == TUK_Definition, KWLoc, Name)) {
2035 Diag(KWLoc, diag::err_use_with_wrong_tag)
2036 << Name
2037 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2038 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2039 Kind = PrevRecordDecl->getTagKind();
2040 }
2041
2042 // Check for redefinition of this class template.
2043 if (TUK == TUK_Definition) {
2044 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2045 // If we have a prior definition that is not visible, treat this as
2046 // simply making that previous definition visible.
2047 NamedDecl *Hidden = nullptr;
2048 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2049 SkipBody->ShouldSkip = true;
2050 SkipBody->Previous = Def;
2051 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2052 assert(Tmpl && "original definition of a class template is not a "
2053 "class template?");
2056 } else {
2057 Diag(NameLoc, diag::err_redefinition) << Name;
2058 Diag(Def->getLocation(), diag::note_previous_definition);
2059 // FIXME: Would it make sense to try to "forget" the previous
2060 // definition, as part of error recovery?
2061 return true;
2062 }
2063 }
2064 }
2065 } else if (PrevDecl) {
2066 // C++ [temp]p5:
2067 // A class template shall not have the same name as any other
2068 // template, class, function, object, enumeration, enumerator,
2069 // namespace, or type in the same scope (3.3), except as specified
2070 // in (14.5.4).
2071 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2072 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2073 return true;
2074 }
2075
2076 // Check the template parameter list of this declaration, possibly
2077 // merging in the template parameter list from the previous class
2078 // template declaration. Skip this check for a friend in a dependent
2079 // context, because the template parameter list might be dependent.
2080 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2082 TemplateParams,
2083 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2084 : nullptr,
2085 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2086 SemanticContext->isDependentContext())
2090 SkipBody))
2091 Invalid = true;
2092
2093 if (SS.isSet()) {
2094 // If the name of the template was qualified, we must be defining the
2095 // template out-of-line.
2096 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2097 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2098 : diag::err_member_decl_does_not_match)
2099 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2100 Invalid = true;
2101 }
2102 }
2103
2104 // If this is a templated friend in a dependent context we should not put it
2105 // on the redecl chain. In some cases, the templated friend can be the most
2106 // recent declaration tricking the template instantiator to make substitutions
2107 // there.
2108 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2109 bool ShouldAddRedecl
2110 = !(TUK == TUK_Friend && CurContext->isDependentContext());
2111
2112 CXXRecordDecl *NewClass =
2113 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2114 PrevClassTemplate && ShouldAddRedecl ?
2115 PrevClassTemplate->getTemplatedDecl() : nullptr,
2116 /*DelayTypeCreation=*/true);
2117 SetNestedNameSpecifier(*this, NewClass, SS);
2118 if (NumOuterTemplateParamLists > 0)
2120 Context,
2121 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2122
2123 // Add alignment attributes if necessary; these attributes are checked when
2124 // the ASTContext lays out the structure.
2125 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2128 }
2129
2130 ClassTemplateDecl *NewTemplate
2131 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2132 DeclarationName(Name), TemplateParams,
2133 NewClass);
2134
2135 if (ShouldAddRedecl)
2136 NewTemplate->setPreviousDecl(PrevClassTemplate);
2137
2138 NewClass->setDescribedClassTemplate(NewTemplate);
2139
2140 if (ModulePrivateLoc.isValid())
2141 NewTemplate->setModulePrivate();
2142
2143 // Build the type for the class template declaration now.
2145 T = Context.getInjectedClassNameType(NewClass, T);
2146 assert(T->isDependentType() && "Class template type is not dependent?");
2147 (void)T;
2148
2149 // If we are providing an explicit specialization of a member that is a
2150 // class template, make a note of that.
2151 if (PrevClassTemplate &&
2152 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2153 PrevClassTemplate->setMemberSpecialization();
2154
2155 // Set the access specifier.
2156 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2157 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2158
2159 // Set the lexical context of these templates
2161 NewTemplate->setLexicalDeclContext(CurContext);
2162
2163 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2164 NewClass->startDefinition();
2165
2166 ProcessDeclAttributeList(S, NewClass, Attr);
2167 ProcessAPINotes(NewClass);
2168
2169 if (PrevClassTemplate)
2170 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2171
2174
2175 if (TUK != TUK_Friend) {
2176 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2177 Scope *Outer = S;
2178 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2179 Outer = Outer->getParent();
2180 PushOnScopeChains(NewTemplate, Outer);
2181 } else {
2182 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2183 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2184 NewClass->setAccess(PrevClassTemplate->getAccess());
2185 }
2186
2187 NewTemplate->setObjectOfFriendDecl();
2188
2189 // Friend templates are visible in fairly strange ways.
2191 DeclContext *DC = SemanticContext->getRedeclContext();
2192 DC->makeDeclVisibleInContext(NewTemplate);
2193 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2194 PushOnScopeChains(NewTemplate, EnclosingScope,
2195 /* AddToContext = */ false);
2196 }
2197
2199 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2200 Friend->setAccess(AS_public);
2201 CurContext->addDecl(Friend);
2202 }
2203
2204 if (PrevClassTemplate)
2205 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2206
2207 if (Invalid) {
2208 NewTemplate->setInvalidDecl();
2209 NewClass->setInvalidDecl();
2210 }
2211
2212 ActOnDocumentableDecl(NewTemplate);
2213
2214 if (SkipBody && SkipBody->ShouldSkip)
2215 return SkipBody->Previous;
2216
2217 return NewTemplate;
2218}
2219
2220namespace {
2221/// Tree transform to "extract" a transformed type from a class template's
2222/// constructor to a deduction guide.
2223class ExtractTypeForDeductionGuide
2224 : public TreeTransform<ExtractTypeForDeductionGuide> {
2225 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2226
2227public:
2229 ExtractTypeForDeductionGuide(
2230 Sema &SemaRef,
2231 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2232 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2233
2234 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2235
2236 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2237 ASTContext &Context = SemaRef.getASTContext();
2238 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2239 TypedefNameDecl *Decl = OrigDecl;
2240 // Transform the underlying type of the typedef and clone the Decl only if
2241 // the typedef has a dependent context.
2242 if (OrigDecl->getDeclContext()->isDependentContext()) {
2243 TypeLocBuilder InnerTLB;
2244 QualType Transformed =
2245 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2246 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2247 if (isa<TypeAliasDecl>(OrigDecl))
2249 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2250 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2251 else {
2252 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2254 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2255 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2256 }
2257 MaterializedTypedefs.push_back(Decl);
2258 }
2259
2260 QualType TDTy = Context.getTypedefType(Decl);
2261 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2262 TypedefTL.setNameLoc(TL.getNameLoc());
2263
2264 return TDTy;
2265 }
2266};
2267
2268// Build a deduction guide with the specified parameter types.
2269FunctionTemplateDecl *buildDeductionGuide(
2270 Sema &SemaRef, TemplateDecl *OriginalTemplate,
2271 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2272 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2273 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
2274 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2275 DeclContext *DC = OriginalTemplate->getDeclContext();
2276 auto DeductionGuideName =
2278 OriginalTemplate);
2279
2280 DeclarationNameInfo Name(DeductionGuideName, Loc);
2282 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2283
2284 // Build the implicit deduction guide template.
2285 auto *Guide =
2286 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2287 TInfo->getType(), TInfo, LocEnd, Ctor);
2288 Guide->setImplicit(IsImplicit);
2289 Guide->setParams(Params);
2290
2291 for (auto *Param : Params)
2292 Param->setDeclContext(Guide);
2293 for (auto *TD : MaterializedTypedefs)
2294 TD->setDeclContext(Guide);
2295
2296 auto *GuideTemplate = FunctionTemplateDecl::Create(
2297 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2298 GuideTemplate->setImplicit(IsImplicit);
2299 Guide->setDescribedFunctionTemplate(GuideTemplate);
2300
2301 if (isa<CXXRecordDecl>(DC)) {
2302 Guide->setAccess(AS_public);
2303 GuideTemplate->setAccess(AS_public);
2304 }
2305
2306 DC->addDecl(GuideTemplate);
2307 return GuideTemplate;
2308}
2309
2310// Transform a given template type parameter `TTP`.
2312transformTemplateTypeParam(Sema &SemaRef, DeclContext *DC,
2315 unsigned NewDepth, unsigned NewIndex) {
2316 // TemplateTypeParmDecl's index cannot be changed after creation, so
2317 // substitute it directly.
2318 auto *NewTTP = TemplateTypeParmDecl::Create(
2319 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
2320 NewIndex, TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2321 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2323 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2324 : std::nullopt);
2325 if (const auto *TC = TTP->getTypeConstraint())
2326 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2327 /*EvaluateConstraint=*/true);
2328 if (TTP->hasDefaultArgument()) {
2329 TypeSourceInfo *InstantiatedDefaultArg =
2330 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2331 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2332 if (InstantiatedDefaultArg)
2333 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2334 }
2335 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
2336 return NewTTP;
2337}
2338// Similar to above, but for non-type template or template template parameters.
2339template <typename NonTypeTemplateOrTemplateTemplateParmDecl>
2340NonTypeTemplateOrTemplateTemplateParmDecl *
2341transformTemplateParam(Sema &SemaRef, DeclContext *DC,
2342 NonTypeTemplateOrTemplateTemplateParmDecl *OldParam,
2343 MultiLevelTemplateArgumentList &Args, unsigned NewIndex,
2344 unsigned NewDepth) {
2345 // Ask the template instantiator to do the heavy lifting for us, then adjust
2346 // the index of the parameter once it's done.
2347 auto *NewParam = cast<NonTypeTemplateOrTemplateTemplateParmDecl>(
2348 SemaRef.SubstDecl(OldParam, DC, Args));
2349 NewParam->setPosition(NewIndex);
2350 NewParam->setDepth(NewDepth);
2351 return NewParam;
2352}
2353
2354/// Transform to convert portions of a constructor declaration into the
2355/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2356struct ConvertConstructorToDeductionGuideTransform {
2357 ConvertConstructorToDeductionGuideTransform(Sema &S,
2358 ClassTemplateDecl *Template)
2359 : SemaRef(S), Template(Template) {
2360 // If the template is nested, then we need to use the original
2361 // pattern to iterate over the constructors.
2362 ClassTemplateDecl *Pattern = Template;
2363 while (Pattern->getInstantiatedFromMemberTemplate()) {
2364 if (Pattern->isMemberSpecialization())
2365 break;
2366 Pattern = Pattern->getInstantiatedFromMemberTemplate();
2367 NestedPattern = Pattern;
2368 }
2369
2370 if (NestedPattern)
2371 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2372 }
2373
2374 Sema &SemaRef;
2375 ClassTemplateDecl *Template;
2376 ClassTemplateDecl *NestedPattern = nullptr;
2377
2378 DeclContext *DC = Template->getDeclContext();
2379 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2380 DeclarationName DeductionGuideName =
2382
2383 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2384
2385 // Index adjustment to apply to convert depth-1 template parameters into
2386 // depth-0 template parameters.
2387 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2388
2389 // Instantiation arguments for the outermost depth-1 templates
2390 // when the template is nested
2391 MultiLevelTemplateArgumentList OuterInstantiationArgs;
2392
2393 /// Transform a constructor declaration into a deduction guide.
2394 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2395 CXXConstructorDecl *CD) {
2397
2399
2400 // C++ [over.match.class.deduct]p1:
2401 // -- For each constructor of the class template designated by the
2402 // template-name, a function template with the following properties:
2403
2404 // -- The template parameters are the template parameters of the class
2405 // template followed by the template parameters (including default
2406 // template arguments) of the constructor, if any.
2407 TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2408 if (FTD) {
2409 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2412 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2413 AllParams.insert(AllParams.begin(),
2414 TemplateParams->begin(), TemplateParams->end());
2415 SubstArgs.reserve(InnerParams->size());
2416 Depth1Args.reserve(InnerParams->size());
2417
2418 // Later template parameters could refer to earlier ones, so build up
2419 // a list of substituted template arguments as we go.
2420 for (NamedDecl *Param : *InnerParams) {
2422 Args.setKind(TemplateSubstitutionKind::Rewrite);
2423 Args.addOuterTemplateArguments(Depth1Args);
2424 Args.addOuterRetainedLevel();
2425 if (NestedPattern)
2426 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2427 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2428 if (!NewParam)
2429 return nullptr;
2430 // Constraints require that we substitute depth-1 arguments
2431 // to match depths when substituted for evaluation later
2432 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2433 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2434
2435 if (NestedPattern) {
2436 TemplateDeclInstantiator Instantiator(SemaRef, DC,
2437 OuterInstantiationArgs);
2438 Instantiator.setEvaluateConstraints(false);
2439 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2440 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2441 });
2442 }
2443
2444 assert(NewParam->getTemplateDepth() == 0 &&
2445 "Unexpected template parameter depth");
2446
2447 AllParams.push_back(NewParam);
2448 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2449 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2450 }
2451
2452 // Substitute new template parameters into requires-clause if present.
2453 Expr *RequiresClause = nullptr;
2454 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2456 Args.setKind(TemplateSubstitutionKind::Rewrite);
2457 Args.addOuterTemplateArguments(Depth1Args);
2458 Args.addOuterRetainedLevel();
2459 if (NestedPattern)
2460 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2461 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2462 if (E.isInvalid())
2463 return nullptr;
2464 RequiresClause = E.getAs<Expr>();
2465 }
2466
2467 TemplateParams = TemplateParameterList::Create(
2468 SemaRef.Context, InnerParams->getTemplateLoc(),
2469 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2470 RequiresClause);
2471 }
2472
2473 // If we built a new template-parameter-list, track that we need to
2474 // substitute references to the old parameters into references to the
2475 // new ones.
2477 Args.setKind(TemplateSubstitutionKind::Rewrite);
2478 if (FTD) {
2479 Args.addOuterTemplateArguments(SubstArgs);
2480 Args.addOuterRetainedLevel();
2481 }
2482
2483 if (NestedPattern)
2484 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2485
2488 assert(FPTL && "no prototype for constructor declaration");
2489
2490 // Transform the type of the function, adjusting the return type and
2491 // replacing references to the old parameters with references to the
2492 // new ones.
2493 TypeLocBuilder TLB;
2495 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2496 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2497 MaterializedTypedefs);
2498 if (NewType.isNull())
2499 return nullptr;
2500 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2501
2502 return buildDeductionGuide(
2503 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
2504 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
2505 /*IsImplicit=*/true, MaterializedTypedefs);
2506 }
2507
2508 /// Build a deduction guide with the specified parameter types.
2509 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2510 SourceLocation Loc = Template->getLocation();
2511
2512 // Build the requested type.
2514 EPI.HasTrailingReturn = true;
2515 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2516 DeductionGuideName, EPI);
2517 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2518 if (NestedPattern)
2519 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2520 DeductionGuideName);
2521
2524
2525 // Build the parameters, needed during deduction / substitution.
2527 for (auto T : ParamTypes) {
2528 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
2529 if (NestedPattern)
2530 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2531 DeclarationName());
2532 ParmVarDecl *NewParam =
2533 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
2534 TSI->getType(), TSI, SC_None, nullptr);
2535 NewParam->setScopeInfo(0, Params.size());
2536 FPTL.setParam(Params.size(), NewParam);
2537 Params.push_back(NewParam);
2538 }
2539
2540 return buildDeductionGuide(
2541 SemaRef, Template, GetTemplateParameterList(Template), nullptr,
2542 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
2543 }
2544
2545private:
2546 /// Transform a constructor template parameter into a deduction guide template
2547 /// parameter, rebuilding any internal references to earlier parameters and
2548 /// renumbering as we go.
2549 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2551 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2552 return transformTemplateTypeParam(
2553 SemaRef, DC, TTP, Args, TTP->getDepth() - 1,
2554 Depth1IndexAdjustment + TTP->getIndex());
2555 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2556 return transformTemplateParam(SemaRef, DC, TTP, Args,
2557 Depth1IndexAdjustment + TTP->getIndex(),
2558 TTP->getDepth() - 1);
2559 auto *NTTP = cast<NonTypeTemplateParmDecl>(TemplateParam);
2560 return transformTemplateParam(SemaRef, DC, NTTP, Args,
2561 Depth1IndexAdjustment + NTTP->getIndex(),
2562 NTTP->getDepth() - 1);
2563 }
2564
2565 QualType transformFunctionProtoType(
2569 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2570 SmallVector<QualType, 4> ParamTypes;
2571 const FunctionProtoType *T = TL.getTypePtr();
2572
2573 // -- The types of the function parameters are those of the constructor.
2574 for (auto *OldParam : TL.getParams()) {
2575 ParmVarDecl *NewParam =
2576 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2577 if (NestedPattern && NewParam)
2578 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2579 MaterializedTypedefs);
2580 if (!NewParam)
2581 return QualType();
2582 ParamTypes.push_back(NewParam->getType());
2583 Params.push_back(NewParam);
2584 }
2585
2586 // -- The return type is the class template specialization designated by
2587 // the template-name and template arguments corresponding to the
2588 // template parameters obtained from the class template.
2589 //
2590 // We use the injected-class-name type of the primary template instead.
2591 // This has the convenient property that it is different from any type that
2592 // the user can write in a deduction-guide (because they cannot enter the
2593 // context of the template), so implicit deduction guides can never collide
2594 // with explicit ones.
2595 QualType ReturnType = DeducedType;
2596 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2597
2598 // Resolving a wording defect, we also inherit the variadicness of the
2599 // constructor.
2601 EPI.Variadic = T->isVariadic();
2602 EPI.HasTrailingReturn = true;
2603
2604 QualType Result = SemaRef.BuildFunctionType(
2605 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2606 if (Result.isNull())
2607 return QualType();
2608
2609 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2611 NewTL.setLParenLoc(TL.getLParenLoc());
2612 NewTL.setRParenLoc(TL.getRParenLoc());
2615 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2616 NewTL.setParam(I, Params[I]);
2617
2618 return Result;
2619 }
2620
2621 ParmVarDecl *transformFunctionTypeParam(
2623 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2624 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2625 TypeSourceInfo *NewDI;
2626 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2627 // Expand out the one and only element in each inner pack.
2628 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2629 NewDI =
2630 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2631 OldParam->getLocation(), OldParam->getDeclName());
2632 if (!NewDI) return nullptr;
2633 NewDI =
2634 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2635 PackTL.getTypePtr()->getNumExpansions());
2636 } else
2637 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2638 OldParam->getDeclName());
2639 if (!NewDI)
2640 return nullptr;
2641
2642 // Extract the type. This (for instance) replaces references to typedef
2643 // members of the current instantiations with the definitions of those
2644 // typedefs, avoiding triggering instantiation of the deduced type during
2645 // deduction.
2646 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2647 .transform(NewDI);
2648
2649 // Resolving a wording defect, we also inherit default arguments from the
2650 // constructor.
2651 ExprResult NewDefArg;
2652 if (OldParam->hasDefaultArg()) {
2653 // We don't care what the value is (we won't use it); just create a
2654 // placeholder to indicate there is a default argument.
2655 QualType ParamTy = NewDI->getType();
2656 NewDefArg = new (SemaRef.Context)
2658 ParamTy.getNonLValueExprType(SemaRef.Context),
2659 ParamTy->isLValueReferenceType() ? VK_LValue
2660 : ParamTy->isRValueReferenceType() ? VK_XValue
2661 : VK_PRValue);
2662 }
2663 // Handle arrays and functions decay.
2664 auto NewType = NewDI->getType();
2665 if (NewType->isArrayType() || NewType->isFunctionType())
2666 NewType = SemaRef.Context.getDecayedType(NewType);
2667
2668 ParmVarDecl *NewParam = ParmVarDecl::Create(
2669 SemaRef.Context, DC, OldParam->getInnerLocStart(),
2670 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
2671 OldParam->getStorageClass(), NewDefArg.get());
2672 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2673 OldParam->getFunctionScopeIndex());
2674 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2675 return NewParam;
2676 }
2677};
2678
2679// Find all template parameters that appear in the given DeducedArgs.
2680// Return the indices of the template parameters in the TemplateParams.
2681SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
2682 ArrayRef<NamedDecl *> TemplateParams,
2683 ArrayRef<TemplateArgument> DeducedArgs) {
2684 struct TemplateParamsReferencedFinder
2685 : public RecursiveASTVisitor<TemplateParamsReferencedFinder> {
2686 llvm::DenseSet<NamedDecl *> TemplateParams;
2687 llvm::DenseSet<const NamedDecl *> ReferencedTemplateParams;
2688
2689 TemplateParamsReferencedFinder(ArrayRef<NamedDecl *> TemplateParams)
2690 : TemplateParams(TemplateParams.begin(), TemplateParams.end()) {}
2691
2692 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) {
2693 TTP->getIndex();
2694 MarkAppeared(TTP->getDecl());
2695 return true;
2696 }
2697 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
2698 MarkAppeared(DRE->getFoundDecl());
2699 return true;
2700 }
2701
2702 void MarkAppeared(NamedDecl *ND) {
2703 if (TemplateParams.contains(ND))
2704 ReferencedTemplateParams.insert(ND);
2705 }
2706 };
2707 TemplateParamsReferencedFinder Finder(TemplateParams);
2708 Finder.TraverseTemplateArguments(DeducedArgs);
2709
2710 SmallVector<unsigned> Results;
2711 for (unsigned Index = 0; Index < TemplateParams.size(); ++Index) {
2712 if (Finder.ReferencedTemplateParams.contains(TemplateParams[Index]))
2713 Results.push_back(Index);
2714 }
2715 return Results;
2716}
2717
2718bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
2719 // Check whether we've already declared deduction guides for this template.
2720 // FIXME: Consider storing a flag on the template to indicate this.
2721 assert(Name.getNameKind() ==
2723 "name must be a deduction guide name");
2724 auto Existing = DC->lookup(Name);
2725 for (auto *D : Existing)
2726 if (D->isImplicit())
2727 return true;
2728 return false;
2729}
2730
2731// Build deduction guides for a type alias template.
2732void DeclareImplicitDeductionGuidesForTypeAlias(
2734 auto &Context = SemaRef.Context;
2735 // FIXME: if there is an explicit deduction guide after the first use of the
2736 // type alias usage, we will not cover this explicit deduction guide. fix this
2737 // case.
2738 if (hasDeclaredDeductionGuides(
2740 AliasTemplate->getDeclContext()))
2741 return;
2742 // Unwrap the sugared ElaboratedType.
2743 auto RhsType = AliasTemplate->getTemplatedDecl()
2744 ->getUnderlyingType()
2745 .getSingleStepDesugaredType(Context);
2746 TemplateDecl *Template = nullptr;
2747 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
2748 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
2749 // Cases where the RHS of the alias is dependent. e.g.
2750 // template<typename T>
2751 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
2752 Template = TST->getTemplateName().getAsTemplateDecl();
2753 AliasRhsTemplateArgs = TST->template_arguments();
2754 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
2755 // Cases where template arguments in the RHS of the alias are not
2756 // dependent. e.g.
2757 // using AliasFoo = Foo<bool>;
2758 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
2759 RT->getAsCXXRecordDecl())) {
2760 Template = CTSD->getSpecializedTemplate();
2761 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
2762 }
2763 } else {
2764 assert(false && "unhandled RHS type of the alias");
2765 }
2766 if (!Template)
2767 return;
2768 DeclarationNameInfo NameInfo(
2769 Context.DeclarationNames.getCXXDeductionGuideName(Template), Loc);
2770 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
2771 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
2772 Guides.suppressDiagnostics();
2773
2774 for (auto *G : Guides) {
2775 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(G);
2776 if (!F)
2777 continue;
2778 auto RType = F->getTemplatedDecl()->getReturnType();
2779 // The (trailing) return type of the deduction guide.
2780 const TemplateSpecializationType *FReturnType =
2782 if (const auto *InjectedCNT = RType->getAs<InjectedClassNameType>())
2783 // implicitly-generated deduction guide.
2784 FReturnType = InjectedCNT->getInjectedTST();
2785 else if (const auto *ET = RType->getAs<ElaboratedType>())
2786 // explicit deduction guide.
2787 FReturnType = ET->getNamedType()->getAs<TemplateSpecializationType>();
2788 assert(FReturnType && "expected to see a return type");
2789 // Deduce template arguments of the deduction guide f from the RHS of
2790 // the alias.
2791 //
2792 // C++ [over.match.class.deduct]p3: ...For each function or function
2793 // template f in the guides of the template named by the
2794 // simple-template-id of the defining-type-id, the template arguments
2795 // of the return type of f are deduced from the defining-type-id of A
2796 // according to the process in [temp.deduct.type] with the exception
2797 // that deduction does not fail if not all template arguments are
2798 // deduced.
2799 //
2800 //
2801 // template<typename X, typename Y>
2802 // f(X, Y) -> f<Y, X>;
2803 //
2804 // template<typename U>
2805 // using alias = f<int, U>;
2806 //
2807 // The RHS of alias is f<int, U>, we deduced the template arguments of
2808 // the return type of the deduction guide from it: Y->int, X->U
2809 sema::TemplateDeductionInfo TDeduceInfo(Loc);
2810 // Must initialize n elements, this is required by DeduceTemplateArguments.
2812 F->getTemplateParameters()->size());
2813
2814 // FIXME: DeduceTemplateArguments stops immediately at the first
2815 // non-deducible template argument. However, this doesn't seem to casue
2816 // issues for practice cases, we probably need to extend it to continue
2817 // performing deduction for rest of arguments to align with the C++
2818 // standard.
2820 F->getTemplateParameters(), FReturnType->template_arguments(),
2821 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
2822 /*NumberOfArgumentsMustMatch=*/false);
2823
2825 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
2826 // !!NOTE: DeduceResults respects the sequence of template parameters of
2827 // the deduction guide f.
2828 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2829 if (const auto &D = DeduceResults[Index]; !D.isNull()) // Deduced
2830 DeducedArgs.push_back(D);
2831 else
2832 NonDeducedTemplateParamsInFIndex.push_back(Index);
2833 }
2834 auto DeducedAliasTemplateParams =
2835 TemplateParamsReferencedInTemplateArgumentList(
2836 AliasTemplate->getTemplateParameters()->asArray(), DeducedArgs);
2837 // All template arguments null by default.
2838 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
2839 F->getTemplateParameters()->size());
2840
2841 Sema::InstantiatingTemplate BuildingDeductionGuides(
2842 SemaRef, AliasTemplate->getLocation(), F,
2844 if (BuildingDeductionGuides.isInvalid())
2845 return;
2847
2848 // Create a template parameter list for the synthesized deduction guide f'.
2849 //
2850 // C++ [over.match.class.deduct]p3.2:
2851 // If f is a function template, f' is a function template whose template
2852 // parameter list consists of all the template parameters of A
2853 // (including their default template arguments) that appear in the above
2854 // deductions or (recursively) in their default template arguments
2855 SmallVector<NamedDecl *> FPrimeTemplateParams;
2856 // Store template arguments that refer to the newly-created template
2857 // parameters, used for building `TemplateArgsForBuildingFPrime`.
2858 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
2859 AliasTemplate->getTemplateParameters()->size());
2860 auto TransformTemplateParameter =
2861 [&SemaRef](DeclContext *DC, NamedDecl *TemplateParam,
2863 unsigned NewIndex) -> NamedDecl * {
2864 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2865 return transformTemplateTypeParam(SemaRef, DC, TTP, Args,
2866 TTP->getDepth(), NewIndex);
2867 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2868 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
2869 TTP->getDepth());
2870 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
2871 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
2872 NTTP->getDepth());
2873 return nullptr;
2874 };
2875
2876 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
2877 auto *TP = AliasTemplate->getTemplateParameters()->getParam(
2878 AliasTemplateParamIdx);
2879 // Rebuild any internal references to earlier parameters and reindex as
2880 // we go.
2883 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
2884 NamedDecl *NewParam =
2885 TransformTemplateParameter(AliasTemplate->getDeclContext(), TP, Args,
2886 /*NewIndex*/ FPrimeTemplateParams.size());
2887 FPrimeTemplateParams.push_back(NewParam);
2888
2889 auto NewTemplateArgument = Context.getCanonicalTemplateArgument(
2890 Context.getInjectedTemplateArg(NewParam));
2891 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
2892 }
2893 // ...followed by the template parameters of f that were not deduced
2894 // (including their default template arguments)
2895 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
2896 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
2899 // We take a shortcut here, it is ok to reuse the
2900 // TemplateArgsForBuildingFPrime.
2901 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
2902 NamedDecl *NewParam = TransformTemplateParameter(
2903 F->getDeclContext(), TP, Args, FPrimeTemplateParams.size());
2904 FPrimeTemplateParams.push_back(NewParam);
2905
2906 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
2907 "The argument must be null before setting");
2908 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
2910 Context.getInjectedTemplateArg(NewParam));
2911 }
2912 // Substitute new template parameters into requires-clause if present.
2913 Expr *RequiresClause = nullptr;
2914 if (Expr *InnerRC = F->getTemplateParameters()->getRequiresClause()) {
2917 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
2918 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2919 if (E.isInvalid())
2920 return;
2921 RequiresClause = E.getAs<Expr>();
2922 }
2923 // FIXME: implement the is_deducible constraint per C++
2924 // [over.match.class.deduct]p3.3:
2925 // ... and a constraint that is satisfied if and only if the arguments
2926 // of A are deducible (see below) from the return type.
2927 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
2928 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
2929 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
2930 FPrimeTemplateParams,
2931 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
2932 /*RequiresClause=*/RequiresClause);
2933
2934 // To form a deduction guide f' from f, we leverage clang's instantiation
2935 // mechanism, we construct a template argument list where the template
2936 // arguments refer to the newly-created template parameters of f', and
2937 // then apply instantiation on this template argument list to instantiate
2938 // f, this ensures all template parameter occurrences are updated
2939 // correctly.
2940 //
2941 // The template argument list is formed from the `DeducedArgs`, two parts:
2942 // 1) appeared template parameters of alias: transfrom the deduced
2943 // template argument;
2944 // 2) non-deduced template parameters of f: rebuild a
2945 // template argument;
2946 //
2947 // 2) has been built already (when rebuilding the new template
2948 // parameters), we now perform 1).
2951 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
2952 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2953 const auto &D = DeduceResults[Index];
2954 if (D.isNull()) {
2955 // 2): Non-deduced template parameter has been built already.
2956 assert(!TemplateArgsForBuildingFPrime[Index].isNull() &&
2957 "template arguments for non-deduced template parameters should "
2958 "be been set!");
2959 continue;
2960 }
2962 D, QualType(), SourceLocation{});
2963 TemplateArgumentLoc Output;
2964 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
2965 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
2966 "InstantiatedArgs must be null before setting");
2967 TemplateArgsForBuildingFPrime[Index] = (Output.getArgument());
2968 }
2969 }
2970
2971 auto *TemplateArgListForBuildingFPrime = TemplateArgumentList::CreateCopy(
2972 Context, TemplateArgsForBuildingFPrime);
2973 // Form the f' by substituting the template arguments into f.
2974 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
2975 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
2977 auto *GG = dyn_cast<CXXDeductionGuideDecl>(FPrime);
2978 buildDeductionGuide(SemaRef, AliasTemplate, FPrimeTemplateParamList,
2979 GG->getCorrespondingConstructor(),
2980 GG->getExplicitSpecifier(), GG->getTypeSourceInfo(),
2981 AliasTemplate->getBeginLoc(),
2982 AliasTemplate->getLocation(),
2983 AliasTemplate->getEndLoc(), F->isImplicit());
2984 }
2985 }
2986}
2987
2988} // namespace
2989
2991 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
2992 SourceLocation Loc) {
2993 if (CXXRecordDecl *DefRecord =
2994 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2995 if (TemplateDecl *DescribedTemplate =
2996 DefRecord->getDescribedClassTemplate())
2997 Template = DescribedTemplate;
2998 }
2999
3000 DeclContext *DC = Template->getDeclContext();
3001 if (DC->isDependentContext())
3002 return nullptr;
3003
3004 ConvertConstructorToDeductionGuideTransform Transform(
3005 *this, cast<ClassTemplateDecl>(Template));
3006 if (!isCompleteType(Loc, Transform.DeducedType))
3007 return nullptr;
3008
3009 // In case we were expanding a pack when we attempted to declare deduction
3010 // guides, turn off pack expansion for everything we're about to do.
3011 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
3012 /*NewSubstitutionIndex=*/-1);
3013 // Create a template instantiation record to track the "instantiation" of
3014 // constructors into deduction guides.
3015 InstantiatingTemplate BuildingDeductionGuides(
3016 *this, Loc, Template,
3018 if (BuildingDeductionGuides.isInvalid())
3019 return nullptr;
3020
3021 ClassTemplateDecl *Pattern =
3022 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3023 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3024
3025 auto *DG = cast<FunctionTemplateDecl>(
3026 Transform.buildSimpleDeductionGuide(ParamTypes));
3027 SavedContext.pop();
3028 return DG;
3029}
3030
3032 SourceLocation Loc) {
3033 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
3034 DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
3035 return;
3036 }
3037 if (CXXRecordDecl *DefRecord =
3038 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
3039 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
3040 Template = DescribedTemplate;
3041 }
3042
3043 DeclContext *DC = Template->getDeclContext();
3044 if (DC->isDependentContext())
3045 return;
3046
3047 ConvertConstructorToDeductionGuideTransform Transform(
3048 *this, cast<ClassTemplateDecl>(Template));
3049 if (!isCompleteType(Loc, Transform.DeducedType))
3050 return;
3051
3052 if (hasDeclaredDeductionGuides(Transform.DeductionGuideName, DC))
3053 return;
3054
3055 // In case we were expanding a pack when we attempted to declare deduction
3056 // guides, turn off pack expansion for everything we're about to do.
3057 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3058 // Create a template instantiation record to track the "instantiation" of
3059 // constructors into deduction guides.
3060 InstantiatingTemplate BuildingDeductionGuides(
3061 *this, Loc, Template,
3063 if (BuildingDeductionGuides.isInvalid())
3064 return;
3065
3066 // Convert declared constructors into deduction guide templates.
3067 // FIXME: Skip constructors for which deduction must necessarily fail (those
3068 // for which some class template parameter without a default argument never
3069 // appears in a deduced context).
3070 ClassTemplateDecl *Pattern =
3071 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3072 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3073 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
3074 bool AddedAny = false;
3075 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
3076 D = D->getUnderlyingDecl();
3077 if (D->isInvalidDecl() || D->isImplicit())
3078 continue;
3079
3080 D = cast<NamedDecl>(D->getCanonicalDecl());
3081
3082 // Within C++20 modules, we may have multiple same constructors in
3083 // multiple same RecordDecls. And it doesn't make sense to create
3084 // duplicated deduction guides for the duplicated constructors.
3085 if (ProcessedCtors.count(D))
3086 continue;
3087
3088 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
3089 auto *CD =
3090 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
3091 // Class-scope explicit specializations (MS extension) do not result in
3092 // deduction guides.
3093 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
3094 continue;
3095
3096 // Cannot make a deduction guide when unparsed arguments are present.
3097 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
3098 return !P || P->hasUnparsedDefaultArg();
3099 }))
3100 continue;
3101
3102 ProcessedCtors.insert(D);
3103 Transform.transformConstructor(FTD, CD);
3104 AddedAny = true;
3105 }
3106
3107 // C++17 [over.match.class.deduct]
3108 // -- If C is not defined or does not declare any constructors, an
3109 // additional function template derived as above from a hypothetical
3110 // constructor C().
3111 if (!AddedAny)
3112 Transform.buildSimpleDeductionGuide(std::nullopt);
3113
3114 // -- An additional function template derived as above from a hypothetical
3115 // constructor C(C), called the copy deduction candidate.
3116 cast<CXXDeductionGuideDecl>(
3117 cast<FunctionTemplateDecl>(
3118 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
3119 ->getTemplatedDecl())
3120 ->setDeductionCandidateKind(DeductionCandidate::Copy);
3121
3122 SavedContext.pop();
3123}
3124
3125/// Diagnose the presence of a default template argument on a
3126/// template parameter, which is ill-formed in certain contexts.
3127///
3128/// \returns true if the default template argument should be dropped.
3131 SourceLocation ParamLoc,
3132 SourceRange DefArgRange) {
3133 switch (TPC) {
3137 return false;
3138
3141 // C++ [temp.param]p9:
3142 // A default template-argument shall not be specified in a
3143 // function template declaration or a function template
3144 // definition [...]
3145 // If a friend function template declaration specifies a default
3146 // template-argument, that declaration shall be a definition and shall be
3147 // the only declaration of the function template in the translation unit.
3148 // (C++98/03 doesn't have this wording; see DR226).
3149 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
3150 diag::warn_cxx98_compat_template_parameter_default_in_function_template
3151 : diag::ext_template_parameter_default_in_function_template)
3152 << DefArgRange;
3153 return false;
3154
3156 // C++0x [temp.param]p9:
3157 // A default template-argument shall not be specified in the
3158 // template-parameter-lists of the definition of a member of a
3159 // class template that appears outside of the member's class.
3160 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
3161 << DefArgRange;
3162 return true;
3163
3166 // C++ [temp.param]p9:
3167 // A default template-argument shall not be specified in a
3168 // friend template declaration.
3169 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
3170 << DefArgRange;
3171 return true;
3172
3173 // FIXME: C++0x [temp.param]p9 allows default template-arguments
3174 // for friend function templates if there is only a single
3175 // declaration (and it is a definition). Strange!
3176 }
3177
3178 llvm_unreachable("Invalid TemplateParamListContext!");
3179}
3180
3181/// Check for unexpanded parameter packs within the template parameters
3182/// of a template template parameter, recursively.
3185 // A template template parameter which is a parameter pack is also a pack
3186 // expansion.
3187 if (TTP->isParameterPack())
3188 return false;
3189
3191 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3192 NamedDecl *P = Params->getParam(I);
3193 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
3194 if (!TTP->isParameterPack())
3195 if (const TypeConstraint *TC = TTP->getTypeConstraint())
3196 if (TC->hasExplicitTemplateArgs())
3197 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3200 return true;
3201 continue;
3202 }
3203
3204 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
3205 if (!NTTP->isParameterPack() &&
3206 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
3207 NTTP->getTypeSourceInfo(),
3209 return true;
3210
3211 continue;
3212 }
3213
3214 if (TemplateTemplateParmDecl *InnerTTP
3215 = dyn_cast<TemplateTemplateParmDecl>(P))
3216 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
3217 return true;
3218 }
3219
3220 return false;
3221}
3222
3223/// Checks the validity of a template parameter list, possibly
3224/// considering the template parameter list from a previous
3225/// declaration.
3226///
3227/// If an "old" template parameter list is provided, it must be
3228/// equivalent (per TemplateParameterListsAreEqual) to the "new"
3229/// template parameter list.
3230///
3231/// \param NewParams Template parameter list for a new template
3232/// declaration. This template parameter list will be updated with any
3233/// default arguments that are carried through from the previous
3234/// template parameter list.
3235///
3236/// \param OldParams If provided, template parameter list from a
3237/// previous declaration of the same template. Default template
3238/// arguments will be merged from the old template parameter list to
3239/// the new template parameter list.
3240///
3241/// \param TPC Describes the context in which we are checking the given
3242/// template parameter list.
3243///
3244/// \param SkipBody If we might have already made a prior merged definition
3245/// of this template visible, the corresponding body-skipping information.
3246/// Default argument redefinition is not an error when skipping such a body,
3247/// because (under the ODR) we can assume the default arguments are the same
3248/// as the prior merged definition.
3249///
3250/// \returns true if an error occurred, false otherwise.
3252 TemplateParameterList *OldParams,
3254 SkipBodyInfo *SkipBody) {
3255 bool Invalid = false;
3256
3257 // C++ [temp.param]p10:
3258 // The set of default template-arguments available for use with a
3259 // template declaration or definition is obtained by merging the
3260 // default arguments from the definition (if in scope) and all
3261 // declarations in scope in the same way default function
3262 // arguments are (8.3.6).
3263 bool SawDefaultArgument = false;
3264 SourceLocation PreviousDefaultArgLoc;
3265
3266 // Dummy initialization to avoid warnings.
3267 TemplateParameterList::iterator OldParam = NewParams->end();
3268 if (OldParams)
3269 OldParam = OldParams->begin();
3270
3271 bool RemoveDefaultArguments = false;
3272 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3273 NewParamEnd = NewParams->end();
3274 NewParam != NewParamEnd; ++NewParam) {
3275 // Whether we've seen a duplicate default argument in the same translation
3276 // unit.
3277 bool RedundantDefaultArg = false;
3278 // Whether we've found inconsis inconsitent default arguments in different
3279 // translation unit.
3280 bool InconsistentDefaultArg = false;
3281 // The name of the module which contains the inconsistent default argument.
3282 std::string PrevModuleName;
3283
3284 SourceLocation OldDefaultLoc;
3285 SourceLocation NewDefaultLoc;
3286
3287 // Variable used to diagnose missing default arguments
3288 bool MissingDefaultArg = false;
3289
3290 // Variable used to diagnose non-final parameter packs
3291 bool SawParameterPack = false;
3292
3293 if (TemplateTypeParmDecl *NewTypeParm
3294 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
3295 // Check the presence of a default argument here.
3296 if (NewTypeParm->hasDefaultArgument() &&
3298 NewTypeParm->getLocation(),
3299 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
3300 .getSourceRange()))
3301 NewTypeParm->removeDefaultArgument();
3302
3303 // Merge default arguments for template type parameters.
3304 TemplateTypeParmDecl *OldTypeParm
3305 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
3306 if (NewTypeParm->isParameterPack()) {
3307 assert(!NewTypeParm->hasDefaultArgument() &&
3308 "Parameter packs can't have a default argument!");
3309 SawParameterPack = true;
3310 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
3311 NewTypeParm->hasDefaultArgument() &&
3312 (!SkipBody || !SkipBody->ShouldSkip)) {
3313 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
3314 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
3315 SawDefaultArgument = true;
3316
3317 if (!OldTypeParm->getOwningModule())
3318 RedundantDefaultArg = true;
3319 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
3320 NewTypeParm)) {
3321 InconsistentDefaultArg = true;
3322 PrevModuleName =
3324 }
3325 PreviousDefaultArgLoc = NewDefaultLoc;
3326 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
3327 // Merge the default argument from the old declaration to the
3328 // new declaration.
3329 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
3330 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
3331 } else if (NewTypeParm->hasDefaultArgument()) {
3332 SawDefaultArgument = true;
3333 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
3334 } else if (SawDefaultArgument)
3335 MissingDefaultArg = true;
3336 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
3337 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
3338 // Check for unexpanded parameter packs.
3339 if (!NewNonTypeParm->isParameterPack() &&
3340 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
3341 NewNonTypeParm->getTypeSourceInfo(),
3343 Invalid = true;
3344 continue;
3345 }
3346
3347 // Check the presence of a default argument here.
3348 if (NewNonTypeParm->hasDefaultArgument() &&
3350 NewNonTypeParm->getLocation(),
3351 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
3352 NewNonTypeParm->removeDefaultArgument();
3353 }
3354
3355 // Merge default arguments for non-type template parameters
3356 NonTypeTemplateParmDecl *OldNonTypeParm
3357 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
3358 if (NewNonTypeParm->isParameterPack()) {
3359 assert(!NewNonTypeParm->hasDefaultArgument() &&
3360 "Parameter packs can't have a default argument!");
3361 if (!NewNonTypeParm->isPackExpansion())
3362 SawParameterPack = true;
3363 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3364 NewNonTypeParm->hasDefaultArgument() &&
3365 (!SkipBody || !SkipBody->ShouldSkip)) {
3366 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3367 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3368 SawDefaultArgument = true;
3369 if (!OldNonTypeParm->getOwningModule())
3370 RedundantDefaultArg = true;
3371 else if (!getASTContext().isSameDefaultTemplateArgument(
3372 OldNonTypeParm, NewNonTypeParm)) {
3373 InconsistentDefaultArg = true;
3374 PrevModuleName =
3375 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3376 }
3377 PreviousDefaultArgLoc = NewDefaultLoc;
3378 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3379 // Merge the default argument from the old declaration to the
3380 // new declaration.
3381 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
3382 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3383 } else if (NewNonTypeParm->hasDefaultArgument()) {
3384 SawDefaultArgument = true;
3385 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3386 } else if (SawDefaultArgument)
3387 MissingDefaultArg = true;
3388 } else {
3389 TemplateTemplateParmDecl *NewTemplateParm
3390 = cast<TemplateTemplateParmDecl>(*NewParam);
3391
3392 // Check for unexpanded parameter packs, recursively.
3393 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
3394 Invalid = true;
3395 continue;
3396 }
3397
3398 // Check the presence of a default argument here.
3399 if (NewTemplateParm->hasDefaultArgument() &&
3401 NewTemplateParm->getLocation(),
3402 NewTemplateParm->getDefaultArgument().getSourceRange()))
3403 NewTemplateParm->removeDefaultArgument();
3404
3405 // Merge default arguments for template template parameters
3406 TemplateTemplateParmDecl *OldTemplateParm
3407 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
3408 if (NewTemplateParm->isParameterPack()) {
3409 assert(!NewTemplateParm->hasDefaultArgument() &&
3410 "Parameter packs can't have a default argument!");
3411 if (!NewTemplateParm->isPackExpansion())
3412 SawParameterPack = true;
3413 } else if (OldTemplateParm &&
3414 hasVisibleDefaultArgument(OldTemplateParm) &&
3415 NewTemplateParm->hasDefaultArgument() &&
3416 (!SkipBody || !SkipBody->ShouldSkip)) {
3417 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3418 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3419 SawDefaultArgument = true;
3420 if (!OldTemplateParm->getOwningModule())
3421 RedundantDefaultArg = true;
3422 else if (!getASTContext().isSameDefaultTemplateArgument(
3423 OldTemplateParm, NewTemplateParm)) {
3424 InconsistentDefaultArg = true;
3425 PrevModuleName =
3426 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3427 }
3428 PreviousDefaultArgLoc = NewDefaultLoc;
3429 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3430 // Merge the default argument from the old declaration to the
3431 // new declaration.
3432 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3433 PreviousDefaultArgLoc
3434 = OldTemplateParm->getDefaultArgument().getLocation();
3435 } else if (NewTemplateParm->hasDefaultArgument()) {
3436 SawDefaultArgument = true;
3437 PreviousDefaultArgLoc
3438 = NewTemplateParm->getDefaultArgument().getLocation();
3439 } else if (SawDefaultArgument)
3440 MissingDefaultArg = true;
3441 }
3442
3443 // C++11 [temp.param]p11:
3444 // If a template parameter of a primary class template or alias template
3445 // is a template parameter pack, it shall be the last template parameter.
3446 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3447 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3448 TPC == TPC_TypeAliasTemplate)) {
3449 Diag((*NewParam)->getLocation(),
3450 diag::err_template_param_pack_must_be_last_template_parameter);
3451 Invalid = true;
3452 }
3453
3454 // [basic.def.odr]/13:
3455 // There can be more than one definition of a
3456 // ...
3457 // default template argument
3458 // ...
3459 // in a program provided that each definition appears in a different
3460 // translation unit and the definitions satisfy the [same-meaning
3461 // criteria of the ODR].
3462 //
3463 // Simply, the design of modules allows the definition of template default
3464 // argument to be repeated across translation unit. Note that the ODR is
3465 // checked elsewhere. But it is still not allowed to repeat template default
3466 // argument in the same translation unit.
3467 if (RedundantDefaultArg) {
3468 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3469 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3470 Invalid = true;
3471 } else if (InconsistentDefaultArg) {
3472 // We could only diagnose about the case that the OldParam is imported.
3473 // The case NewParam is imported should be handled in ASTReader.
3474 Diag(NewDefaultLoc,
3475 diag::err_template_param_default_arg_inconsistent_redefinition);
3476 Diag(OldDefaultLoc,
3477 diag::note_template_param_prev_default_arg_in_other_module)
3478 << PrevModuleName;
3479 Invalid = true;
3480 } else if (MissingDefaultArg &&
3481 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
3482 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
3483 // C++ 23[temp.param]p14:
3484 // If a template-parameter of a class template, variable template, or
3485 // alias template has a default template argument, each subsequent
3486 // template-parameter shall either have a default template argument
3487 // supplied or be a template parameter pack.
3488 Diag((*NewParam)->getLocation(),
3489 diag::err_template_param_default_arg_missing);
3490 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3491 Invalid = true;
3492 RemoveDefaultArguments = true;
3493 }
3494
3495 // If we have an old template parameter list that we're merging
3496 // in, move on to the next parameter.
3497 if (OldParams)
3498 ++OldParam;
3499 }
3500
3501 // We were missing some default arguments at the end of the list, so remove
3502 // all of the default arguments.
3503 if (RemoveDefaultArguments) {
3504 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3505 NewParamEnd = NewParams->end();
3506 NewParam != NewParamEnd; ++NewParam) {
3507 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3508 TTP->removeDefaultArgument();
3509 else if (NonTypeTemplateParmDecl *NTTP
3510 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3511 NTTP->removeDefaultArgument();
3512 else
3513 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3514 }
3515 }
3516
3517 return Invalid;
3518}
3519
3520namespace {
3521
3522/// A class which looks for a use of a certain level of template
3523/// parameter.
3524struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3526
3527 unsigned Depth;
3528
3529 // Whether we're looking for a use of a template parameter that makes the
3530 // overall construct type-dependent / a dependent type. This is strictly
3531 // best-effort for now; we may fail to match at all for a dependent type
3532 // in some cases if this is set.
3533 bool IgnoreNonTypeDependent;
3534
3535 bool Match;
3536 SourceLocation MatchLoc;
3537
3538 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3539 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3540 Match(false) {}
3541
3542 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3543 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3544 NamedDecl *ND = Params->getParam(0);
3545 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3546 Depth = PD->getDepth();
3547 } else if (NonTypeTemplateParmDecl *PD =
3548 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3549 Depth = PD->getDepth();
3550 } else {
3551 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3552 }
3553 }
3554
3555 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3556 if (ParmDepth >= Depth) {
3557 Match = true;
3558 MatchLoc = Loc;
3559 return true;
3560 }
3561 return false;
3562 }
3563
3564 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3565 // Prune out non-type-dependent expressions if requested. This can
3566 // sometimes result in us failing to find a template parameter reference
3567 // (if a value-dependent expression creates a dependent type), but this
3568 // mode is best-effort only.
3569 if (auto *E = dyn_cast_or_null<Expr>(S))
3570 if (IgnoreNonTypeDependent && !E->isTypeDependent())
3571 return true;
3572 return super::TraverseStmt(S, Q);
3573 }
3574
3575 bool TraverseTypeLoc(TypeLoc TL) {
3576 if (IgnoreNonTypeDependent && !TL.isNull() &&
3577 !TL.getType()->isDependentType())
3578 return true;
3579 return super::TraverseTypeLoc(TL);
3580 }
3581
3582 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3583 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3584 }
3585
3586 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3587 // For a best-effort search, keep looking until we find a location.
3588 return IgnoreNonTypeDependent || !Matches(T->getDepth());
3589 }
3590
3591 bool TraverseTemplateName(TemplateName N) {
3592 if (TemplateTemplateParmDecl *PD =
3593 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3594 if (Matches(PD->getDepth()))
3595 return false;
3596 return super::TraverseTemplateName(N);
3597 }
3598
3599 bool VisitDeclRefExpr(DeclRefExpr *E) {
3600 if (NonTypeTemplateParmDecl *PD =
3601 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3602 if (Matches(PD->getDepth(), E->getExprLoc()))
3603 return false;
3604 return super::VisitDeclRefExpr(E);
3605 }
3606
3607 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3608 return TraverseType(T->getReplacementType());
3609 }
3610
3611 bool
3612 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3613 return TraverseTemplateArgument(T->getArgumentPack());
3614 }
3615
3616 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3617 return TraverseType(T->getInjectedSpecializationType());
3618 }
3619};
3620} // end anonymous namespace
3621
3622/// Determines whether a given type depends on the given parameter
3623/// list.
3624static bool
3626 if (!Params->size())
3627 return false;
3628
3629 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3630 Checker.TraverseType(T);
3631 return Checker.Match;
3632}
3633
3634// Find the source range corresponding to the named type in the given
3635// nested-name-specifier, if any.
3637 QualType T,
3638 const CXXScopeSpec &SS) {
3640 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3641 if (const Type *CurType = NNS->getAsType()) {
3642 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3643 return NNSLoc.getTypeLoc().getSourceRange();
3644 } else
3645 break;
3646
3647 NNSLoc = NNSLoc.getPrefix();
3648 }
3649
3650 return SourceRange();
3651}
3652
3653/// Match the given template parameter lists to the given scope
3654/// specifier, returning the template parameter list that applies to the
3655/// name.
3656///
3657/// \param DeclStartLoc the start of the declaration that has a scope
3658/// specifier or a template parameter list.
3659///
3660/// \param DeclLoc The location of the declaration itself.
3661///
3662/// \param SS the scope specifier that will be matched to the given template
3663/// parameter lists. This scope specifier precedes a qualified name that is
3664/// being declared.
3665///
3666/// \param TemplateId The template-id following the scope specifier, if there
3667/// is one. Used to check for a missing 'template<>'.
3668///
3669/// \param ParamLists the template parameter lists, from the outermost to the
3670/// innermost template parameter lists.
3671///
3672/// \param IsFriend Whether to apply the slightly different rules for
3673/// matching template parameters to scope specifiers in friend
3674/// declarations.
3675///
3676/// \param IsMemberSpecialization will be set true if the scope specifier
3677/// denotes a fully-specialized type, and therefore this is a declaration of
3678/// a member specialization.
3679///
3680/// \returns the template parameter list, if any, that corresponds to the
3681/// name that is preceded by the scope specifier @p SS. This template
3682/// parameter list may have template parameters (if we're declaring a
3683/// template) or may have no template parameters (if we're declaring a
3684/// template specialization), or may be NULL (if what we're declaring isn't
3685/// itself a template).
3687 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3688 TemplateIdAnnotation *TemplateId,
3689 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3690 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3691 IsMemberSpecialization = false;
3692 Invalid = false;
3693
3694 // The sequence of nested types to which we will match up the template
3695 // parameter lists. We first build this list by starting with the type named
3696 // by the nested-name-specifier and walking out until we run out of types.
3697 SmallVector<QualType, 4> NestedTypes;
3698 QualType T;
3699 if (SS.getScopeRep()) {
3701 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3703 else
3704 T = QualType(SS.getScopeRep()->getAsType(), 0);
3705 }
3706
3707 // If we found an explicit specialization that prevents us from needing
3708 // 'template<>' headers, this will be set to the location of that
3709 // explicit specialization.
3710 SourceLocation ExplicitSpecLoc;
3711
3712 while (!T.isNull()) {
3713 NestedTypes.push_back(T);
3714
3715 // Retrieve the parent of a record type.
3717 // If this type is an explicit specialization, we're done.
3719 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3720 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3721 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3722 ExplicitSpecLoc = Spec->getLocation();
3723 break;
3724 }
3725 } else if (Record->getTemplateSpecializationKind()
3727 ExplicitSpecLoc = Record->getLocation();
3728 break;
3729 }
3730
3731 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3733 else
3734 T = QualType();
3735 continue;
3736 }
3737
3738 if (const TemplateSpecializationType *TST
3740 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3741 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3743 else
3744 T = QualType();
3745 continue;
3746 }
3747 }
3748
3749 // Look one step prior in a dependent template specialization type.
3750 if (const DependentTemplateSpecializationType *DependentTST
3752 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3753 T = QualType(NNS->getAsType(), 0);
3754 else
3755 T = QualType();
3756 continue;
3757 }
3758
3759 // Look one step prior in a dependent name type.
3760 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3761 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3762 T = QualType(NNS->getAsType(), 0);
3763 else
3764 T = QualType();
3765 continue;
3766 }
3767
3768 // Retrieve the parent of an enumeration type.
3769 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3770 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3771 // check here.
3772 EnumDecl *Enum = EnumT->getDecl();
3773
3774 // Get to the parent type.
3775 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3777 else
3778 T = QualType();
3779 continue;
3780 }
3781
3782 T = QualType();
3783 }
3784 // Reverse the nested types list, since we want to traverse from the outermost
3785 // to the innermost while checking template-parameter-lists.
3786 std::reverse(NestedTypes.begin(), NestedTypes.end());
3787
3788 // C++0x [temp.expl.spec]p17:
3789 // A member or a member template may be nested within many
3790 // enclosing class templates. In an explicit specialization for
3791 // such a member, the member declaration shall be preceded by a
3792 // template<> for each enclosing class template that is
3793 // explicitly specialized.
3794 bool SawNonEmptyTemplateParameterList = false;
3795
3796 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3797 if (SawNonEmptyTemplateParameterList) {
3798 if (!SuppressDiagnostic)
3799 Diag(DeclLoc, diag::err_specialize_member_of_template)
3800 << !Recovery << Range;
3801 Invalid = true;
3802 IsMemberSpecialization = false;
3803 return true;
3804 }
3805
3806 return false;
3807 };
3808
3809 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3810 // Check that we can have an explicit specialization here.
3811 if (CheckExplicitSpecialization(Range, true))
3812 return true;
3813
3814 // We don't have a template header, but we should.
3815 SourceLocation ExpectedTemplateLoc;
3816 if (!ParamLists.empty())
3817 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3818 else
3819 ExpectedTemplateLoc = DeclStartLoc;
3820
3821 if (!SuppressDiagnostic)
3822 Diag(DeclLoc, diag::err_template_spec_needs_header)
3823 << Range
3824 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3825 return false;
3826 };
3827
3828 unsigned ParamIdx = 0;
3829 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3830 ++TypeIdx) {
3831 T = NestedTypes[TypeIdx];
3832
3833 // Whether we expect a 'template<>' header.
3834 bool NeedEmptyTemplateHeader = false;
3835
3836 // Whether we expect a template header with parameters.
3837 bool NeedNonemptyTemplateHeader = false;
3838
3839 // For a dependent type, the set of template parameters that we
3840 // expect to see.
3841 TemplateParameterList *ExpectedTemplateParams = nullptr;
3842
3843 // C++0x [temp.expl.spec]p15:
3844 // A member or a member template may be nested within many enclosing
3845 // class templates. In an explicit specialization for such a member, the
3846 // member declaration shall be preceded by a template<> for each
3847 // enclosing class template that is explicitly specialized.
3850 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3851 ExpectedTemplateParams = Partial->getTemplateParameters();
3852 NeedNonemptyTemplateHeader = true;
3853 } else if (Record->isDependentType()) {
3854 if (Record->getDescribedClassTemplate()) {
3855 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3856 ->getTemplateParameters();
3857 NeedNonemptyTemplateHeader = true;
3858 }
3859 } else if (ClassTemplateSpecializationDecl *Spec
3860 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3861 // C++0x [temp.expl.spec]p4:
3862 // Members of an explicitly specialized class template are defined
3863 // in the same manner as members of normal classes, and not using
3864 // the template<> syntax.
3865 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3866 NeedEmptyTemplateHeader = true;
3867 else
3868 continue;
3869 } else if (Record->getTemplateSpecializationKind()) {
3870 if (Record->getTemplateSpecializationKind()
3872 TypeIdx == NumTypes - 1)
3873 IsMemberSpecialization = true;
3874
3875 continue;
3876 }
3877 } else if (const TemplateSpecializationType *TST
3879 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3880 ExpectedTemplateParams = Template->getTemplateParameters();
3881 NeedNonemptyTemplateHeader = true;
3882 }
3883 } else if (T->getAs<DependentTemplateSpecializationType>()) {
3884 // FIXME: We actually could/should check the template arguments here
3885 // against the corresponding template parameter list.
3886 NeedNonemptyTemplateHeader = false;
3887 }
3888
3889 // C++ [temp.expl.spec]p16:
3890 // In an explicit specialization declaration for a member of a class
3891 // template or a member template that ap- pears in namespace scope, the
3892 // member template and some of its enclosing class templates may remain
3893 // unspecialized, except that the declaration shall not explicitly
3894 // specialize a class member template if its en- closing class templates
3895 // are not explicitly specialized as well.
3896 if (ParamIdx < ParamLists.size()) {
3897 if (ParamLists[ParamIdx]->size() == 0) {
3898 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3899 false))
3900 return nullptr;
3901 } else
3902 SawNonEmptyTemplateParameterList = true;
3903 }
3904
3905 if (NeedEmptyTemplateHeader) {
3906 // If we're on the last of the types, and we need a 'template<>' header
3907 // here, then it's a member specialization.
3908 if (TypeIdx == NumTypes - 1)
3909 IsMemberSpecialization = true;
3910
3911 if (ParamIdx < ParamLists.size()) {
3912 if (ParamLists[ParamIdx]->size() > 0) {
3913 // The header has template parameters when it shouldn't. Complain.
3914 if (!SuppressDiagnostic)
3915 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3916 diag::err_template_param_list_matches_nontemplate)
3917 << T
3918 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3919 ParamLists[ParamIdx]->getRAngleLoc())
3921 Invalid = true;
3922 return nullptr;
3923 }
3924
3925 // Consume this template header.
3926 ++ParamIdx;
3927 continue;
3928 }
3929
3930 if (!IsFriend)
3931 if (DiagnoseMissingExplicitSpecialization(
3933 return nullptr;
3934
3935 continue;
3936 }
3937
3938 if (NeedNonemptyTemplateHeader) {
3939 // In friend declarations we can have template-ids which don't
3940 // depend on the corresponding template parameter lists. But
3941 // assume that empty parameter lists are supposed to match this
3942 // template-id.
3943 if (IsFriend && T->isDependentType()) {
3944 if (ParamIdx < ParamLists.size() &&
3945 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3946 ExpectedTemplateParams = nullptr;
3947 else
3948 continue;
3949 }
3950
3951 if (ParamIdx < ParamLists.size()) {
3952 // Check the template parameter list, if we can.
3953 if (ExpectedTemplateParams &&
3955 ExpectedTemplateParams,
3956 !SuppressDiagnostic, TPL_TemplateMatch))
3957 Invalid = true;
3958
3959 if (!Invalid &&
3960 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3962 Invalid = true;
3963
3964 ++ParamIdx;
3965 continue;
3966 }
3967
3968 if (!SuppressDiagnostic)
3969 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3970 << T
3972 Invalid = true;
3973 continue;
3974 }
3975 }
3976
3977 // If there were at least as many template-ids as there were template
3978 // parameter lists, then there are no template parameter lists remaining for
3979 // the declaration itself.
3980 if (ParamIdx >= ParamLists.size()) {
3981 if (TemplateId && !IsFriend) {
3982 // We don't have a template header for the declaration itself, but we
3983 // should.
3984 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3985 TemplateId->RAngleLoc));
3986
3987 // Fabricate an empty template parameter list for the invented header.
3989 SourceLocation(), std::nullopt,
3990 SourceLocation(), nullptr);
3991 }
3992
3993 return nullptr;
3994 }
3995
3996 // If there were too many template parameter lists, complain about that now.
3997 if (ParamIdx < ParamLists.size() - 1) {
3998 bool HasAnyExplicitSpecHeader = false;
3999 bool AllExplicitSpecHeaders = true;
4000 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
4001 if (ParamLists[I]->size() == 0)
4002 HasAnyExplicitSpecHeader = true;
4003 else
4004 AllExplicitSpecHeaders = false;
4005 }
4006
4007 if (!SuppressDiagnostic)
4008 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4009 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
4010 : diag::err_template_spec_extra_headers)
4011 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
4012 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
4013
4014 // If there was a specialization somewhere, such that 'template<>' is
4015 // not required, and there were any 'template<>' headers, note where the
4016 // specialization occurred.
4017 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
4018 !SuppressDiagnostic)
4019 Diag(ExplicitSpecLoc,
4020 diag::note_explicit_template_spec_does_not_need_header)
4021 << NestedTypes.back();
4022
4023 // We have a template parameter list with no corresponding scope, which
4024 // means that the resulting template declaration can't be instantiated
4025 // properly (we'll end up with dependent nodes when we shouldn't).
4026 if (!AllExplicitSpecHeaders)
4027 Invalid = true;
4028 }
4029
4030 // C++ [temp.expl.spec]p16:
4031 // In an explicit specialization declaration for a member of a class
4032 // template or a member template that ap- pears in namespace scope, the
4033 // member template and some of its enclosing class templates may remain
4034 // unspecialized, except that the declaration shall not explicitly
4035 // specialize a class member template if its en- closing class templates
4036 // are not explicitly specialized as well.
4037 if (ParamLists.back()->size() == 0 &&
4038 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4039 false))
4040 return nullptr;
4041
4042 // Return the last template parameter list, which corresponds to the
4043 // entity being declared.
4044 return ParamLists.back();
4045}
4046
4048 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4049 Diag(Template->getLocation(), diag::note_template_declared_here)
4050 << (isa<FunctionTemplateDecl>(Template)
4051 ? 0
4052 : isa<ClassTemplateDecl>(Template)
4053 ? 1
4054 : isa<VarTemplateDecl>(Template)
4055 ? 2
4056 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
4057 << Template->getDeclName();
4058 return;
4059 }
4060
4061 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
4062 for (OverloadedTemplateStorage::iterator I = OST->begin(),
4063 IEnd = OST->end();
4064 I != IEnd; ++I)
4065 Diag((*I)->getLocation(), diag::note_template_declared_here)
4066 << 0 << (*I)->getDeclName();
4067
4068 return;
4069 }
4070}
4071
4072static QualType
4075 SourceLocation TemplateLoc,
4076 TemplateArgumentListInfo &TemplateArgs) {
4077 ASTContext &Context = SemaRef.getASTContext();
4078
4079 switch (BTD->getBuiltinTemplateKind()) {
4080 case BTK__make_integer_seq: {
4081 // Specializations of __make_integer_seq<S, T, N> are treated like
4082 // S<T, 0, ..., N-1>.
4083
4084 QualType OrigType = Converted[1].getAsType();
4085 // C++14 [inteseq.intseq]p1:
4086 // T shall be an integer type.
4087 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
4088 SemaRef.Diag(TemplateArgs[1].getLocation(),
4089 diag::err_integer_sequence_integral_element_type);
4090 return QualType();
4091 }
4092
4093 TemplateArgument NumArgsArg = Converted[2];
4094 if (NumArgsArg.isDependent())
4096 Converted);
4097
4098 TemplateArgumentListInfo SyntheticTemplateArgs;
4099 // The type argument, wrapped in substitution sugar, gets reused as the
4100 // first template argument in the synthetic template argument list.
4101 SyntheticTemplateArgs.addArgument(
4104 OrigType, TemplateArgs[1].getLocation())));
4105
4106 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
4107 // Expand N into 0 ... N-1.
4108 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
4109 I < NumArgs; ++I) {
4110 TemplateArgument TA(Context, I, OrigType);
4111 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
4112 TA, OrigType, TemplateArgs[2].getLocation()));
4113 }
4114 } else {
4115 // C++14 [inteseq.make]p1:
4116 // If N is negative the program is ill-formed.
4117 SemaRef.Diag(TemplateArgs[2].getLocation(),
4118 diag::err_integer_sequence_negative_length);
4119 return QualType();
4120 }
4121
4122 // The first template argument will be reused as the template decl that
4123 // our synthetic template arguments will be applied to.
4124 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
4125 TemplateLoc, SyntheticTemplateArgs);
4126 }
4127
4129 // Specializations of
4130 // __type_pack_element<Index, T_1, ..., T_N>
4131 // are treated like T_Index.
4132 assert(Converted.size() == 2 &&
4133 "__type_pack_element should be given an index and a parameter pack");
4134
4135 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
4136 if (IndexArg.isDependent() || Ts.isDependent())
4138 Converted);
4139
4140 llvm::APSInt Index = IndexArg.getAsIntegral();
4141 assert(Index >= 0 && "the index used with __type_pack_element should be of "
4142 "type std::size_t, and hence be non-negative");
4143 // If the Index is out of bounds, the program is ill-formed.
4144 if (Index >= Ts.pack_size()) {
4145 SemaRef.Diag(TemplateArgs[0].getLocation(),
4146 diag::err_type_pack_element_out_of_bounds);
4147 return QualType();
4148 }
4149
4150 // We simply return the type at index `Index`.
4151 int64_t N = Index.getExtValue();
4152 return Ts.getPackAsArray()[N].getAsType();
4153 }
4154 llvm_unreachable("unexpected BuiltinTemplateDecl!");
4155}
4156
4157/// Determine whether this alias template is "enable_if_t".
4158/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
4160 return AliasTemplate->getName().equals("enable_if_t") ||
4161 AliasTemplate->getName().equals("__enable_if_t");
4162}
4163
4164/// Collect all of the separable terms in the given condition, which
4165/// might be a conjunction.
4166///
4167/// FIXME: The right answer is to convert the logical expression into
4168/// disjunctive normal form, so we can find the first failed term
4169/// within each possible clause.
4170static void collectConjunctionTerms(Expr *Clause,
4171 SmallVectorImpl<Expr *> &Terms) {
4172 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
4173 if (BinOp->getOpcode() == BO_LAnd) {
4174 collectConjunctionTerms(BinOp->getLHS(), Terms);
4175 collectConjunctionTerms(BinOp->getRHS(), Terms);
4176 return;
4177 }
4178 }
4179
4180 Terms.push_back(Clause);
4181}
4182
4183// The ranges-v3 library uses an odd pattern of a top-level "||" with
4184// a left-hand side that is value-dependent but never true. Identify
4185// the idiom and ignore that term.
4187 // Top-level '||'.
4188 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
4189 if (!BinOp) return Cond;
4190
4191 if (BinOp->getOpcode() != BO_LOr) return Cond;
4192
4193 // With an inner '==' that has a literal on the right-hand side.
4194 Expr *LHS = BinOp->getLHS();
4195 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
4196 if (!InnerBinOp) return Cond;
4197
4198 if (InnerBinOp->getOpcode() != BO_EQ ||
4199 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
4200 return Cond;
4201
4202 // If the inner binary operation came from a macro expansion named
4203 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
4204 // of the '||', which is the real, user-provided condition.
4205 SourceLocation Loc = InnerBinOp->getExprLoc();
4206 if (!Loc.isMacroID()) return Cond;
4207
4208 StringRef MacroName = PP.getImmediateMacroName(Loc);
4209 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
4210 return BinOp->getRHS();
4211
4212 return Cond;
4213}
4214
4215namespace {
4216
4217// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
4218// within failing boolean expression, such as substituting template parameters
4219// for actual types.
4220class FailedBooleanConditionPrinterHelper : public PrinterHelper {
4221public:
4222 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
4223 : Policy(P) {}
4224
4225 bool handledStmt(Stmt *E, raw_ostream &OS) override {
4226 const auto *DR = dyn_cast<DeclRefExpr>(E);
4227 if (DR && DR->getQualifier()) {
4228 // If this is a qualified name, expand the template arguments in nested
4229 // qualifiers.
4230 DR->getQualifier()->print(OS, Policy, true);
4231 // Then print the decl itself.
4232 const ValueDecl *VD = DR->getDecl();
4233 OS << VD->getName();
4234 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
4235 // This is a template variable, print the expanded template arguments.
4237 OS, IV->getTemplateArgs().asArray(), Policy,
4238 IV->getSpecializedTemplate()->getTemplateParameters());
4239 }
4240 return true;
4241 }
4242 return false;
4243 }
4244
4245private:
4246 const PrintingPolicy Policy;
4247};
4248
4249} // end anonymous namespace
4250
4251std::pair<Expr *, std::string>
4253 Cond = lookThroughRangesV3Condition(PP, Cond);
4254
4255 // Separate out all of the terms in a conjunction.
4257 collectConjunctionTerms(Cond, Terms);
4258
4259 // Determine which term failed.
4260 Expr *FailedCond = nullptr;
4261 for (Expr *Term : Terms) {
4262 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
4263
4264 // Literals are uninteresting.
4265 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
4266 isa<IntegerLiteral>(TermAsWritten))
4267 continue;
4268
4269 // The initialization of the parameter from the argument is
4270 // a constant-evaluated context.
4273
4274 bool Succeeded;
4275 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
4276 !Succeeded) {
4277 FailedCond = TermAsWritten;
4278 break;
4279 }
4280 }
4281 if (!FailedCond)
4282 FailedCond = Cond->IgnoreParenImpCasts();
4283
4284 std::string Description;
4285 {
4286 llvm::raw_string_ostream Out(Description);
4288 Policy.PrintCanonicalTypes = true;
4289 FailedBooleanConditionPrinterHelper Helper(Policy);
4290 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
4291 }
4292 return { FailedCond, Description };
4293}
4294
4296 SourceLocation TemplateLoc,
4297 TemplateArgumentListInfo &TemplateArgs) {
4299 = Name.getUnderlying().getAsDependentTemplateName();
4300 if (DTN && DTN->isIdentifier())
4301 // When building a template-id where the template-name is dependent,
4302 // assume the template is a type template. Either our assumption is
4303 // correct, or the code is ill-formed and will be diagnosed when the
4304 // dependent name is substituted.
4307 TemplateArgs.arguments());
4308
4309 if (Name.getAsAssumedTemplateName() &&
4310 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
4311 return QualType();
4312
4313 TemplateDecl *Template = Name.getAsTemplateDecl();
4314 if (!Template || isa<FunctionTemplateDecl>(Template) ||
4315 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
4316 // We might have a substituted template template parameter pack. If so,
4317 // build a template specialization type for it.
4318 if (Name.getAsSubstTemplateTemplateParmPack())
4320 TemplateArgs.arguments());
4321
4322 Diag(TemplateLoc, diag::err_template_id_not_a_type)
4323 << Name;
4325 return QualType();
4326 }
4327
4328 // Check that the template argument list is well-formed for this
4329 // template.
4330 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4331 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
4332 SugaredConverted, CanonicalConverted,
4333 /*UpdateArgsWithConversions=*/true))
4334 return QualType();
4335
4336 QualType CanonType;
4337
4339 dyn_cast<TypeAliasTemplateDecl>(Template)) {
4340
4341 // Find the canonical type for this type alias template specialization.
4342 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
4343 if (Pattern->isInvalidDecl())
4344 return QualType();
4345
4346 // Only substitute for the innermost template argument list.
4347 MultiLevelTemplateArgumentList TemplateArgLists;
4348 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
4349 /*Final=*/false);
4350 TemplateArgLists.addOuterRetainedLevels(
4351 AliasTemplate->getTemplateParameters()->getDepth());
4352
4354 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
4355 if (Inst.isInvalid())
4356 return QualType();
4357
4358 std::optional<ContextRAII> SavedContext;
4359 if (!AliasTemplate->getDeclContext()->isFileContext())
4360 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
4361
4362 CanonType =
4363 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
4364 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
4365 if (CanonType.isNull()) {
4366 // If this was enable_if and we failed to find the nested type
4367 // within enable_if in a SFINAE context, dig out the specific
4368 // enable_if condition that failed and present that instead.
4370 if (auto DeductionInfo = isSFINAEContext()) {
4371 if (*DeductionInfo &&
4372 (*DeductionInfo)->hasSFINAEDiagnostic() &&
4373 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4374 diag::err_typename_nested_not_found_enable_if &&
4375 TemplateArgs[0].getArgument().getKind()
4377 Expr *FailedCond;
4378 std::string FailedDescription;
4379 std::tie(FailedCond, FailedDescription) =
4380 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
4381
4382 // Remove the old SFINAE diagnostic.
4383 PartialDiagnosticAt OldDiag =
4385 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
4386
4387 // Add a new SFINAE diagnostic specifying which condition
4388 // failed.
4389 (*DeductionInfo)->addSFINAEDiagnostic(
4390 OldDiag.first,
4391 PDiag(diag::err_typename_nested_not_found_requirement)
4392 << FailedDescription
4393 << FailedCond->getSourceRange());
4394 }
4395 }
4396 }
4397
4398 return QualType();
4399 }
4400 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
4401 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
4402 TemplateLoc, TemplateArgs);
4403 } else if (Name.isDependent() ||
4405 TemplateArgs, CanonicalConverted)) {
4406 // This class template specialization is a dependent
4407 // type. Therefore, its canonical type is another class template
4408 // specialization type that contains all of the converted
4409 // arguments in canonical form. This ensures that, e.g., A<T> and
4410 // A<T, T> have identical types when A is declared as:
4411 //
4412 // template<typename T, typename U = T> struct A;
4414 Name, CanonicalConverted);
4415
4416 // This might work out to be a current instantiation, in which
4417 // case the canonical type needs to be the InjectedClassNameType.
4418 //
4419 // TODO: in theory this could be a simple hashtable lookup; most
4420 // changes to CurContext don't change the set of current
4421 // instantiations.
4422 if (isa<ClassTemplateDecl>(Template)) {
4423 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4424 // If we get out to a namespace, we're done.
4425 if (Ctx->isFileContext()) break;
4426
4427 // If this isn't a record, keep looking.
4428 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4429 if (!Record) continue;
4430
4431 // Look for one of the two cases with InjectedClassNameTypes
4432 // and check whether it's the same template.
4433 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4434 !Record->getDescribedClassTemplate())
4435 continue;
4436
4437 // Fetch the injected class name type and check whether its
4438 // injected type is equal to the type we just built.
4440 QualType Injected = cast<InjectedClassNameType>(ICNT)
4441 ->getInjectedSpecializationType();
4442
4443 if (CanonType != Injected->getCanonicalTypeInternal())
4444 continue;
4445
4446 // If so, the canonical type of this TST is the injected
4447 // class name type of the record we just found.
4448 assert(ICNT.isCanonical());
4449 CanonType = ICNT;
4450 break;
4451 }
4452 }
4453 } else if (ClassTemplateDecl *ClassTemplate =
4454 dyn_cast<ClassTemplateDecl>(Template)) {
4455 // Find the class template specialization declaration that
4456 // corresponds to these arguments.
4457 void *InsertPos = nullptr;
4459 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4460 if (!Decl) {
4461 // This is the first time we have referenced this class template
4462 // specialization. Create the canonical declaration and add it to
4463 // the set of specializations.
4465 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4466 ClassTemplate->getDeclContext(),
4467 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4468 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4469 nullptr);
4470 ClassTemplate->AddSpecialization(Decl, InsertPos);
4471 if (ClassTemplate->isOutOfLine())
4472 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4473 }
4474
4475 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4476 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4477 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4478 if (!Inst.isInvalid()) {
4479 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4480 CanonicalConverted,
4481 /*Final=*/false);
4482 InstantiateAttrsForDecl(TemplateArgLists,
4483 ClassTemplate->getTemplatedDecl(), Decl);
4484 }
4485 }
4486
4487 // Diagnose uses of this specialization.
4488 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4489
4490 CanonType = Context.getTypeDeclType(Decl);
4491 assert(isa<RecordType>(CanonType) &&
4492 "type of non-dependent specialization is not a RecordType");
4493 } else {
4494 llvm_unreachable("Unhandled template kind");
4495 }
4496
4497 // Build the fully-sugared type for this class template
4498 // specialization, which refers back to the class template
4499 // specialization we created or found.
4500 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4501 CanonType);
4502}
4503
4505 TemplateNameKind &TNK,
4506 SourceLocation NameLoc,
4507 IdentifierInfo *&II) {
4508 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4509
4510 TemplateName Name = ParsedName.get();
4511 auto *ATN = Name.getAsAssumedTemplateName();
4512 assert(ATN && "not an assumed template name");
4513 II = ATN->getDeclName().getAsIdentifierInfo();
4514
4515 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4516 // Resolved to a type template name.
4517 ParsedName = TemplateTy::make(Name);
4518 TNK = TNK_Type_template;
4519 }
4520}
4521
4523 SourceLocation NameLoc,
4524 bool Diagnose) {
4525 // We assumed this undeclared identifier to be an (ADL-only) function
4526 // template name, but it was used in a context where a type was required.
4527 // Try to typo-correct it now.
4528 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4529 assert(ATN && "not an assumed template name");
4530
4531 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4532 struct CandidateCallback : CorrectionCandidateCallback {
4533 bool ValidateCandidate(const TypoCorrection &TC) override {
4534 return TC.getCorrectionDecl() &&
4536 }
4537 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4538 return std::make_unique<CandidateCallback>(*this);
4539 }
4540 } FilterCCC;
4541
4542 TypoCorrection Corrected =
4543 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4544 FilterCCC, CTK_ErrorRecovery);
4545 if (Corrected && Corrected.getFoundDecl()) {
4546 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4547 << ATN->getDeclName());
4548 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4549 return false;
4550 }
4551
4552 if (Diagnose)
4553 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4554 return true;
4555}
4556
4558 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4559 TemplateTy TemplateD, IdentifierInfo *TemplateII,
4560 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4561 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4562 bool IsCtorOrDtorName, bool IsClassName,
4563 ImplicitTypenameContext AllowImplicitTypename) {
4564 if (SS.isInvalid())
4565 return true;
4566
4567 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4568 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4569
4570 // C++ [temp.res]p3:
4571 // A qualified-id that refers to a type and in which the
4572 // nested-name-specifier depends on a template-parameter (14.6.2)
4573 // shall be prefixed by the keyword typename to indicate that the
4574 // qualified-id denotes a type, forming an
4575 // elaborated-type-specifier (7.1.5.3).
4576 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4577 // C++2a relaxes some of those restrictions in [temp.res]p5.
4578 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4580 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4581 else
4582 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4583 << SS.getScopeRep() << TemplateII->getName()
4584 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4585 } else
4586 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4587 << SS.getScopeRep() << TemplateII->getName();
4588
4589 // FIXME: This is not quite correct recovery as we don't transform SS
4590 // into the corresponding dependent form (and we don't diagnose missing
4591 // 'template' keywords within SS as a result).
4592 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4593 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4594 TemplateArgsIn, RAngleLoc);
4595 }
4596
4597 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4598 // it's not actually allowed to be used as a type in most cases. Because
4599 // we annotate it before we know whether it's valid, we have to check for
4600 // this case here.
4601 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4602 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4603 Diag(TemplateIILoc,
4604 TemplateKWLoc.isInvalid()
4605 ? diag::err_out_of_line_qualified_id_type_names_constructor
4606 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4607 << TemplateII << 0 /*injected-class-name used as template name*/
4608 << 1 /*if any keyword was present, it was 'template'*/;
4609 }
4610 }
4611
4612 TemplateName Template = TemplateD.get();
4613 if (Template.getAsAssumedTemplateName() &&
4614 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4615 return true;
4616
4617 // Translate the parser's template argument list in our AST format.
4618 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4619 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4620
4621 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4622 assert(SS.getScopeRep() == DTN->getQualifier());
4624 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4625 TemplateArgs.arguments());
4626 // Build type-source information.
4627 TypeLocBuilder TLB;
4632 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4633 SpecTL.setTemplateNameLoc(TemplateIILoc);
4634 SpecTL.setLAngleLoc(LAngleLoc);
4635 SpecTL.setRAngleLoc(RAngleLoc);
4636 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4637 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4638 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4639 }
4640
4641 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4642 if (SpecTy.isNull())
4643 return true;
4644
4645 // Build type-source information.
4646 TypeLocBuilder TLB;
4649 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4650 SpecTL.setTemplateNameLoc(TemplateIILoc);
4651 SpecTL.setLAngleLoc(LAngleLoc);
4652 SpecTL.setRAngleLoc(RAngleLoc);
4653 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4654 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4655
4656 // Create an elaborated-type-specifier containing the nested-name-specifier.
4657 QualType ElTy =
4659 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4660 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4662 if (!ElabTL.isEmpty())
4664 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4665}
4666
4668 TypeSpecifierType TagSpec,
4669 SourceLocation TagLoc,
4670 CXXScopeSpec &SS,
4671 SourceLocation TemplateKWLoc,
4672 TemplateTy TemplateD,
4673 SourceLocation TemplateLoc,
4674 SourceLocation LAngleLoc,
4675 ASTTemplateArgsPtr TemplateArgsIn,
4676 SourceLocation RAngleLoc) {
4677 if (SS.isInvalid())
4678 return TypeResult(true);
4679
4680 TemplateName Template = TemplateD.get();
4681
4682 // Translate the parser's template argument list in our AST format.
4683 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4684 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4685
4686 // Determine the tag kind
4688 ElaboratedTypeKeyword Keyword
4690
4691 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4692 assert(SS.getScopeRep() == DTN->getQualifier());
4694 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4695 TemplateArgs.arguments());
4696
4697 // Build type-source information.
4698 TypeLocBuilder TLB;
4701 SpecTL.setElaboratedKeywordLoc(TagLoc);
4703 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4704 SpecTL.setTemplateNameLoc(TemplateLoc);
4705 SpecTL.setLAngleLoc(LAngleLoc);
4706 SpecTL.setRAngleLoc(RAngleLoc);
4707 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4708 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4709 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4710 }
4711
4712 if (TypeAliasTemplateDecl *TAT =
4713 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4714 // C++0x [dcl.type.elab]p2:
4715 // If the identifier resolves to a typedef-name or the simple-template-id
4716 // resolves to an alias template specialization, the
4717 // elaborated-type-specifier is ill-formed.
4718 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4719 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4720 Diag(TAT->getLocation(), diag::note_declared_at);
4721 }
4722
4723 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4724 if (Result.isNull())
4725 return TypeResult(true);
4726
4727 // Check the tag kind
4728 if (const RecordType *RT = Result->getAs<RecordType>()) {
4729 RecordDecl *D = RT->getDecl();
4730
4732 assert(Id && "templated class must have an identifier");
4733
4734 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4735 TagLoc, Id)) {
4736 Diag(TagLoc, diag::err_use_with_wrong_tag)
4737 << Result
4739 Diag(D->getLocation(), diag::note_previous_use);
4740 }
4741 }
4742
4743 // Provide source-location information for the template specialization.
4744 TypeLocBuilder TLB;
4747 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4748 SpecTL.setTemplateNameLoc(TemplateLoc);
4749 SpecTL.setLAngleLoc(LAngleLoc);
4750 SpecTL.setRAngleLoc(RAngleLoc);
4751 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4752 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4753
4754 // Construct an elaborated type containing the nested-name-specifier (if any)
4755 // and tag keyword.
4758 ElabTL.setElaboratedKeywordLoc(TagLoc);
4761}
4762
4763static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4764 NamedDecl *PrevDecl,
4765 SourceLocation Loc,
4767
4769
4771 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4772 switch (Arg.getKind()) {
4780 return false;
4781
4783 QualType Type = Arg.getAsType();
4784 const TemplateTypeParmType *TPT =
4786 return TPT && !Type.hasQualifiers() &&
4787 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4788 }
4789
4791 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4792 if (!DRE || !DRE->getDecl())
4793 return false;
4794 const NonTypeTemplateParmDecl *NTTP =
4795 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4796 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4797 }
4798
4800 const TemplateTemplateParmDecl *TTP =
4801 dyn_cast_or_null<TemplateTemplateParmDecl>(
4803 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4804 }
4805 llvm_unreachable("unexpected kind of template argument");
4806}
4807
4810 if (Params->size() != Args.size())
4811 return false;
4812
4813 unsigned Depth = Params->getDepth();
4814
4815 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4816 TemplateArgument Arg = Args[I];
4817
4818 // If the parameter is a pack expansion, the argument must be a pack
4819 // whose only element is a pack expansion.
4820 if (Params->getParam(I)->isParameterPack()) {
4821 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4822 !Arg.pack_begin()->isPackExpansion())
4823 return false;
4824 Arg = Arg.pack_begin()->getPackExpansionPattern();
4825 }
4826
4827 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4828 return false;
4829 }
4830
4831 return true;
4832}
4833
4834template<typename PartialSpecDecl>
4835static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4836 if (Partial->getDeclContext()->isDependentContext())
4837 return;
4838
4839 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4840 // for non-substitution-failure issues?
4841 TemplateDeductionInfo Info(Partial->getLocation());
4842 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4843 return;
4844
4845 auto *Template = Partial->getSpecializedTemplate();
4846 S.Diag(Partial->getLocation(),
4847 diag::ext_partial_spec_not_more_specialized_than_primary)
4848 << isa<VarTemplateDecl>(Template);
4849
4850 if (Info.hasSFINAEDiagnostic()) {
4854 SmallString<128> SFINAEArgString;
4855 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4856 S.Diag(Diag.first,
4857 diag::note_partial_spec_not_more_specialized_than_primary)
4858 << SFINAEArgString;
4859 }
4860
4861 S.NoteTemplateLocation(*Template);
4862 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4863 Template->getAssociatedConstraints(TemplateAC);
4864 Partial->getAssociatedConstraints(PartialAC);
4865 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4866 TemplateAC);
4867}
4868
4869static void
4871 const llvm::SmallBitVector &DeducibleParams) {
4872 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4873 if (!DeducibleParams[I]) {
4874 NamedDecl *Param = TemplateParams->getParam(I);
4875 if (Param->getDeclName())
4876 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4877 << Param->getDeclName();
4878 else
4879 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4880 << "(anonymous)";
4881 }
4882 }
4883}
4884
4885
4886template<typename PartialSpecDecl>
4888 PartialSpecDecl *Partial) {
4889 // C++1z [temp.class.spec]p8: (DR1495)
4890 // - The specialization shall be more specialized than the primary
4891 // template (14.5.5.2).
4893
4894 // C++ [temp.class.spec]p8: (DR1315)
4895 // - Each template-parameter shall appear at least once in the
4896 // template-id outside a non-deduced context.
4897 // C++1z [temp.class.spec.match]p3 (P0127R2)
4898 // If the template arguments of a partial specialization cannot be
4899 // deduced because of the structure of its template-parameter-list
4900 // and the template-id, the program is ill-formed.
4901 auto *TemplateParams = Partial->getTemplateParameters();
4902 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4903 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4904 TemplateParams->getDepth(), DeducibleParams);
4905
4906 if (!DeducibleParams.all()) {
4907 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4908 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4909 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4910 << (NumNonDeducible > 1)
4911 << SourceRange(Partial->getLocation(),
4912 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4913 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4914 }
4915}
4916
4919 checkTemplatePartialSpecialization(*this, Partial);
4920}
4921
4924 checkTemplatePartialSpecialization(*this, Partial);
4925}
4926
4928 // C++1z [temp.param]p11:
4929 // A template parameter of a deduction guide template that does not have a
4930 // default-argument shall be deducible from the parameter-type-list of the
4931 // deduction guide template.
4932 auto *TemplateParams = TD->getTemplateParameters();
4933 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4934 MarkDeducedTemplateParameters(TD, DeducibleParams);
4935 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4936 // A parameter pack is deducible (to an empty pack).
4937 auto *Param = TemplateParams->getParam(I);
4938 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4939 DeducibleParams[I] = true;
4940 }
4941
4942 if (!DeducibleParams.all()) {
4943 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4944 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4945 << (NumNonDeducible > 1);
4946 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4947 }
4948}
4949
4952 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4954 // D must be variable template id.
4956 "Variable template specialization is declared with a template id.");
4957
4958 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4959 TemplateArgumentListInfo TemplateArgs =
4960 makeTemplateArgumentListInfo(*this, *TemplateId);
4961 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4962 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4963 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4964
4965 TemplateName Name = TemplateId->Template.get();
4966
4967 // The template-id must name a variable template.
4969 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4970 if (!VarTemplate) {
4971 NamedDecl *FnTemplate;
4972 if (auto *OTS = Name.getAsOverloadedTemplate())
4973 FnTemplate = *OTS->begin();
4974 else
4975 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4976 if (FnTemplate)
4977 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4978 << FnTemplate->getDeclName();
4979 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4981 }
4982
4983 // Check for unexpanded parameter packs in any of the template arguments.
4984 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4985 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4989 return true;
4990
4991 // Check that the template argument list is well-formed for this
4992 // template.
4993 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4994 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4995 false, SugaredConverted, CanonicalConverted,
4996 /*UpdateArgsWithConversions=*/true))
4997 return true;
4998
4999 // Find the variable template (partial) specialization declaration that
5000 // corresponds to these arguments.
5003 TemplateArgs.size(),
5004 CanonicalConverted))
5005 return true;
5006
5007 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
5008 // also do them during instantiation.
5009 if (!Name.isDependent() &&
5011 TemplateArgs, CanonicalConverted)) {
5012 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5013 << VarTemplate->getDeclName();
5015 }
5016
5017 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
5018 CanonicalConverted) &&
5019 (!Context.getLangOpts().CPlusPlus20 ||
5020 !TemplateParams->hasAssociatedConstraints())) {
5021 // C++ [temp.class.spec]p9b3:
5022 //
5023 // -- The argument list of the specialization shall not be identical
5024 // to the implicit argument list of the primary template.
5025 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5026 << /*variable template*/ 1
5027 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
5028 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5029 // FIXME: Recover from this by treating the declaration as a redeclaration
5030 // of the primary template.
5031 return true;
5032 }
5033 }
5034
5035 void *InsertPos = nullptr;
5036 VarTemplateSpecializationDecl *PrevDecl = nullptr;
5037
5039 PrevDecl = VarTemplate->findPartialSpecialization(
5040 CanonicalConverted, TemplateParams, InsertPos);
5041 else
5042 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
5043
5045
5046 // Check whether we can declare a variable template specialization in
5047 // the current scope.
5048 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
5049 TemplateNameLoc,
5051 return true;
5052
5053 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
5054 // Since the only prior variable template specialization with these
5055 // arguments was referenced but not declared, reuse that
5056 // declaration node as our own, updating its source location and
5057 // the list of outer template parameters to reflect our new declaration.
5058 Specialization = PrevDecl;
5059 Specialization->setLocation(TemplateNameLoc);
5060 PrevDecl = nullptr;
5061 } else if (IsPartialSpecialization) {
5062 // Create a new class template partial specialization declaration node.
5064 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
5067 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
5068 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
5069 CanonicalConverted, TemplateArgs);
5070
5071 if (!PrevPartial)
5072 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
5073 Specialization = Partial;
5074
5075 // If we are providing an explicit specialization of a member variable
5076 // template specialization, make a note of that.
5077 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5078 PrevPartial->setMemberSpecialization();
5079
5081 } else {
5082 // Create a new class template specialization declaration node for
5083 // this explicit specialization or friend declaration.
5085 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
5086 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
5087 Specialization->setTemplateArgsInfo(TemplateArgs);
5088
5089 if (!PrevDecl)
5090 VarTemplate->AddSpecialization(Specialization, InsertPos);
5091 }
5092
5093 // C++ [temp.expl.spec]p6:
5094 // If a template, a member template or the member of a class template is
5095 // explicitly specialized then that specialization shall be declared
5096 // before the first use of that specialization that would cause an implicit
5097 // instantiation to take place, in every translation unit in which such a
5098 // use occurs; no diagnostic is required.
5099 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5100 bool Okay = false;
5101 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5102 // Is there any previous explicit specialization declaration?
5104 Okay = true;
5105 break;
5106 }
5107 }
5108
5109 if (!Okay) {
5110 SourceRange Range(TemplateNameLoc, RAngleLoc);
5111 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5112 << Name << Range;
5113
5114 Diag(PrevDecl->getPointOfInstantiation(),
5115 diag::note_instantiation_required_here)
5116 << (PrevDecl->getTemplateSpecializationKind() !=
5118 return true;
5119 }
5120 }
5121
5122 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5123 Specialization->setLexicalDeclContext(CurContext);
5124
5125 // Add the specialization into its lexical context, so that it can
5126 // be seen when iterating through the list of declarations in that
5127 // context. However, specializations are not found by name lookup.
5129
5130 // Note that this is an explicit specialization.
5131 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5132
5133 Previous.clear();
5134 if (PrevDecl)
5135 Previous.addDecl(PrevDecl);
5136 else if (Specialization->isStaticDataMember() &&
5137 Specialization->isOutOfLine())
5138 Specialization->setAccess(VarTemplate->getAccess());
5139
5140 return Specialization;
5141}
5142
5143namespace {
5144/// A partial specialization whose template arguments have matched
5145/// a given template-id.
5146struct PartialSpecMatchResult {
5149};
5150} // end anonymous namespace
5151
5154 SourceLocation TemplateNameLoc,
5155 const TemplateArgumentListInfo &TemplateArgs) {
5156 assert(Template && "A variable template id without template?");
5157
5158 // Check that the template argument list is well-formed for this template.
5159 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5161 Template, TemplateNameLoc,
5162 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
5163 SugaredConverted, CanonicalConverted,
5164 /*UpdateArgsWithConversions=*/true))
5165 return true;
5166
5167 // Produce a placeholder value if the specialization is dependent.
5168 if (Template->getDeclContext()->isDependentContext() ||
5170 TemplateArgs, CanonicalConverted))
5171 return DeclResult();
5172
5173 // Find the variable template specialization declaration that
5174 // corresponds to these arguments.
5175 void *InsertPos = nullptr;
5177 Template->findSpecialization(CanonicalConverted, InsertPos)) {
5178 checkSpecializationReachability(TemplateNameLoc, Spec);
5179 // If we already have a variable template specialization, return it.
5180 return Spec;
5181 }
5182
5183 // This is the first time we have referenced this variable template
5184 // specialization. Create the canonical declaration and add it to
5185 // the set of specializations, based on the closest partial specialization
5186 // that it represents. That is,
5187 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
5188 const TemplateArgumentList *PartialSpecArgs = nullptr;
5189 bool AmbiguousPartialSpec = false;
5190 typedef PartialSpecMatchResult MatchResult;
5192 SourceLocation PointOfInstantiation = TemplateNameLoc;
5193 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
5194 /*ForTakingAddress=*/false);
5195
5196 // 1. Attempt to find the closest partial specialization that this
5197 // specializes, if any.
5198 // TODO: Unify with InstantiateClassTemplateSpecialization()?
5199 // Perhaps better after unification of DeduceTemplateArguments() and
5200 // getMoreSpecializedPartialSpecialization().
5202 Template->getPartialSpecializations(PartialSpecs);
5203
5204 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
5205 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
5206 TemplateDeductionInfo Info(FailedCandidates.getLocation());
5207
5209 DeduceTemplateArguments(Partial, CanonicalConverted, Info);
5211 // Store the failed-deduction information for use in diagnostics, later.
5212 // TODO: Actually use the failed-deduction info?
5213 FailedCandidates.addCandidate().set(
5214 DeclAccessPair::make(Template, AS_public), Partial,
5216 (void)Result;
5217 } else {
5218 Matched.push_back(PartialSpecMatchResult());
5219 Matched.back().Partial = Partial;
5220 Matched.back().Args = Info.takeCanonical();
5221 }
5222 }
5223
5224 if (Matched.size() >= 1) {
5225 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
5226 if (Matched.size() == 1) {
5227 // -- If exactly one matching specialization is found, the
5228 // instantiation is generated from that specialization.
5229 // We don't need to do anything for this.
5230 } else {
5231 // -- If more than one matching specialization is found, the
5232 // partial order rules (14.5.4.2) are used to determine
5233 // whether one of the specializations is more specialized
5234 // than the others. If none of the specializations is more
5235 // specialized than all of the other matching
5236 // specializations, then the use of the variable template is
5237 // ambiguous and the program is ill-formed.
5239 PEnd = Matched.end();
5240 P != PEnd; ++P) {
5241 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
5242 PointOfInstantiation) ==
5243 P->Partial)
5244 Best = P;
5245 }
5246
5247 // Determine if the best partial specialization is more specialized than
5248 // the others.
5249 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
5250 PEnd = Matched.end();
5251 P != PEnd; ++P) {
5253 P->Partial, Best->Partial,
5254 PointOfInstantiation) != Best->Partial) {
5255 AmbiguousPartialSpec = true;
5256 break;
5257 }
5258 }
5259 }
5260
5261 // Instantiate using the best variable template partial specialization.
5262 InstantiationPattern = Best->Partial;
5263 PartialSpecArgs = Best->Args;
5264 } else {
5265 // -- If no match is found, the instantiation is generated
5266 // from the primary template.
5267 // InstantiationPattern = Template->getTemplatedDecl();
5268 }
5269
5270 // 2. Create the canonical declaration.
5271 // Note that we do not instantiate a definition until we see an odr-use
5272 // in DoMarkVarDeclReferenced().
5273 // FIXME: LateAttrs et al.?
5275 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
5276 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
5277 if (!Decl)
5278 return true;
5279
5280 if (AmbiguousPartialSpec) {
5281 // Partial ordering did not produce a clear winner. Complain.
5283 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
5284 << Decl;
5285
5286 // Print the matching partial specializations.
5287 for (MatchResult P : Matched)
5288 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
5289 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
5290 *P.Args);
5291 return true;
5292 }
5293
5295 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
5296 Decl->setInstantiationOf(D, PartialSpecArgs);
5297
5298 checkSpecializationReachability(TemplateNameLoc, Decl);
5299
5300 assert(Decl && "No variable template specialization?");
5301 return Decl;
5302}
5303
5305 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
5306 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
5307 const TemplateArgumentListInfo *TemplateArgs) {
5308
5309 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
5310 *TemplateArgs);
5311 if (Decl.isInvalid())
5312 return ExprError();
5313
5314 if (!Decl.get())
5315 return ExprResult();
5316
5317 VarDecl *Var = cast<VarDecl>(Decl.get());
5320 NameInfo.getLoc());
5321
5322 // Build an ordinary singleton decl ref.
5323 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
5324}
5325
5327 SourceLocation Loc) {
5328 Diag(Loc, diag::err_template_missing_args)
5329 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
5330 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
5331 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
5332 }
5333}
5334
5337 SourceLocation TemplateKWLoc,
5338 const DeclarationNameInfo &ConceptNameInfo,
5339 NamedDecl *FoundDecl,
5340 ConceptDecl *NamedConcept,
5341 const TemplateArgumentListInfo *TemplateArgs) {
5342 assert(NamedConcept && "A concept template id without a template?");
5343
5344 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5346 NamedConcept, ConceptNameInfo.getLoc(),
5347 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
5348 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
5349 /*UpdateArgsWithConversions=*/false))
5350 return ExprError();
5351
5353 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
5354 CanonicalConverted);
5355 ConstraintSatisfaction Satisfaction;
5356 bool AreArgsDependent =
5358 *TemplateArgs, CanonicalConverted);
5359 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5360 /*Final=*/false);
5362
5365
5366 if (!AreArgsDependent &&
5368 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5369 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5370 TemplateArgs->getRAngleLoc()),
5371 Satisfaction))
5372 return ExprError();
5373 auto *CL = ConceptReference::Create(
5374 Context,
5376 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5379 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5380}
5381
5383 SourceLocation TemplateKWLoc,
5384 LookupResult &R,
5385 bool RequiresADL,
5386 const TemplateArgumentListInfo *TemplateArgs) {
5387 // FIXME: Can we do any checking at this point? I guess we could check the
5388 // template arguments that we have against the template name, if the template
5389 // name refers to a single template. That's not a terribly common case,
5390 // though.
5391 // foo<int> could identify a single function unambiguously
5392 // This approach does NOT work, since f<int>(1);
5393 // gets resolved prior to resorting to overload resolution
5394 // i.e., template<class T> void f(double);
5395 // vs template<class T, class U> void f(U);
5396
5397 // These should be filtered out by our callers.
5398 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5399
5400 // Non-function templates require a template argument list.
5401 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5402 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5404 return ExprError();
5405 }
5406 }
5407 bool KnownDependent = false;
5408 // In C++1y, check variable template ids.
5409 if (R.getAsSingle<VarTemplateDecl>()) {
5412 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5413 if (Res.isInvalid() || Res.isUsable())
5414 return Res;
5415 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5416 KnownDependent = true;
5417 }
5418
5419 if (R.getAsSingle<ConceptDecl>()) {
5420 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5422 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5423 }
5424
5425 // We don't want lookup warnings at this point.
5427
5430 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5431 R.begin(), R.end(), KnownDependent);
5432
5433 return ULE;
5434}
5435
5436// We actually only call this from template instantiation.
5439 SourceLocation TemplateKWLoc,
5440 const DeclarationNameInfo &NameInfo,
5441 const TemplateArgumentListInfo *TemplateArgs) {
5442
5443 assert(TemplateArgs || TemplateKWLoc.isValid());
5444 DeclContext *DC;
5445 if (!(DC = computeDeclContext(SS, false)) ||
5446 DC->isDependentContext() ||
5448 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5449
5450 bool MemberOfUnknownSpecialization;
5451 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5452 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5453 /*Entering*/false, MemberOfUnknownSpecialization,
5454 TemplateKWLoc))
5455 return ExprError();
5456
5457 if (R.isAmbiguous())
5458 return ExprError();
5459
5460 if (R.empty()) {
5461 Diag(NameInfo.getLoc(), diag::err_no_member)
5462 << NameInfo.getName() << DC << SS.getRange();
5463 return ExprError();
5464 }
5465
5466 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5467 bool isTypeAliasTemplateDecl) {
5468 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5469 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5470 << isTypeAliasTemplateDecl;
5471 Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0;
5472 return ExprError();
5473 };
5474
5476 return DiagnoseTypeTemplateDecl(Temp, false);
5477
5479 return DiagnoseTypeTemplateDecl(Temp, true);
5480
5481 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5482}
5483
5484/// Form a template name from a name that is syntactically required to name a
5485/// template, either due to use of the 'template' keyword or because a name in
5486/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5487///
5488/// This action forms a template name given the name of the template and its
5489/// optional scope specifier. This is used when the 'template' keyword is used
5490/// or when the parsing context unambiguously treats a following '<' as
5491/// introducing a template argument list. Note that this may produce a
5492/// non-dependent template name if we can perform the lookup now and identify
5493/// the named template.
5494///
5495/// For example, given "x.MetaFun::template apply", the scope specifier
5496/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5497/// of the "template" keyword, and "apply" is the \p Name.
5499 CXXScopeSpec &SS,
5500 SourceLocation TemplateKWLoc,
5501 const UnqualifiedId &Name,
5502 ParsedType ObjectType,
5503 bool EnteringContext,
5505 bool AllowInjectedClassName) {
5506 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5507 Diag(TemplateKWLoc,
5509 diag::warn_cxx98_compat_template_outside_of_template :
5510 diag::ext_template_outside_of_template)
5511 << FixItHint::CreateRemoval(TemplateKWLoc);
5512
5513 if (SS.isInvalid())
5514 return TNK_Non_template;
5515
5516 // Figure out where isTemplateName is going to look.
5517 DeclContext *LookupCtx = nullptr;
5518 if (SS.isNotEmpty())
5519 LookupCtx = computeDeclContext(SS, EnteringContext);
5520 else if (ObjectType)
5521 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5522
5523 // C++0x [temp.names]p5:
5524 // If a name prefixed by the keyword template is not the name of
5525 // a template, the program is ill-formed. [Note: the keyword
5526 // template may not be applied to non-template members of class
5527 // templates. -end note ] [ Note: as is the case with the
5528 // typename prefix, the template prefix is allowed in cases
5529 // where it is not strictly necessary; i.e., when the
5530 // nested-name-specifier or the expression on the left of the ->
5531 // or . is not dependent on a template-parameter, or the use
5532 // does not appear in the scope of a template. -end note]
5533 //
5534 // Note: C++03 was more strict here, because it banned the use of
5535 // the "template" keyword prior to a template-name that was not a
5536 // dependent name. C++ DR468 relaxed this requirement (the
5537 // "template" keyword is now permitted). We follow the C++0x
5538 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5539 bool MemberOfUnknownSpecialization;
5540 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5541 ObjectType, EnteringContext, Result,
5542 MemberOfUnknownSpecialization);
5543 if (TNK != TNK_Non_template) {
5544 // We resolved this to a (non-dependent) template name. Return it.
5545 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5546 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5547 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5548 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5549 // C++14 [class.qual]p2:
5550 // In a lookup in which function names are not ignored and the
5551 // nested-name-specifier nominates a class C, if the name specified
5552 // [...] is the injected-class-name of C, [...] the name is instead
5553 // considered to name the constructor
5554 //
5555 // We don't get here if naming the constructor would be valid, so we
5556 // just reject immediately and recover by treating the
5557 // injected-class-name as naming the template.
5558 Diag(Name.getBeginLoc(),
5559 diag::ext_out_of_line_qualified_id_type_names_constructor)
5560 << Name.Identifier
5561 << 0 /*injected-class-name used as template name*/
5562 << TemplateKWLoc.isValid();
5563 }
5564 return TNK;
5565 }
5566
5567 if (!MemberOfUnknownSpecialization) {
5568 // Didn't find a template name, and the lookup wasn't dependent.
5569 // Do the lookup again to determine if this is a "nothing found" case or
5570 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5571 // need to do this.
5573 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5575 bool MOUS;
5576 // Tell LookupTemplateName that we require a template so that it diagnoses
5577 // cases where it finds a non-template.
5578 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5579 ? RequiredTemplateKind(TemplateKWLoc)
5581 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5582 RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5583 !R.isAmbiguous()) {
5584 if (LookupCtx)
5585 Diag(Name.getBeginLoc(), diag::err_no_member)
5586 << DNI.getName() << LookupCtx << SS.getRange();
5587 else
5588 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5589 << DNI.getName() << SS.getRange();
5590 }
5591 return TNK_Non_template;
5592 }
5593
5594 NestedNameSpecifier *Qualifier = SS.getScopeRep();
5595
5596 switch (Name.getKind()) {
5599 Context.getDependentTemplateName(Qualifier, Name.Identifier));
5601
5604 Qualifier, Name.OperatorFunctionId.Operator));
5605 return TNK_Function_template;
5606
5608 // This is a kind of template name, but can never occur in a dependent
5609 // scope (literal operators can only be declared at namespace scope).
5610 break;
5611
5612 default:
5613 break;
5614 }
5615
5616 // This name cannot possibly name a dependent template. Diagnose this now
5617 // rather than building a dependent template name that can never be valid.
5618 Diag(Name.getBeginLoc(),
5619 diag::err_template_kw_refers_to_dependent_non_template)
5620 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5621 << TemplateKWLoc.isValid() << TemplateKWLoc;
5622 return TNK_Non_template;
5623}
5624
5627 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5628 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5629 const TemplateArgument &Arg = AL.getArgument();
5630 QualType ArgType;
5631 TypeSourceInfo *TSI = nullptr;
5632
5633 // Check template type parameter.
5634 switch(Arg.getKind()) {
5636 // C++ [temp.arg.type]p1:
5637 // A template-argument for a template-parameter which is a
5638 // type shall be a type-id.
5639 ArgType = Arg.getAsType();
5640 TSI = AL.getTypeSourceInfo();
5641 break;
5644 // We have a template type parameter but the template argument
5645 // is a template without any arguments.
5646 SourceRange SR = AL.getSourceRange();
5649 return true;
5650 }
5652 // We have a template type parameter but the template argument is an
5653 // expression; see if maybe it is missing the "typename" keyword.
5654 CXXScopeSpec SS;
5655 DeclarationNameInfo NameInfo;
5656
5657 if (DependentScopeDeclRefExpr *ArgExpr =
5658 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5659 SS.Adopt(ArgExpr->getQualifierLoc());
5660 NameInfo = ArgExpr->getNameInfo();
5661 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5662 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5663 if (ArgExpr->isImplicitAccess()) {
5664 SS.Adopt(ArgExpr->getQualifierLoc());
5665 NameInfo = ArgExpr->getMemberNameInfo();
5666 }
5667 }
5668
5669 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5670 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5671 LookupParsedName(Result, CurScope, &SS);
5672
5673 if (Result.getAsSingle<TypeDecl>() ||
5674 Result.getResultKind() ==
5676 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5677 // Suggest that the user add 'typename' before the NNS.
5679 Diag(Loc, getLangOpts().MSVCCompat
5680 ? diag::ext_ms_template_type_arg_missing_typename
5681 : diag::err_template_arg_must_be_type_suggest)
5682 << FixItHint::CreateInsertion(Loc, "typename ");
5684
5685 // Recover by synthesizing a type using the location information that we
5686 // already have.
5688 SS.getScopeRep(), II);
5689 TypeLocBuilder TLB;
5691 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5693 TL.setNameLoc(NameInfo.getLoc());
5694 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5695
5696 // Overwrite our input TemplateArgumentLoc so that we can recover
5697 // properly.
5700
5701 break;
5702 }
5703 }
5704 // fallthrough
5705 [[fallthrough]];
5706 }
5707 default: {
5708 // We allow instantiateing a template with template argument packs when
5709 // building deduction guides.
5710 if (Arg.getKind() == TemplateArgument::Pack &&
5711 CodeSynthesisContexts.back().Kind ==
5713 SugaredConverted.push_back(Arg);
5714 CanonicalConverted.push_back(Arg);
5715 return false;
5716 }
5717 // We have a template type parameter but the template argument
5718 // is not a type.
5719 SourceRange SR = AL.getSourceRange();
5720 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5722
5723 return true;
5724 }
5725 }
5726
5727 if (CheckTemplateArgument(TSI))
5728 return true;
5729
5730 // Objective-C ARC:
5731 // If an explicitly-specified template argument type is a lifetime type
5732 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5733 if (getLangOpts().ObjCAutoRefCount &&
5734 ArgType->isObjCLifetimeType() &&
5735 !ArgType.getObjCLifetime()) {
5736 Qualifiers Qs;
5738 ArgType = Context.getQualifiedType(ArgType, Qs);
5739 }
5740
5741 SugaredConverted.push_back(TemplateArgument(ArgType));
5742 CanonicalConverted.push_back(
5744 return false;
5745}
5746
5747/// Substitute template arguments into the default template argument for
5748/// the given template type parameter.
5749///
5750/// \param SemaRef the semantic analysis object for which we are performing
5751/// the substitution.
5752///
5753/// \param Template the template that we are synthesizing template arguments
5754/// for.
5755///
5756/// \param TemplateLoc the location of the template name that started the
5757/// template-id we are checking.
5758///
5759/// \param RAngleLoc the location of the right angle bracket ('>') that
5760/// terminates the template-id.
5761///
5762/// \param Param the template template parameter whose default we are
5763/// substituting into.
5764///
5765/// \param Converted the list of template arguments provided for template
5766/// parameters that precede \p Param in the template parameter list.
5767/// \returns the substituted template argument, or NULL if an error occurred.
5769 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5770 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5771 ArrayRef<TemplateArgument> SugaredConverted,
5772 ArrayRef<TemplateArgument> CanonicalConverted) {
5773 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5774
5775 // If the argument type is dependent, instantiate it now based
5776 // on the previously-computed template arguments.
5777 if (ArgType->getType()->isInstantiationDependentType()) {
5778 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5779 SugaredConverted,
5780 SourceRange(TemplateLoc, RAngleLoc));
5781 if (Inst.isInvalid())
5782 return nullptr;
5783
5784 // Only substitute for the innermost template argument list.
5785 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5786 /*Final=*/true);
5787 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5788 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5789
5790 bool ForLambdaCallOperator = false;
5791 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5792 ForLambdaCallOperator = Rec->isLambda();
5793 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5794 !ForLambdaCallOperator);
5795 ArgType =
5796 SemaRef.SubstType(ArgType, TemplateArgLists,
5797 Param->getDefaultArgumentLoc(), Param->getDeclName());
5798 }
5799
5800 return ArgType;
5801}
5802
5803/// Substitute template arguments into the default template argument for
5804/// the given non-type template parameter.
5805///
5806/// \param SemaRef the semantic analysis object for which we are performing
5807/// the substitution.
5808///
5809/// \param Template the template that we are synthesizing template arguments
5810/// for.
5811///
5812/// \param TemplateLoc the location of the template name that started the
5813/// template-id we are checking.
5814///
5815/// \param RAngleLoc the location of the right angle bracket ('>') that
5816/// terminates the template-id.
5817///
5818/// \param Param the non-type template parameter whose default we are
5819/// substituting into.
5820///
5821/// \param Converted the list of template arguments provided for template
5822/// parameters that precede \p Param in the template parameter list.
5823///
5824/// \returns the substituted template argument, or NULL if an error occurred.
5826 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5827 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5828 ArrayRef<TemplateArgument> SugaredConverted,
5829 ArrayRef<TemplateArgument> CanonicalConverted) {
5830 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5831 SugaredConverted,
5832 SourceRange(TemplateLoc, RAngleLoc));
5833 if (Inst.isInvalid())
5834 return ExprError();
5835
5836 // Only substitute for the innermost template argument list.
5837 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5838 /*Final=*/true);
5839 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5840 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5841
5842 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5843 EnterExpressionEvaluationContext ConstantEvaluated(
5845 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5846}
5847
5848/// Substitute template arguments into the default template argument for
5849/// the given template template parameter.
5850///
5851/// \param SemaRef the semantic analysis object for which we are performing
5852/// the substitution.
5853///
5854/// \param Template the template that we are synthesizing template arguments
5855/// for.
5856///
5857/// \param TemplateLoc the location of the template name that started the
5858/// template-id we are checking.
5859///
5860/// \param RAngleLoc the location of the right angle bracket ('>') that
5861/// terminates the template-id.
5862///
5863/// \param Param the template template parameter whose default we are
5864/// substituting into.
5865///
5866/// \param Converted the list of template arguments provided for template
5867/// parameters that precede \p Param in the template parameter list.
5868///
5869/// \param QualifierLoc Will be set to the nested-name-specifier (with
5870/// source-location information) that precedes the template name.
5871///
5872/// \returns the substituted template argument, or NULL if an error occurred.
5874 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5875 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5876 ArrayRef<TemplateArgument> SugaredConverted,
5877 ArrayRef<TemplateArgument> CanonicalConverted,
5878 NestedNameSpecifierLoc &QualifierLoc) {
5880 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5881 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5882 if (Inst.isInvalid())
5883 return TemplateName();
5884
5885 // Only substitute for the innermost template argument list.
5886 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5887 /*Final=*/true);
5888 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5889 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5890
5891 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5892 // Substitute into the nested-name-specifier first,
5893 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5894 if (QualifierLoc) {
5895 QualifierLoc =
5896 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5897 if (!QualifierLoc)
5898 return TemplateName();
5899 }
5900
5901 return SemaRef.SubstTemplateName(
5902 QualifierLoc,
5905 TemplateArgLists);
5906}
5907
5908/// If the given template parameter has a default template
5909/// argument, substitute into that default template argument and
5910/// return the corresponding template argument.
5912 TemplateDecl *Template, SourceLocation TemplateLoc,
5913 SourceLocation RAngleLoc, Decl *Param,
5914 ArrayRef<TemplateArgument> SugaredConverted,
5915 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5916 HasDefaultArg = false;
5917
5918 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5919 if (!hasReachableDefaultArgument(TypeParm))
5920 return TemplateArgumentLoc();
5921
5922 HasDefaultArg = true;
5924 *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
5925 CanonicalConverted);
5926 if (DI)
5927 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5928
5929 return TemplateArgumentLoc();
5930 }
5931
5932 if (NonTypeTemplateParmDecl *NonTypeParm
5933 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5934 if (!hasReachableDefaultArgument(NonTypeParm))
5935 return TemplateArgumentLoc();
5936
5937 HasDefaultArg = true;
5939 *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
5940 CanonicalConverted);
5941 if (Arg.isInvalid())
5942 return TemplateArgumentLoc();
5943
5944 Expr *ArgE = Arg.getAs<Expr>();
5945 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5946 }
5947
5948 TemplateTemplateParmDecl *TempTempParm
5949 = cast<TemplateTemplateParmDecl>(Param);
5950 if (!hasReachableDefaultArgument(TempTempParm))
5951 return TemplateArgumentLoc();
5952
5953 HasDefaultArg = true;
5954 NestedNameSpecifierLoc QualifierLoc;
5956 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5957 CanonicalConverted, QualifierLoc);
5958 if (TName.isNull())
5959 return TemplateArgumentLoc();
5960
5961 return TemplateArgumentLoc(
5962 Context, TemplateArgument(TName),
5964 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5965}
5966
5967/// Convert a template-argument that we parsed as a type into a template, if
5968/// possible. C++ permits injected-class-names to perform dual service as
5969/// template template arguments and as template type arguments.
5972 // Extract and step over any surrounding nested-name-specifier.
5973 NestedNameSpecifierLoc QualLoc;
5974 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5975 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5976 return TemplateArgumentLoc();
5977
5978 QualLoc = ETLoc.getQualifierLoc();
5979 TLoc = ETLoc.getNamedTypeLoc();
5980 }
5981 // If this type was written as an injected-class-name, it can be used as a
5982 // template template argument.
5983 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5984 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5985 QualLoc, InjLoc.getNameLoc());
5986
5987 // If this type was written as an injected-class-name, it may have been
5988 // converted to a RecordType during instantiation. If the RecordType is
5989 // *not* wrapped in a TemplateSpecializationType and denotes a class
5990 // template specialization, it must have come from an injected-class-name.
5991 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5992 if (auto *CTSD =
5993 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5994 return TemplateArgumentLoc(Context,
5995 TemplateName(CTSD->getSpecializedTemplate()),
5996 QualLoc, RecLoc.getNameLoc());
5997
5998 return TemplateArgumentLoc();
5999}
6000
6001/// Check that the given template argument corresponds to the given
6002/// template parameter.
6003///
6004/// \param Param The template parameter against which the argument will be
6005/// checked.
6006///
6007/// \param Arg The template argument, which may be updated due to conversions.
6008///
6009/// \param Template The template in which the template argument resides.
6010///
6011/// \param TemplateLoc The location of the template name for the template
6012/// whose argument list we're matching.
6013///
6014/// \param RAngleLoc The location of the right angle bracket ('>') that closes
6015/// the template argument list.
6016///
6017/// \param ArgumentPackIndex The index into the argument pack where this
6018/// argument will be placed. Only valid if the parameter is a parameter pack.
6019///
6020/// \param Converted The checked, converted argument will be added to the
6021/// end of this small vector.
6022///
6023/// \param CTAK Describes how we arrived at this particular template argument:
6024/// explicitly written, deduced, etc.
6025///
6026/// \returns true on error, false otherwise.
6028 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
6029 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
6030 unsigned ArgumentPackIndex,
6031 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6032 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6034 // Check template type parameters.
6035 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
6036 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
6037 CanonicalConverted);
6038
6039 // Check non-type template parameters.
6040 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6041 // Do substitution on the type of the non-type template parameter
6042 // with the template arguments we've seen thus far. But if the
6043 // template has a dependent context then we cannot substitute yet.
6044 QualType NTTPType = NTTP->getType();
6045 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
6046 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
6047
6048 if (NTTPType->isInstantiationDependentType() &&
6049 !isa<TemplateTemplateParmDecl>(Template) &&
6050 !Template->getDeclContext()->isDependentContext()) {
6051 // Do substitution on the type of the non-type template parameter.
6052 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
6053 SugaredConverted,
6054 SourceRange(TemplateLoc, RAngleLoc));
6055 if (Inst.isInvalid())
6056 return true;
6057
6058 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
6059 /*Final=*/true);
6060 // If the parameter is a pack expansion, expand this slice of the pack.
6061 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
6063 ArgumentPackIndex);
6064 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
6065 NTTP->getDeclName());
6066 } else {
6067 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
6068 NTTP->getDeclName());
6069 }
6070
6071 // If that worked, check the non-type template parameter type
6072 // for validity.
6073 if (!NTTPType.isNull())
6074 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
6075 NTTP->getLocation());
6076 if (NTTPType.isNull())
6077 return true;
6078 }
6079
6080 switch (Arg.getArgument().getKind()) {
6082 llvm_unreachable("Should never see a NULL template argument here");
6083
6085 Expr *E = Arg.getArgument().getAsExpr();
6086 TemplateArgument SugaredResult, CanonicalResult;
6087 unsigned CurSFINAEErrors = NumSFINAEErrors;
6088 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
6089 CanonicalResult, CTAK);
6090 if (Res.isInvalid())
6091 return true;
6092 // If the current template argument causes an error, give up now.
6093 if (CurSFINAEErrors < NumSFINAEErrors)
6094 return true;
6095
6096 // If the resulting expression is new, then use it in place of the
6097 // old expression in the template argument.
6098 if (Res.get() != E) {
6099 TemplateArgument TA(Res.get());
6100 Arg = TemplateArgumentLoc(TA, Res.get());
6101 }
6102
6103 SugaredConverted.push_back(SugaredResult);
6104 CanonicalConverted.push_back(CanonicalResult);
6105 break;
6106 }
6107
6112 // We've already checked this template argument, so just copy
6113 // it to the list of converted arguments.
6114 SugaredConverted.push_back(Arg.getArgument());
6115 CanonicalConverted.push_back(
6117 break;
6118
6121 // We were given a template template argument. It may not be ill-formed;
6122 // see below.
6123 if (DependentTemplateName *DTN
6126 // We have a template argument such as \c T::template X, which we
6127 // parsed as a template template argument. However, since we now
6128 // know that we need a non-type template argument, convert this
6129 // template name into an expression.
6130
6131 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
6132 Arg.getTemplateNameLoc());
6133
6134 CXXScopeSpec SS;
6136 // FIXME: the template-template arg was a DependentTemplateName,
6137 // so it was provided with a template keyword. However, its source
6138 // location is not stored in the template argument structure.
6139 SourceLocation TemplateKWLoc;
6141 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
6142 nullptr);
6143
6144 // If we parsed the template argument as a pack expansion, create a
6145 // pack expansion expression.
6148 if (E.isInvalid())
6149 return true;
6150 }
6151
6152 TemplateArgument SugaredResult, CanonicalResult;
6153 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
6154 CanonicalResult, CTAK_Specified);
6155 if (E.isInvalid())
6156 return true;
6157
6158 SugaredConverted.push_back(SugaredResult);
6159 CanonicalConverted.push_back(CanonicalResult);
6160 break;
6161 }
6162
6163 // We have a template argument that actually does refer to a class
6164 // template, alias template, or template template parameter, and
6165 // therefore cannot be a non-type template argument.
6166 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
6167 << Arg.getSourceRange();
6169
6170 return true;
6171
6173 // We have a non-type template parameter but the template
6174 // argument is a type.
6175
6176 // C++ [temp.arg]p2:
6177 // In a template-argument, an ambiguity between a type-id and
6178 // an expression is resolved to a type-id, regardless of the
6179 // form of the corresponding template-parameter.
6180 //
6181 // We warn specifically about this case, since it can be rather
6182 // confusing for users.
6183 QualType T = Arg.getArgument().getAsType();
6184 SourceRange SR = Arg.getSourceRange();
6185 if (T->isFunctionType())
6186 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
6187 else
6188 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
6190 return true;
6191 }
6192
6194 llvm_unreachable("Caller must expand template argument packs");
6195 }
6196
6197 return false;
6198 }
6199
6200
6201 // Check template template parameters.
6202 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
6203
6204 TemplateParameterList *Params = TempParm->getTemplateParameters();
6205 if (TempParm->isExpandedParameterPack())
6206 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
6207
6208 // Substitute into the template parameter list of the template
6209 // template parameter, since previously-supplied template arguments
6210 // may appear within the template template parameter.
6211 //
6212 // FIXME: Skip this if the parameters aren't instantiation-dependent.
6213 {
6214 // Set up a template instantiation context.
6216 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
6217 SugaredConverted,
6218 SourceRange(TemplateLoc, RAngleLoc));
6219 if (Inst.isInvalid())
6220 return true;
6221
6222 Params =
6225 Template, SugaredConverted, /*Final=*/true),
6226 /*EvaluateConstraints=*/false);
6227 if (!Params)
6228 return true;
6229 }
6230
6231 // C++1z [temp.local]p1: (DR1004)
6232 // When [the injected-class-name] is used [...] as a template-argument for
6233 // a template template-parameter [...] it refers to the class template
6234 // itself.
6238 if (!ConvertedArg.getArgument().isNull())
6239 Arg = ConvertedArg;
6240 }
6241
6242 switch (Arg.getArgument().getKind()) {
6244 llvm_unreachable("Should never see a NULL template argument here");
6245
6248 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
6249 return true;
6250
6251 SugaredConverted.push_back(Arg.getArgument());
6252 CanonicalConverted.push_back(
6254 break;
6255
6258 // We have a template template parameter but the template
6259 // argument does not refer to a template.
6260 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
6261 << getLangOpts().CPlusPlus11;
6262 return true;
6263
6268 llvm_unreachable("non-type argument with template template parameter");
6269
6271 llvm_unreachable("Caller must expand template argument packs");
6272 }
6273
6274 return false;
6275}
6276
6277/// Diagnose a missing template argument.
6278template<typename TemplateParmDecl>
6280 TemplateDecl *TD,
6281 const TemplateParmDecl *D,
6283 // Dig out the most recent declaration of the template parameter; there may be
6284 // declarations of the template that are more recent than TD.
6285 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
6286 ->getTemplateParameters()
6287 ->getParam(D->getIndex()));
6288
6289 // If there's a default argument that's not reachable, diagnose that we're
6290 // missing a module import.
6292 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
6293 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
6294 D->getDefaultArgumentLoc(), Modules,
6296 /*Recover*/true);
6297 return true;
6298 }
6299
6300 // FIXME: If there's a more recent default argument that *is* visible,
6301 // diagnose that it was declared too late.
6302
6304
6305 S.Diag(Loc, diag::err_template_arg_list_different_arity)
6306 << /*not enough args*/0
6308 << TD;
6309 S.NoteTemplateLocation(*TD, Params->getSourceRange());
6310 return true;
6311}
6312
6313/// Check that the given template argument list is well-formed
6314/// for specializing the given template.
6316 TemplateDecl *Template, SourceLocation TemplateLoc,
6317 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
6318 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6319 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6320 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
6321
6323 *ConstraintsNotSatisfied = false;
6324
6325 // Make a copy of the template arguments for processing. Only make the
6326 // changes at the end when successful in matching the arguments to the
6327 // template.
6328 TemplateArgumentListInfo NewArgs = TemplateArgs;
6329
6331
6332 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
6333
6334 // C++ [temp.arg]p1:
6335 // [...] The type and form of each template-argument specified in
6336 // a template-id shall match the type and form specified for the
6337 // corresponding parameter declared by the template in its
6338 // template-parameter-list.
6339 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
6340 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
6341 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
6342 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
6343 LocalInstantiationScope InstScope(*this, true);
6344 for (TemplateParameterList::iterator Param = Params->begin(),
6345 ParamEnd = Params->end();
6346 Param != ParamEnd; /* increment in loop */) {
6347 // If we have an expanded parameter pack, make sure we don't have too
6348 // many arguments.
6349 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
6350 if (*Expansions == SugaredArgumentPack.size()) {
6351 // We're done with this parameter pack. Pack up its arguments and add
6352 // them to the list.
6353 SugaredConverted.push_back(
6354 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6355 SugaredArgumentPack.clear();
6356
6357 CanonicalConverted.push_back(
6358 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6359 CanonicalArgumentPack.clear();
6360
6361 // This argument is assigned to the next parameter.
6362 ++Param;
6363 continue;
6364 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
6365 // Not enough arguments for this parameter pack.
6366 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6367 << /*not enough args*/0
6369 << Template;
6370 NoteTemplateLocation(*Template, Params->getSourceRange());
6371 return true;
6372 }
6373 }
6374
6375 if (ArgIdx < NumArgs) {
6376 // Check the template argument we were given.
6377 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
6378 RAngleLoc, SugaredArgumentPack.size(),
6379 SugaredConverted, CanonicalConverted,
6381 return true;
6382
6383 CanonicalConverted.back().setIsDefaulted(
6385 Context, NewArgs[ArgIdx].getArgument(), *Param,
6386 CanonicalConverted, Params->getDepth()));
6387
6388 bool PackExpansionIntoNonPack =
6389 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
6390 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
6391 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
6392 isa<ConceptDecl>(Template))) {
6393 // Core issue 1430: we have a pack expansion as an argument to an
6394 // alias template, and it's not part of a parameter pack. This
6395 // can't be canonicalized, so reject it now.
6396 // As for concepts - we cannot normalize constraints where this
6397 // situation exists.
6398 Diag(NewArgs[ArgIdx].getLocation(),
6399 diag::err_template_expansion_into_fixed_list)
6400 << (isa<ConceptDecl>(Template) ? 1 : 0)
6401 << NewArgs[ArgIdx].getSourceRange();
6403 return true;
6404 }
6405
6406 // We're now done with this argument.
6407 ++ArgIdx;
6408
6409 if ((*Param)->isTemplateParameterPack()) {
6410 // The template parameter was a template parameter pack, so take the
6411 // deduced argument and place it on the argument pack. Note that we
6412 // stay on the same template parameter so that we can deduce more
6413 // arguments.
6414 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
6415 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
6416 } else {
6417 // Move to the next template parameter.
6418 ++Param;
6419 }
6420
6421 // If we just saw a pack expansion into a non-pack, then directly convert
6422 // the remaining arguments, because we don't know what parameters they'll
6423 // match up with.
6424 if (PackExpansionIntoNonPack) {
6425 if (!SugaredArgumentPack.empty()) {
6426 // If we were part way through filling in an expanded parameter pack,
6427 // fall back to just producing individual arguments.
6428 SugaredConverted.insert(SugaredConverted.end(),
6429 SugaredArgumentPack.begin(),
6430 SugaredArgumentPack.end());
6431 SugaredArgumentPack.clear();
6432
6433 CanonicalConverted.insert(CanonicalConverted.end(),
6434 CanonicalArgumentPack.begin(),
6435 CanonicalArgumentPack.end());
6436 CanonicalArgumentPack.clear();
6437 }
6438
6439 while (ArgIdx < NumArgs) {
6440 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6441 SugaredConverted.push_back(Arg);
6442 CanonicalConverted.push_back(
6444 ++ArgIdx;
6445 }
6446
6447 return false;
6448 }
6449
6450 continue;
6451 }
6452
6453 // If we're checking a partial template argument list, we're done.
6454 if (PartialTemplateArgs) {
6455 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6456 SugaredConverted.push_back(
6457 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6458 CanonicalConverted.push_back(
6459 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6460 }
6461 return false;
6462 }
6463
6464 // If we have a template parameter pack with no more corresponding
6465 // arguments, just break out now and we'll fill in the argument pack below.
6466 if ((*Param)->isTemplateParameterPack()) {
6467 assert(!getExpandedPackSize(*Param) &&
6468 "Should have dealt with this already");
6469
6470 // A non-expanded parameter pack before the end of the parameter list
6471 // only occurs for an ill-formed template parameter list, unless we've
6472 // got a partial argument list for a function template, so just bail out.
6473 if (Param + 1 != ParamEnd) {
6474 assert(
6475 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6476 "Concept templates must have parameter packs at the end.");
6477 return true;
6478 }
6479
6480 SugaredConverted.push_back(
6481 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6482 SugaredArgumentPack.clear();
6483
6484 CanonicalConverted.push_back(
6485 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6486 CanonicalArgumentPack.clear();
6487
6488 ++Param;
6489 continue;
6490 }
6491
6492 // Check whether we have a default argument.
6494
6495 // Retrieve the default template argument from the template
6496 // parameter. For each kind of template parameter, we substitute the
6497 // template arguments provided thus far and any "outer" template arguments
6498 // (when the template parameter was part of a nested template) into
6499 // the default argument.
6500 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6502 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6503 NewArgs);
6504
6506 *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6507 CanonicalConverted);
6508 if (!ArgType)
6509 return true;
6510
6512 ArgType);
6513 } else if (NonTypeTemplateParmDecl *NTTP
6514 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6515 if (!hasReachableDefaultArgument(NTTP))
6516 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6517 NewArgs);
6518
6520 *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6521 CanonicalConverted);
6522 if (E.isInvalid())
6523 return true;
6524
6525 Expr *Ex = E.getAs<Expr>();
6527 } else {
6528 TemplateTemplateParmDecl *TempParm
6529 = cast<TemplateTemplateParmDecl>(*Param);
6530
6531 if (!hasReachableDefaultArgument(TempParm))
6532 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6533 NewArgs);
6534
6535 NestedNameSpecifierLoc QualifierLoc;
6537 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6538 CanonicalConverted, QualifierLoc);
6539 if (Name.isNull())
6540 return true;
6541
6542 Arg = TemplateArgumentLoc(
6543 Context, TemplateArgument(Name), QualifierLoc,
6545 }
6546
6547 // Introduce an instantiation record that describes where we are using
6548 // the default template argument. We're not actually instantiating a
6549 // template here, we just create this object to put a note into the
6550 // context stack.
6551 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6552 SugaredConverted,
6553 SourceRange(TemplateLoc, RAngleLoc));
6554 if (Inst.isInvalid())
6555 return true;
6556
6557 // Check the default template argument.
6558 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6559 SugaredConverted, CanonicalConverted,
6561 return true;
6562
6563 CanonicalConverted.back().setIsDefaulted(true);
6564
6565 // Core issue 150 (assumed resolution): if this is a template template
6566 // parameter, keep track of the default template arguments from the
6567 // template definition.
6568 if (isTemplateTemplateParameter)
6569 NewArgs.addArgument(Arg);
6570
6571 // Move to the next template parameter and argument.
6572 ++Param;
6573 ++ArgIdx;
6574 }
6575
6576 // If we're performing a partial argument substitution, allow any trailing
6577 // pack expansions; they might be empty. This can happen even if
6578 // PartialTemplateArgs is false (the list of arguments is complete but
6579 // still dependent).
6580 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6582 while (ArgIdx < NumArgs &&
6583 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6584 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6585 SugaredConverted.push_back(Arg);
6586 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6587 }
6588 }
6589
6590 // If we have any leftover arguments, then there were too many arguments.
6591 // Complain and fail.
6592 if (ArgIdx < NumArgs) {
6593 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6594 << /*too many args*/1
6596 << Template
6597 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6598 NoteTemplateLocation(*Template, Params->getSourceRange());
6599 return true;
6600 }
6601
6602 // No problems found with the new argument list, propagate changes back
6603 // to caller.
6604 if (UpdateArgsWithConversions)
6605 TemplateArgs = std::move(NewArgs);
6606
6607 if (!PartialTemplateArgs) {
6608 // Setup the context/ThisScope for the case where we are needing to
6609 // re-instantiate constraints outside of normal instantiation.
6610 DeclContext *NewContext = Template->getDeclContext();
6611
6612 // If this template is in a template, make sure we extract the templated
6613 // decl.
6614 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6615 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6616 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6617
6618 Qualifiers ThisQuals;
6619 if (const auto *Method =
6620 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6621 ThisQuals = Method->getMethodQualifiers();
6622
6623 ContextRAII Context(*this, NewContext);
6624 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6625
6627 Template, NewContext, /*Final=*/false, CanonicalConverted,
6628 /*RelativeToPrimary=*/true,
6629 /*Pattern=*/nullptr,
6630 /*ForConceptInstantiation=*/true);
6632 Template, MLTAL,
6633 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6636 return true;
6637 }
6638 }
6639
6640 return false;
6641}
6642
6643namespace {
6644 class UnnamedLocalNoLinkageFinder
6645 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6646 {
6647 Sema &S;
6648 SourceRange SR;
6649
6651
6652 public:
6653 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6654
6655 bool Visit(QualType T) {
6656 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6657 }
6658
6659#define TYPE(Class, Parent) \
6660 bool Visit##Class##Type(const Class##Type *);
6661#define ABSTRACT_TYPE(Class, Parent) \
6662 bool Visit##Class##Type(const Class##Type *) { return false; }
6663#define NON_CANONICAL_TYPE(Class, Parent) \
6664 bool Visit##Class##Type(const Class##Type *) { return false; }
6665#include "clang/AST/TypeNodes.inc"
6666
6667 bool VisitTagDecl(const TagDecl *Tag);
6668 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6669 };
6670} // end anonymous namespace
6671
6672bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6673 return false;
6674}
6675
6676bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6677 return Visit(T->getElementType());
6678}
6679
6680bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6681 return Visit(T->getPointeeType());
6682}
6683
6684bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6685 const BlockPointerType* T) {
6686 return Visit(T->getPointeeType());
6687}
6688
6689bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6690 const LValueReferenceType* T) {
6691 return Visit(T->getPointeeType());
6692}
6693
6694bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6695 const RValueReferenceType* T) {
6696 return Visit(T->getPointeeType());
6697}
6698
6699bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6700 const MemberPointerType* T) {
6701 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
6702}
6703
6704bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6705 const ConstantArrayType* T) {
6706 return Visit(T->getElementType());
6707}
6708
6709bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6710 const IncompleteArrayType* T) {
6711 return Visit(T->getElementType());
6712}
6713
6714bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6715 const VariableArrayType* T) {
6716 return Visit(T->getElementType());
6717}
6718
6719bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6720 const DependentSizedArrayType* T) {
6721 return Visit(T->getElementType());
6722}
6723
6724bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6725 const DependentSizedExtVectorType* T) {
6726 return Visit(T->getElementType());
6727}
6728
6729bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6730 const DependentSizedMatrixType *T) {
6731 return Visit(T->getElementType());
6732}
6733
6734bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6735 const DependentAddressSpaceType *T) {
6736 return Visit(T->getPointeeType());
6737}
6738
6739bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6740 return Visit(T->getElementType());
6741}
6742
6743bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6744 const DependentVectorType *T) {
6745 return Visit(T->getElementType());
6746}
6747
6748bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6749 return Visit(T->getElementType());
6750}
6751
6752bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6753 const ConstantMatrixType *T) {
6754 return Visit(T->getElementType());
6755}
6756
6757bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6758 const FunctionProtoType* T) {
6759 for (const auto &A : T->param_types()) {
6760 if (Visit(A))
6761 return true;
6762 }
6763
6764 return Visit(T->getReturnType());
6765}
6766
6767bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6768 const FunctionNoProtoType* T) {
6769 return Visit(T->getReturnType());
6770}
6771
6772bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6773 const UnresolvedUsingType*) {
6774 return false;
6775}
6776
6777bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6778 return false;
6779}
6780
6781bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6782 return Visit(T->getUnmodifiedType());
6783}
6784
6785bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6786 return false;
6787}
6788
6789bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6790 const PackIndexingType *) {
6791 return false;
6792}
6793
6794bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6795 const UnaryTransformType*) {
6796 return false;
6797}
6798
6799bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6800 return Visit(T->getDeducedType());
6801}
6802
6803bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6805 return Visit(T->getDeducedType());
6806}
6807
6808bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6809 return VisitTagDecl(T->getDecl());
6810}
6811
6812bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6813 return VisitTagDecl(T->getDecl());
6814}
6815
6816bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6817 const TemplateTypeParmType*) {
6818 return false;
6819}
6820
6821bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6823 return false;
6824}
6825
6826bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6828 return false;
6829}
6830
6831bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6832 const InjectedClassNameType* T) {
6833 return VisitTagDecl(T->getDecl());
6834}
6835
6836bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6837 const DependentNameType* T) {
6838 return VisitNestedNameSpecifier(T->getQualifier());
6839}
6840
6841bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6843 if (auto *Q = T->getQualifier())
6844 return VisitNestedNameSpecifier(Q);
6845 return false;
6846}
6847
6848bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6849 const PackExpansionType* T) {
6850 return Visit(T->getPattern());
6851}
6852
6853bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6854 return false;
6855}
6856
6857bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6858 const ObjCInterfaceType *) {
6859 return false;
6860}
6861
6862bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6863 const ObjCObjectPointerType *) {
6864 return false;
6865}
6866
6867bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6868 return Visit(T->getValueType());
6869}
6870
6871bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6872 return false;
6873}
6874
6875bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6876 return false;
6877}
6878
6879bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6880 const DependentBitIntType *T) {
6881 return false;
6882}
6883
6884bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6885 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6886 S.Diag(SR.getBegin(),
6887 S.getLangOpts().CPlusPlus11 ?
6888 diag::warn_cxx98_compat_template_arg_local_type :
6889 diag::ext_template_arg_local_type)
6890 << S.Context.getTypeDeclType(Tag) << SR;
6891 return true;
6892 }
6893
6894 if (!Tag->hasNameForLinkage()) {
6895 S.Diag(SR.getBegin(),
6896 S.getLangOpts().CPlusPlus11 ?
6897 diag::warn_cxx98_compat_template_arg_unnamed_type :
6898 diag::ext_template_arg_unnamed_type) << SR;
6899 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6900 return true;
6901 }
6902
6903 return false;
6904}
6905
6906bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6907 NestedNameSpecifier *NNS) {
6908 assert(NNS);
6909 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6910 return true;
6911
6912 switch (NNS->getKind()) {
6918 return false;
6919
6922 return Visit(QualType(NNS->getAsType(), 0));
6923 }
6924 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6925}
6926
6927/// Check a template argument against its corresponding
6928/// template type parameter.
6929///
6930/// This routine implements the semantics of C++ [temp.arg.type]. It
6931/// returns true if an error occurred, and false otherwise.
6933 assert(ArgInfo && "invalid TypeSourceInfo");
6934 QualType Arg = ArgInfo->getType();
6935 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6936 QualType CanonArg = Context.getCanonicalType(Arg);
6937
6938 if (CanonArg->isVariablyModifiedType()) {
6939 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6941 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6942 }
6943
6944 // C++03 [temp.arg.type]p2:
6945 // A local type, a type with no linkage, an unnamed type or a type
6946 // compounded from any of these types shall not be used as a
6947 // template-argument for a template type-parameter.
6948 //
6949 // C++11 allows these, and even in C++03 we allow them as an extension with
6950 // a warning.
6951 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6952 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6953 (void)Finder.Visit(CanonArg);
6954 }
6955
6956 return false;
6957}
6958
6962 NPV_Error
6964
6965/// Determine whether the given template argument is a null pointer
6966/// value of the appropriate type.
6969 QualType ParamType, Expr *Arg,
6970 Decl *Entity = nullptr) {
6971 if (Arg->isValueDependent() || Arg->isTypeDependent())
6972 return NPV_NotNullPointer;
6973
6974 // dllimport'd entities aren't constant but are available inside of template
6975 // arguments.
6976 if (Entity && Entity->hasAttr<DLLImportAttr>())
6977 return NPV_NotNullPointer;
6978
6979 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6980 llvm_unreachable(
6981 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6982
6983 if (!S.getLangOpts().CPlusPlus11)
6984 return NPV_NotNullPointer;
6985
6986 // Determine whether we have a constant expression.
6988 if (ArgRV.isInvalid())
6989 return NPV_Error;
6990 Arg = ArgRV.get();
6991
6992 Expr::EvalResult EvalResult;
6994 EvalResult.Diag = &Notes;
6995 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6996 EvalResult.HasSideEffects) {
6997 SourceLocation DiagLoc = Arg->getExprLoc();
6998
6999 // If our only note is the usual "invalid subexpression" note, just point
7000 // the caret at its location rather than producing an essentially
7001 // redundant note.
7002 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7003 diag::note_invalid_subexpr_in_const_expr) {
7004 DiagLoc = Notes[0].first;
7005 Notes.clear();
7006 }
7007
7008 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
7009 << Arg->getType() << Arg->getSourceRange();
7010 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7011 S.Diag(Notes[I].first, Notes[I].second);
7012
7014 return NPV_Error;
7015 }
7016
7017 // C++11 [temp.arg.nontype]p1:
7018 // - an address constant expression of type std::nullptr_t
7019 if (Arg->getType()->isNullPtrType())
7020 return NPV_NullPointer;
7021
7022 // - a constant expression that evaluates to a null pointer value (4.10); or
7023 // - a constant expression that evaluates to a null member pointer value
7024 // (4.11); or
7025 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
7026 (EvalResult.Val.isMemberPointer() &&
7027 !EvalResult.Val.getMemberPointerDecl())) {
7028 // If our expression has an appropriate type, we've succeeded.
7029 bool ObjCLifetimeConversion;
7030 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
7031 S.IsQualificationConversion(Arg->getType(), ParamType, false,
7032 ObjCLifetimeConversion))
7033 return NPV_NullPointer;
7034
7035 // The types didn't match, but we know we got a null pointer; complain,
7036 // then recover as if the types were correct.
7037 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
7038 << Arg->getType() << ParamType << Arg->getSourceRange();
7040 return NPV_NullPointer;
7041 }
7042
7043 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
7044 // We found a pointer that isn't null, but doesn't refer to an object.
7045 // We could just return NPV_NotNullPointer, but we can print a better
7046 // message with the information we have here.
7047 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
7048 << EvalResult.Val.getAsString(S.Context, ParamType);
7050 return NPV_Error;
7051 }
7052
7053 // If we don't have a null pointer value, but we do have a NULL pointer
7054 // constant, suggest a cast to the appropriate type.
7056 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
7057 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
7058 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
7060 ")");
7062 return NPV_NullPointer;
7063 }
7064
7065 // FIXME: If we ever want to support general, address-constant expressions
7066 // as non-type template arguments, we should return the ExprResult here to
7067 // be interpreted by the caller.
7068 return NPV_NotNullPointer;
7069}
7070
7071/// Checks whether the given template argument is compatible with its
7072/// template parameter.
7074 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7075 Expr *Arg, QualType ArgType) {
7076 bool ObjCLifetimeConversion;
7077 if (ParamType->isPointerType() &&
7078 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
7079 S.IsQualificationConversion(ArgType, ParamType, false,
7080 ObjCLifetimeConversion)) {
7081 // For pointer-to-object types, qualification conversions are
7082 // permitted.
7083 } else {
7084 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
7085 if (!ParamRef->getPointeeType()->isFunctionType()) {
7086 // C++ [temp.arg.nontype]p5b3:
7087 // For a non-type template-parameter of type reference to
7088 // object, no conversions apply. The type referred to by the
7089 // reference may be more cv-qualified than the (otherwise
7090 // identical) type of the template- argument. The
7091 // template-parameter is bound directly to the
7092 // template-argument, which shall be an lvalue.
7093
7094 // FIXME: Other qualifiers?
7095 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
7096 unsigned ArgQuals = ArgType.getCVRQualifiers();
7097
7098 if ((ParamQuals | ArgQuals) != ParamQuals) {
7099 S.Diag(Arg->getBeginLoc(),
7100 diag::err_template_arg_ref_bind_ignores_quals)
7101 << ParamType << Arg->getType() << Arg->getSourceRange();
7103 return true;
7104 }
7105 }
7106 }
7107
7108 // At this point, the template argument refers to an object or
7109 // function with external linkage. We now need to check whether the
7110 // argument and parameter types are compatible.
7111 if (!S.Context.hasSameUnqualifiedType(ArgType,
7112 ParamType.getNonReferenceType())) {
7113 // We can't perform this conversion or binding.
7114 if (ParamType->isReferenceType())
7115 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
7116 << ParamType << ArgIn->getType() << Arg->getSourceRange();
7117 else
7118 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7119 << ArgIn->getType() << ParamType << Arg->getSourceRange();
7121 return true;
7122 }
7123 }
7124
7125 return false;
7126}
7127
7128/// Checks whether the given template argument is the address
7129/// of an object or function according to C++ [temp.arg.nontype]p1.
7131 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7132 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7133 bool Invalid = false;
7134 Expr *Arg = ArgIn;
7135 QualType ArgType = Arg->getType();
7136
7137 bool AddressTaken = false;
7138 SourceLocation AddrOpLoc;
7139 if (S.getLangOpts().MicrosoftExt) {
7140 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
7141 // dereference and address-of operators.
7142 Arg = Arg->IgnoreParenCasts();
7143
7144 bool ExtWarnMSTemplateArg = false;
7145 UnaryOperatorKind FirstOpKind;
7146 SourceLocation FirstOpLoc;
7147 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7148 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
7149 if (UnOpKind == UO_Deref)
7150 ExtWarnMSTemplateArg = true;
7151 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
7152 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
7153 if (!AddrOpLoc.isValid()) {
7154 FirstOpKind = UnOpKind;
7155 FirstOpLoc = UnOp->getOperatorLoc();
7156 }
7157 } else
7158 break;
7159 }
7160 if (FirstOpLoc.isValid()) {
7161 if (ExtWarnMSTemplateArg)
7162 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
7163 << ArgIn->getSourceRange();
7164
7165 if (FirstOpKind == UO_AddrOf)
7166 AddressTaken = true;
7167 else if (Arg->getType()->isPointerType()) {
7168 // We cannot let pointers get dereferenced here, that is obviously not a
7169 // constant expression.
7170 assert(FirstOpKind == UO_Deref);
7171 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7172 << Arg->getSourceRange();
7173 }
7174 }
7175 } else {
7176 // See through any implicit casts we added to fix the type.
7177 Arg = Arg->IgnoreImpCasts();
7178
7179 // C++ [temp.arg.nontype]p1:
7180 //
7181 // A template-argument for a non-type, non-template
7182 // template-parameter shall be one of: [...]
7183 //
7184 // -- the address of an object or function with external
7185 // linkage, including function templates and function
7186 // template-ids but excluding non-static class members,
7187 // expressed as & id-expression where the & is optional if
7188 // the name refers to a function or array, or if the
7189 // corresponding template-parameter is a reference; or
7190
7191 // In C++98/03 mode, give an extension warning on any extra parentheses.
7192 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7193 bool ExtraParens = false;
7194 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7195 if (!Invalid && !ExtraParens) {
7196 S.Diag(Arg->getBeginLoc(),
7197 S.getLangOpts().CPlusPlus11
7198 ? diag::warn_cxx98_compat_template_arg_extra_parens
7199 : diag::ext_template_arg_extra_parens)
7200 << Arg->getSourceRange();
7201 ExtraParens = true;
7202 }
7203
7204 Arg = Parens->getSubExpr();
7205 }
7206
7207 while (SubstNonTypeTemplateParmExpr *subst =
7208 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7209 Arg = subst->getReplacement()->IgnoreImpCasts();
7210
7211 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7212 if (UnOp->getOpcode() == UO_AddrOf) {
7213 Arg = UnOp->getSubExpr();
7214 AddressTaken = true;
7215 AddrOpLoc = UnOp->getOperatorLoc();
7216 }
7217 }
7218
7219 while (SubstNonTypeTemplateParmExpr *subst =
7220 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7221 Arg = subst->getReplacement()->IgnoreImpCasts();
7222 }
7223
7224 ValueDecl *Entity = nullptr;
7225 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
7226 Entity = DRE->getDecl();
7227 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
7228 Entity = CUE->getGuidDecl();
7229
7230 // If our parameter has pointer type, check for a null template value.
7231 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
7232 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
7233 Entity)) {
7234 case NPV_NullPointer:
7235 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7236 SugaredConverted = TemplateArgument(ParamType,
7237 /*isNullPtr=*/true);
7238 CanonicalConverted =
7240 /*isNullPtr=*/true);
7241 return false;
7242
7243 case NPV_Error:
7244 return true;
7245
7246 case NPV_NotNullPointer:
7247 break;
7248 }
7249 }
7250
7251 // Stop checking the precise nature of the argument if it is value dependent,
7252 // it should be checked when instantiated.
7253 if (Arg->isValueDependent()) {
7254 SugaredConverted = TemplateArgument(ArgIn);
7255 CanonicalConverted =
7256 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7257 return false;
7258 }
7259
7260 if (!Entity) {
7261 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7262 << Arg->getSourceRange();
7264 return true;
7265 }
7266
7267 // Cannot refer to non-static data members
7268 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
7269 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
7270 << Entity << Arg->getSourceRange();
7272 return true;
7273 }
7274
7275 // Cannot refer to non-static member functions
7276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
7277 if (!Method->isStatic()) {
7278 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
7279 << Method << Arg->getSourceRange();
7281 return true;
7282 }
7283 }
7284
7285 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
7286 VarDecl *Var = dyn_cast<VarDecl>(Entity);
7287 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
7288
7289 // A non-type template argument must refer to an object or function.
7290 if (!Func && !Var && !Guid) {
7291 // We found something, but we don't know specifically what it is.
7292 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
7293 << Arg->getSourceRange();
7294 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
7295 return true;
7296 }
7297
7298 // Address / reference template args must have external linkage in C++98.
7299 if (Entity->getFormalLinkage() == Linkage::Internal) {
7300 S.Diag(Arg->getBeginLoc(),
7301 S.getLangOpts().CPlusPlus11
7302 ? diag::warn_cxx98_compat_template_arg_object_internal
7303 : diag::ext_template_arg_object_internal)
7304 << !Func << Entity << Arg->getSourceRange();
7305 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7306 << !Func;
7307 } else if (!Entity->hasLinkage()) {
7308 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
7309 << !Func << Entity << Arg->getSourceRange();
7310 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7311 << !Func;
7312 return true;
7313 }
7314
7315 if (Var) {
7316 // A value of reference type is not an object.
7317 if (Var->getType()->isReferenceType()) {
7318 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
7319 << Var->getType() << Arg->getSourceRange();
7321 return true;
7322 }
7323
7324 // A template argument must have static storage duration.
7325 if (Var->getTLSKind()) {
7326 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
7327 << Arg->getSourceRange();
7328 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7329 return true;
7330 }
7331 }
7332
7333 if (AddressTaken && ParamType->isReferenceType()) {
7334 // If we originally had an address-of operator, but the
7335 // parameter has reference type, complain and (if things look
7336 // like they will work) drop the address-of operator.
7337 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7338 ParamType.getNonReferenceType())) {
7339 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7340 << ParamType;
7342 return true;
7343 }
7344
7345 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7346 << ParamType
7347 << FixItHint::CreateRemoval(AddrOpLoc);
7349
7350 ArgType = Entity->getType();
7351 }
7352
7353 // If the template parameter has pointer type, either we must have taken the
7354 // address or the argument must decay to a pointer.
7355 if (!AddressTaken && ParamType->isPointerType()) {
7356 if (Func) {
7357 // Function-to-pointer decay.
7358 ArgType = S.Context.getPointerType(Func->getType());
7359 } else if (Entity->getType()->isArrayType()) {
7360 // Array-to-pointer decay.
7361 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7362 } else {
7363 // If the template parameter has pointer type but the address of
7364 // this object was not taken, complain and (possibly) recover by
7365 // taking the address of the entity.
7366 ArgType = S.Context.getPointerType(Entity->getType());
7367 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7368 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7369 << ParamType;
7371 return true;
7372 }
7373
7374 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7375 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7376
7378 }
7379 }
7380
7381 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7382 Arg, ArgType))
7383 return true;
7384
7385 // Create the template argument.
7386 SugaredConverted = TemplateArgument(Entity, ParamType);
7387 CanonicalConverted =
7388 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
7389 S.Context.getCanonicalType(ParamType));
7390 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7391 return false;
7392}
7393
7394/// Checks whether the given template argument is a pointer to
7395/// member constant according to C++ [temp.arg.nontype]p1.
7396static bool
7398 QualType ParamType, Expr *&ResultArg,
7399 TemplateArgument &SugaredConverted,
7400 TemplateArgument &CanonicalConverted) {
7401 bool Invalid = false;
7402
7403 Expr *Arg = ResultArg;
7404 bool ObjCLifetimeConversion;
7405
7406 // C++ [temp.arg.nontype]p1:
7407 //
7408 // A template-argument for a non-type, non-template
7409 // template-parameter shall be one of: [...]
7410 //
7411 // -- a pointer to member expressed as described in 5.3.1.
7412 DeclRefExpr *DRE = nullptr;
7413
7414 // In C++98/03 mode, give an extension warning on any extra parentheses.
7415 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7416 bool ExtraParens = false;
7417 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7418 if (!Invalid && !ExtraParens) {
7419 S.Diag(Arg->getBeginLoc(),
7420 S.getLangOpts().CPlusPlus11
7421 ? diag::warn_cxx98_compat_template_arg_extra_parens
7422 : diag::ext_template_arg_extra_parens)
7423 << Arg->getSourceRange();
7424 ExtraParens = true;
7425 }
7426
7427 Arg = Parens->getSubExpr();
7428 }
7429
7430 while (SubstNonTypeTemplateParmExpr *subst =
7431 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7432 Arg = subst->getReplacement()->IgnoreImpCasts();
7433
7434 // A pointer-to-member constant written &Class::member.
7435 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7436 if (UnOp->getOpcode() == UO_AddrOf) {
7437 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7438 if (DRE && !DRE->getQualifier())
7439 DRE = nullptr;
7440 }
7441 }
7442 // A constant of pointer-to-member type.
7443 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7444 ValueDecl *VD = DRE->getDecl();
7445 if (VD->getType()->isMemberPointerType()) {
7446 if (isa<NonTypeTemplateParmDecl>(VD)) {
7447 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7448 SugaredConverted = TemplateArgument(Arg);
7449 CanonicalConverted =
7450 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7451 } else {
7452 SugaredConverted = TemplateArgument(VD, ParamType);
7453 CanonicalConverted =
7454 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7455 S.Context.getCanonicalType(ParamType));
7456 }
7457 return Invalid;
7458 }
7459 }
7460
7461 DRE = nullptr;
7462 }
7463
7464 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7465
7466 // Check for a null pointer value.
7467 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7468 Entity)) {
7469 case NPV_Error:
7470 return true;
7471 case NPV_NullPointer:
7472 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7473 SugaredConverted = TemplateArgument(ParamType,
7474 /*isNullPtr*/ true);
7475 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7476 /*isNullPtr*/ true);
7477 return false;
7478 case NPV_NotNullPointer:
7479 break;
7480 }
7481
7482 if (S.IsQualificationConversion(ResultArg->getType(),
7483 ParamType.getNonReferenceType(), false,
7484 ObjCLifetimeConversion)) {
7485 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7486 ResultArg->getValueKind())
7487 .get();
7488 } else if (!S.Context.hasSameUnqualifiedType(
7489 ResultArg->getType(), ParamType.getNonReferenceType())) {
7490 // We can't perform this conversion.
7491 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7492 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7494 return true;
7495 }
7496
7497 if (!DRE)
7498 return S.Diag(Arg->getBeginLoc(),
7499 diag::err_template_arg_not_pointer_to_member_form)
7500 << Arg->getSourceRange();
7501
7502 if (isa<FieldDecl>(DRE->getDecl()) ||
7503 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7504 isa<CXXMethodDecl>(DRE->getDecl())) {
7505 assert((isa<FieldDecl>(DRE->getDecl()) ||
7506 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7507 cast<CXXMethodDecl>(DRE->getDecl())
7508 ->isImplicitObjectMemberFunction()) &&
7509 "Only non-static member pointers can make it here");
7510
7511 // Okay: this is the address of a non-static member, and therefore
7512 // a member pointer constant.
7513 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7514 SugaredConverted = TemplateArgument(Arg);
7515 CanonicalConverted =
7516 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7517 } else {
7518 ValueDecl *D = DRE->getDecl();
7519 SugaredConverted = TemplateArgument(D, ParamType);
7520 CanonicalConverted =
7521 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7522 S.Context.getCanonicalType(ParamType));
7523 }
7524 return Invalid;
7525 }
7526
7527 // We found something else, but we don't know specifically what it is.
7528 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7529 << Arg->getSourceRange();
7530 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7531 return true;
7532}
7533
7534/// Check a template argument against its corresponding
7535/// non-type template parameter.
7536///
7537/// This routine implements the semantics of C++ [temp.arg.nontype].
7538/// If an error occurred, it returns ExprError(); otherwise, it
7539/// returns the converted template argument. \p ParamType is the
7540/// type of the non-type template parameter after it has been instantiated.
7542 QualType ParamType, Expr *Arg,
7543 TemplateArgument &SugaredConverted,
7544 TemplateArgument &CanonicalConverted,
7546 SourceLocation StartLoc = Arg->getBeginLoc();
7547
7548 // If the parameter type somehow involves auto, deduce the type now.
7549 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7550 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7551 // During template argument deduction, we allow 'decltype(auto)' to
7552 // match an arbitrary dependent argument.
7553 // FIXME: The language rules don't say what happens in this case.
7554 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7555 // expression is merely instantiation-dependent; is this enough?
7556 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7557 auto *AT = dyn_cast<AutoType>(DeducedT);
7558 if (AT && AT->isDecltypeAuto()) {
7559 SugaredConverted = TemplateArgument(Arg);
7560 CanonicalConverted = TemplateArgument(
7561 Context.getCanonicalTemplateArgument(SugaredConverted));
7562 return Arg;
7563 }
7564 }
7565
7566 // When checking a deduced template argument, deduce from its type even if
7567 // the type is dependent, in order to check the types of non-type template
7568 // arguments line up properly in partial ordering.
7569 Expr *DeductionArg = Arg;
7570 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7571 DeductionArg = PE->getPattern();
7572 TypeSourceInfo *TSI =
7573 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7574 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7575 InitializedEntity Entity =
7578 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7579 Expr *Inits[1] = {DeductionArg};
7580 ParamType =
7581 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7582 if (ParamType.isNull())
7583 return ExprError();
7584 } else {
7585 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7586 Param->getDepth() + 1);
7587 ParamType = QualType();
7589 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7590 /*DependentDeduction=*/true,
7591 // We do not check constraints right now because the
7592 // immediately-declared constraint of the auto type is
7593 // also an associated constraint, and will be checked
7594 // along with the other associated constraints after
7595 // checking the template argument list.
7596 /*IgnoreConstraints=*/true);
7598 if (ParamType.isNull())
7599 return ExprError();
7601 Diag(Arg->getExprLoc(),
7602 diag::err_non_type_template_parm_type_deduction_failure)
7603 << Param->getDeclName() << Param->getType() << Arg->getType()
7604 << Arg->getSourceRange();
7606 return ExprError();
7607 }
7608 }
7609 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7610 // an error. The error message normally references the parameter
7611 // declaration, but here we'll pass the argument location because that's
7612 // where the parameter type is deduced.
7613 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7614 if (ParamType.isNull()) {
7616 return ExprError();
7617 }
7618 }
7619
7620 // We should have already dropped all cv-qualifiers by now.
7621 assert(!ParamType.hasQualifiers() &&
7622 "non-type template parameter type cannot be qualified");
7623
7624 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7625 if (CTAK == CTAK_Deduced &&
7626 (ParamType->isReferenceType()
7628 Arg->getType())
7629 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7630 // FIXME: If either type is dependent, we skip the check. This isn't
7631 // correct, since during deduction we're supposed to have replaced each
7632 // template parameter with some unique (non-dependent) placeholder.
7633 // FIXME: If the argument type contains 'auto', we carry on and fail the
7634 // type check in order to force specific types to be more specialized than
7635 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7636 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7637 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7638 !Arg->getType()->getContainedDeducedType()) {
7639 SugaredConverted = TemplateArgument(Arg);
7640 CanonicalConverted = TemplateArgument(
7641 Context.getCanonicalTemplateArgument(SugaredConverted));
7642 return Arg;
7643 }
7644 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7645 // we should actually be checking the type of the template argument in P,
7646 // not the type of the template argument deduced from A, against the
7647 // template parameter type.
7648 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7649 << Arg->getType()
7650 << ParamType.getUnqualifiedType();
7652 return ExprError();
7653 }
7654
7655 // If either the parameter has a dependent type or the argument is
7656 // type-dependent, there's nothing we can check now.
7657 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7658 // Force the argument to the type of the parameter to maintain invariants.
7659 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7660 if (PE)
7661 Arg = PE->getPattern();
7663 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7664 ParamType->isLValueReferenceType() ? VK_LValue
7665 : ParamType->isRValueReferenceType() ? VK_XValue
7666 : VK_PRValue);
7667 if (E.isInvalid())
7668 return ExprError();
7669 if (PE) {
7670 // Recreate a pack expansion if we unwrapped one.
7671 E = new (Context)
7672 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7673 PE->getNumExpansions());
7674 }
7675 SugaredConverted = TemplateArgument(E.get());
7676 CanonicalConverted = TemplateArgument(
7677 Context.getCanonicalTemplateArgument(SugaredConverted));
7678 return E;
7679 }
7680
7681 QualType CanonParamType = Context.getCanonicalType(ParamType);
7682 // Avoid making a copy when initializing a template parameter of class type
7683 // from a template parameter object of the same type. This is going beyond
7684 // the standard, but is required for soundness: in
7685 // template<A a> struct X { X *p; X<a> *q; };
7686 // ... we need p and q to have the same type.
7687 //
7688 // Similarly, don't inject a call to a copy constructor when initializing
7689 // from a template parameter of the same type.
7690 Expr *InnerArg = Arg->IgnoreParenImpCasts();
7691 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7692 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7693 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7694 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7695
7696 SugaredConverted = TemplateArgument(TPO, ParamType);
7697 CanonicalConverted =
7698 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7699 return Arg;
7700 }
7701 if (isa<NonTypeTemplateParmDecl>(ND)) {
7702 SugaredConverted = TemplateArgument(Arg);
7703 CanonicalConverted =
7704 Context.getCanonicalTemplateArgument(SugaredConverted);
7705 return Arg;
7706 }
7707 }
7708
7709 // The initialization of the parameter from the argument is
7710 // a constant-evaluated context.
7713
7714 bool IsConvertedConstantExpression = true;
7715 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
7717 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
7718 Expr *Inits[1] = {Arg};
7719 InitializedEntity Entity =
7721 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7722 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7723 if (Result.isInvalid() || !Result.get())
7724 return ExprError();
7726 if (Result.isInvalid() || !Result.get())
7727 return ExprError();
7728 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7729 /*DiscardedValue=*/false,
7730 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
7731 .get();
7732 IsConvertedConstantExpression = false;
7733 }
7734
7735 if (getLangOpts().CPlusPlus17) {
7736 // C++17 [temp.arg.nontype]p1:
7737 // A template-argument for a non-type template parameter shall be
7738 // a converted constant expression of the type of the template-parameter.
7739 APValue Value;
7740 ExprResult ArgResult;
7741 if (IsConvertedConstantExpression) {
7742 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
7743 CCEK_TemplateArg, Param);
7744 if (ArgResult.isInvalid())
7745 return ExprError();
7746 } else {
7747 ArgResult = Arg;
7748 }
7749
7750 // For a value-dependent argument, CheckConvertedConstantExpression is
7751 // permitted (and expected) to be unable to determine a value.
7752 if (ArgResult.get()->isValueDependent()) {
7753 SugaredConverted = TemplateArgument(ArgResult.get());
7754 CanonicalConverted =
7755 Context.getCanonicalTemplateArgument(SugaredConverted);
7756 return ArgResult;
7757 }
7758
7759 APValue PreNarrowingValue;
7761 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
7762 false, PreNarrowingValue);
7763 if (ArgResult.isInvalid())
7764 return ExprError();
7765
7766 if (Value.isLValue()) {
7767 APValue::LValueBase Base = Value.getLValueBase();
7768 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7769 // For a non-type template-parameter of pointer or reference type,
7770 // the value of the constant expression shall not refer to
7771 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7772 ParamType->isNullPtrType());
7773 // -- a temporary object
7774 // -- a string literal
7775 // -- the result of a typeid expression, or
7776 // -- a predefined __func__ variable
7777 if (Base &&
7778 (!VD ||
7779 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7780 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7781 << Arg->getSourceRange();
7782 return ExprError();
7783 }
7784
7785 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7786 VD->getType()->isArrayType() &&
7787 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7788 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7789 SugaredConverted = TemplateArgument(VD, ParamType);
7790 CanonicalConverted = TemplateArgument(
7791 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
7792 return ArgResult.get();
7793 }
7794
7795 // -- a subobject [until C++20]
7796 if (!getLangOpts().CPlusPlus20) {
7797 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7798 Value.isLValueOnePastTheEnd()) {
7799 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7800 << Value.getAsString(Context, ParamType);
7801 return ExprError();
7802 }
7803 assert((VD || !ParamType->isReferenceType()) &&
7804 "null reference should not be a constant expression");
7805 assert((!VD || !ParamType->isNullPtrType()) &&
7806 "non-null value of type nullptr_t?");
7807 }
7808 }
7809
7810 if (Value.isAddrLabelDiff())
7811 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7812
7813 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7814 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
7815 return ArgResult.get();
7816 }
7817
7818 // C++ [temp.arg.nontype]p5:
7819 // The following conversions are performed on each expression used
7820 // as a non-type template-argument. If a non-type
7821 // template-argument cannot be converted to the type of the
7822 // corresponding template-parameter then the program is
7823 // ill-formed.
7824 if (ParamType->isIntegralOrEnumerationType()) {
7825 // C++11:
7826 // -- for a non-type template-parameter of integral or
7827 // enumeration type, conversions permitted in a converted
7828 // constant expression are applied.
7829 //
7830 // C++98:
7831 // -- for a non-type template-parameter of integral or
7832 // enumeration type, integral promotions (4.5) and integral
7833 // conversions (4.7) are applied.
7834
7835 if (getLangOpts().CPlusPlus11) {
7836 // C++ [temp.arg.nontype]p1:
7837 // A template-argument for a non-type, non-template template-parameter
7838 // shall be one of:
7839 //
7840 // -- for a non-type template-parameter of integral or enumeration
7841 // type, a converted constant expression of the type of the
7842 // template-parameter; or
7843 llvm::APSInt Value;
7844 ExprResult ArgResult =
7847 if (ArgResult.isInvalid())
7848 return ExprError();
7849
7850 // We can't check arbitrary value-dependent arguments.
7851 if (ArgResult.get()->isValueDependent()) {
7852 SugaredConverted = TemplateArgument(ArgResult.get());
7853 CanonicalConverted =
7854 Context.getCanonicalTemplateArgument(SugaredConverted);
7855 return ArgResult;
7856 }
7857
7858 // Widen the argument value to sizeof(parameter type). This is almost
7859 // always a no-op, except when the parameter type is bool. In
7860 // that case, this may extend the argument from 1 bit to 8 bits.
7861 QualType IntegerType = ParamType;
7862 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7863 IntegerType = Enum->getDecl()->getIntegerType();
7864 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7865 ? Context.getIntWidth(IntegerType)
7866 : Context.getTypeSize(IntegerType));
7867
7868 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7869 CanonicalConverted =
7871 return ArgResult;
7872 }
7873
7874 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7875 if (ArgResult.isInvalid())
7876 return ExprError();
7877 Arg = ArgResult.get();
7878
7879 QualType ArgType = Arg->getType();
7880
7881 // C++ [temp.arg.nontype]p1:
7882 // A template-argument for a non-type, non-template
7883 // template-parameter shall be one of:
7884 //
7885 // -- an integral constant-expression of integral or enumeration
7886 // type; or
7887 // -- the name of a non-type template-parameter; or
7888 llvm::APSInt Value;
7889 if (!ArgType->isIntegralOrEnumerationType()) {
7890 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7891 << ArgType << Arg->getSourceRange();
7893 return ExprError();
7894 } else if (!Arg->isValueDependent()) {
7895 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7896 QualType T;
7897
7898 public:
7899 TmplArgICEDiagnoser(QualType T) : T(T) { }
7900
7901 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7902 SourceLocation Loc) override {
7903 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7904 }
7905 } Diagnoser(ArgType);
7906
7907 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7908 if (!Arg)
7909 return ExprError();
7910 }
7911
7912 // From here on out, all we care about is the unqualified form
7913 // of the argument type.
7914 ArgType = ArgType.getUnqualifiedType();
7915
7916 // Try to convert the argument to the parameter's type.
7917 if (Context.hasSameType(ParamType, ArgType)) {
7918 // Okay: no conversion necessary
7919 } else if (ParamType->isBooleanType()) {
7920 // This is an integral-to-boolean conversion.
7921 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7922 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7923 !ParamType->isEnumeralType()) {
7924 // This is an integral promotion or conversion.
7925 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7926 } else {
7927 // We can't perform this conversion.
7928 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7929 << Arg->getType() << ParamType << Arg->getSourceRange();
7931 return ExprError();
7932 }
7933
7934 // Add the value of this argument to the list of converted
7935 // arguments. We use the bitwidth and signedness of the template
7936 // parameter.
7937 if (Arg->isValueDependent()) {
7938 // The argument is value-dependent. Create a new
7939 // TemplateArgument with the converted expression.
7940 SugaredConverted = TemplateArgument(Arg);
7941 CanonicalConverted =
7942 Context.getCanonicalTemplateArgument(SugaredConverted);
7943 return Arg;
7944 }
7945
7946 QualType IntegerType = ParamType;
7947 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7948 IntegerType = Enum->getDecl()->getIntegerType();
7949 }
7950
7951 if (ParamType->isBooleanType()) {
7952 // Value must be zero or one.
7953 Value = Value != 0;
7954 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7955 if (Value.getBitWidth() != AllowedBits)
7956 Value = Value.extOrTrunc(AllowedBits);
7957 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7958 } else {
7959 llvm::APSInt OldValue = Value;
7960
7961 // Coerce the template argument's value to the value it will have
7962 // based on the template parameter's type.
7963 unsigned AllowedBits = IntegerType->isBitIntType()
7964 ? Context.getIntWidth(IntegerType)
7965 : Context.getTypeSize(IntegerType);
7966 if (Value.getBitWidth() != AllowedBits)
7967 Value = Value.extOrTrunc(AllowedBits);
7968 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7969
7970 // Complain if an unsigned parameter received a negative value.
7971 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7972 (OldValue.isSigned() && OldValue.isNegative())) {
7973 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7974 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7975 << Arg->getSourceRange();
7977 }
7978
7979 // Complain if we overflowed the template parameter's type.
7980 unsigned RequiredBits;
7981 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7982 RequiredBits = OldValue.getActiveBits();
7983 else if (OldValue.isUnsigned())
7984 RequiredBits = OldValue.getActiveBits() + 1;
7985 else
7986 RequiredBits = OldValue.getSignificantBits();
7987 if (RequiredBits > AllowedBits) {
7988 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7989 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7990 << Arg->getSourceRange();
7992 }
7993 }
7994
7995 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7996 SugaredConverted = TemplateArgument(Context, Value, T);
7997 CanonicalConverted =
7999 return Arg;
8000 }
8001
8002 QualType ArgType = Arg->getType();
8003 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
8004
8005 // Handle pointer-to-function, reference-to-function, and
8006 // pointer-to-member-function all in (roughly) the same way.
8007 if (// -- For a non-type template-parameter of type pointer to
8008 // function, only the function-to-pointer conversion (4.3) is
8009 // applied. If the template-argument represents a set of
8010 // overloaded functions (or a pointer to such), the matching
8011 // function is selected from the set (13.4).
8012 (ParamType->isPointerType() &&
8013 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
8014 // -- For a non-type template-parameter of type reference to
8015 // function, no conversions apply. If the template-argument
8016 // represents a set of overloaded functions, the matching
8017 // function is selected from the set (13.4).
8018 (ParamType->isReferenceType() &&
8019 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
8020 // -- For a non-type template-parameter of type pointer to
8021 // member function, no conversions apply. If the
8022 // template-argument represents a set of overloaded member
8023 // functions, the matching member function is selected from
8024 // the set (13.4).
8025 (ParamType->isMemberPointerType() &&
8026 ParamType->castAs<MemberPointerType>()->getPointeeType()
8027 ->isFunctionType())) {
8028
8029 if (Arg->getType() == Context.OverloadTy) {
8030 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
8031 true,
8032 FoundResult)) {
8033 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
8034 return ExprError();
8035
8036 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
8037 if (Res.isInvalid())
8038 return ExprError();
8039 Arg = Res.get();
8040 ArgType = Arg->getType();
8041 } else
8042 return ExprError();
8043 }
8044
8045 if (!ParamType->isMemberPointerType()) {
8047 *this, Param, ParamType, Arg, SugaredConverted,
8048 CanonicalConverted))
8049 return ExprError();
8050 return Arg;
8051 }
8052
8054 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8055 return ExprError();
8056 return Arg;
8057 }
8058
8059 if (ParamType->isPointerType()) {
8060 // -- for a non-type template-parameter of type pointer to
8061 // object, qualification conversions (4.4) and the
8062 // array-to-pointer conversion (4.2) are applied.
8063 // C++0x also allows a value of std::nullptr_t.
8064 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
8065 "Only object pointers allowed here");
8066
8068 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8069 return ExprError();
8070 return Arg;
8071 }
8072
8073 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
8074 // -- For a non-type template-parameter of type reference to
8075 // object, no conversions apply. The type referred to by the
8076 // reference may be more cv-qualified than the (otherwise
8077 // identical) type of the template-argument. The
8078 // template-parameter is bound directly to the
8079 // template-argument, which must be an lvalue.
8080 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
8081 "Only object references allowed here");
8082
8083 if (Arg->getType() == Context.OverloadTy) {
8085 ParamRefType->getPointeeType(),
8086 true,
8087 FoundResult)) {
8088 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
8089 return ExprError();
8090 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
8091 if (Res.isInvalid())
8092 return ExprError();
8093 Arg = Res.get();
8094 ArgType = Arg->getType();
8095 } else
8096 return ExprError();
8097 }
8098
8100 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8101 return ExprError();
8102 return Arg;
8103 }
8104
8105 // Deal with parameters of type std::nullptr_t.
8106 if (ParamType->isNullPtrType()) {
8107 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
8108 SugaredConverted = TemplateArgument(Arg);
8109 CanonicalConverted =
8110 Context.getCanonicalTemplateArgument(SugaredConverted);
8111 return Arg;
8112 }
8113
8114 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
8115 case NPV_NotNullPointer:
8116 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
8117 << Arg->getType() << ParamType;
8119 return ExprError();
8120
8121 case NPV_Error:
8122 return ExprError();
8123
8124 case NPV_NullPointer:
8125 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
8126 SugaredConverted = TemplateArgument(ParamType,
8127 /*isNullPtr=*/true);
8128 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
8129 /*isNullPtr=*/true);
8130 return Arg;
8131 }
8132 }
8133
8134 // -- For a non-type template-parameter of type pointer to data
8135 // member, qualification conversions (4.4) are applied.
8136 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
8137
8139 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8140 return ExprError();
8141 return Arg;
8142}
8143
8147
8148/// Check a template argument against its corresponding
8149/// template template parameter.
8150///
8151/// This routine implements the semantics of C++ [temp.arg.template].
8152/// It returns true if an error occurred, and false otherwise.
8154 TemplateParameterList *Params,
8155 TemplateArgumentLoc &Arg) {
8157 TemplateDecl *Template = Name.getAsTemplateDecl();
8158 if (!Template) {
8159 // Any dependent template name is fine.
8160 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
8161 return false;
8162 }
8163
8164 if (Template->isInvalidDecl())
8165 return true;
8166
8167 // C++0x [temp.arg.template]p1:
8168 // A template-argument for a template template-parameter shall be
8169 // the name of a class template or an alias template, expressed as an
8170 // id-expression. When the template-argument names a class template, only
8171 // primary class templates are considered when matching the
8172 // template template argument with the corresponding parameter;
8173 // partial specializations are not considered even if their
8174 // parameter lists match that of the template template parameter.
8175 //
8176 // Note that we also allow template template parameters here, which
8177 // will happen when we are dealing with, e.g., class template
8178 // partial specializations.
8179 if (!isa<ClassTemplateDecl>(Template) &&
8180 !isa<TemplateTemplateParmDecl>(Template) &&
8181 !isa<TypeAliasTemplateDecl>(Template) &&
8182 !isa<BuiltinTemplateDecl>(Template)) {
8183 assert(isa<FunctionTemplateDecl>(Template) &&
8184 "Only function templates are possible here");
8185 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
8186 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
8187 << Template;
8188 }
8189
8190 // C++1z [temp.arg.template]p3: (DR 150)
8191 // A template-argument matches a template template-parameter P when P
8192 // is at least as specialized as the template-argument A.
8193 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
8194 // defect report resolution from C++17 and shouldn't be introduced by
8195 // concepts.
8196 if (getLangOpts().RelaxedTemplateTemplateArgs) {
8197 // Quick check for the common case:
8198 // If P contains a parameter pack, then A [...] matches P if each of A's
8199 // template parameters matches the corresponding template parameter in
8200 // the template-parameter-list of P.
8202 Template->getTemplateParameters(), Params, false,
8204 // If the argument has no associated constraints, then the parameter is
8205 // definitely at least as specialized as the argument.
8206 // Otherwise - we need a more thorough check.
8207 !Template->hasAssociatedConstraints())
8208 return false;
8209
8211 Arg.getLocation())) {
8212 // P2113
8213 // C++20[temp.func.order]p2
8214 // [...] If both deductions succeed, the partial ordering selects the
8215 // more constrained template (if one exists) as determined below.
8216 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
8217 Params->getAssociatedConstraints(ParamsAC);
8218 // C++2a[temp.arg.template]p3
8219 // [...] In this comparison, if P is unconstrained, the constraints on A
8220 // are not considered.
8221 if (ParamsAC.empty())
8222 return false;
8223
8224 Template->getAssociatedConstraints(TemplateAC);
8225
8226 bool IsParamAtLeastAsConstrained;
8227 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
8228 IsParamAtLeastAsConstrained))
8229 return true;
8230 if (!IsParamAtLeastAsConstrained) {
8231 Diag(Arg.getLocation(),
8232 diag::err_template_template_parameter_not_at_least_as_constrained)
8233 << Template << Param << Arg.getSourceRange();
8234 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
8235 Diag(Template->getLocation(), diag::note_entity_declared_at)
8236 << Template;
8237 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
8238 TemplateAC);
8239 return true;
8240 }
8241 return false;
8242 }
8243 // FIXME: Produce better diagnostics for deduction failures.
8244 }
8245
8247 Params,
8248 true,
8250 Arg.getLocation());
8251}
8252
8254 unsigned HereDiagID,
8255 unsigned ExternalDiagID) {
8256 if (Decl.getLocation().isValid())
8257 return S.Diag(Decl.getLocation(), HereDiagID);
8258
8259 SmallString<128> Str;
8260 llvm::raw_svector_ostream Out(Str);
8262 PP.TerseOutput = 1;
8263 Decl.print(Out, PP);
8264 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
8265}
8266
8268 std::optional<SourceRange> ParamRange) {
8270 noteLocation(*this, Decl, diag::note_template_decl_here,
8271 diag::note_template_decl_external);
8272 if (ParamRange && ParamRange->isValid()) {
8273 assert(Decl.getLocation().isValid() &&
8274 "Parameter range has location when Decl does not");
8275 DB << *ParamRange;
8276 }
8277}
8278
8280 noteLocation(*this, Decl, diag::note_template_param_here,
8281 diag::note_template_param_external);
8282}
8283
8284/// Given a non-type template argument that refers to a
8285/// declaration and the type of its corresponding non-type template
8286/// parameter, produce an expression that properly refers to that
8287/// declaration.
8290 QualType ParamType,
8291 SourceLocation Loc) {
8292 // C++ [temp.param]p8:
8293 //
8294 // A non-type template-parameter of type "array of T" or
8295 // "function returning T" is adjusted to be of type "pointer to
8296 // T" or "pointer to function returning T", respectively.
8297 if (ParamType->isArrayType())
8298 ParamType = Context.getArrayDecayedType(ParamType);
8299 else if (ParamType->isFunctionType())
8300 ParamType = Context.getPointerType(ParamType);
8301
8302 // For a NULL non-type template argument, return nullptr casted to the
8303 // parameter's type.
8304 if (Arg.getKind() == TemplateArgument::NullPtr) {
8305 return ImpCastExprToType(
8307 ParamType,
8308 ParamType->getAs<MemberPointerType>()
8309 ? CK_NullToMemberPointer
8310 : CK_NullToPointer);
8311 }
8312 assert(Arg.getKind() == TemplateArgument::Declaration &&
8313 "Only declaration template arguments permitted here");
8314
8315 ValueDecl *VD = Arg.getAsDecl();
8316
8317 CXXScopeSpec SS;
8318 if (ParamType->isMemberPointerType()) {
8319 // If this is a pointer to member, we need to use a qualified name to
8320 // form a suitable pointer-to-member constant.
8321 assert(VD->getDeclContext()->isRecord() &&
8322 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8323 isa<IndirectFieldDecl>(VD)));
8324 QualType ClassType
8325 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
8326 NestedNameSpecifier *Qualifier
8327 = NestedNameSpecifier::Create(Context, nullptr, false,
8328 ClassType.getTypePtr());
8329 SS.MakeTrivial(Context, Qualifier, Loc);
8330 }
8331
8333 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8334 if (RefExpr.isInvalid())
8335 return ExprError();
8336
8337 // For a pointer, the argument declaration is the pointee. Take its address.
8338 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8339 if (ParamType->isPointerType() && !ElemT.isNull() &&
8340 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8341 // Decay an array argument if we want a pointer to its first element.
8342 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8343 if (RefExpr.isInvalid())
8344 return ExprError();
8345 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8346 // For any other pointer, take the address (or form a pointer-to-member).
8347 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8348 if (RefExpr.isInvalid())
8349 return ExprError();
8350 } else if (ParamType->isRecordType()) {
8351 assert(isa<TemplateParamObjectDecl>(VD) &&
8352 "arg for class template param not a template parameter object");
8353 // No conversions apply in this case.
8354 return RefExpr;
8355 } else {
8356 assert(ParamType->isReferenceType() &&
8357 "unexpected type for decl template argument");
8358 }
8359
8360 // At this point we should have the right value category.
8361 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8362 "value kind mismatch for non-type template argument");
8363
8364 // The type of the template parameter can differ from the type of the
8365 // argument in various ways; convert it now if necessary.
8366 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8367 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8368 CastKind CK;
8369 QualType Ignored;
8370 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8371 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
8372 CK = CK_NoOp;
8373 } else if (ParamType->isVoidPointerType() &&
8374 RefExpr.get()->getType()->isPointerType()) {
8375 CK = CK_BitCast;
8376 } else {
8377 // FIXME: Pointers to members can need conversion derived-to-base or
8378 // base-to-derived conversions. We currently don't retain enough
8379 // information to convert properly (we need to track a cast path or
8380 // subobject number in the template argument).
8381 llvm_unreachable(
8382 "unexpected conversion required for non-type template argument");
8383 }
8384 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8385 RefExpr.get()->getValueKind());
8386 }
8387
8388 return RefExpr;
8389}
8390
8391/// Construct a new expression that refers to the given
8392/// integral template argument with the given source-location
8393/// information.
8394///
8395/// This routine takes care of the mapping from an integral template
8396/// argument (which may have any integral type) to the appropriate
8397/// literal value.
8399 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8400 assert(OrigT->isIntegralOrEnumerationType());
8401
8402 // If this is an enum type that we're instantiating, we need to use an integer
8403 // type the same size as the enumerator. We don't want to build an
8404 // IntegerLiteral with enum type. The integer type of an enum type can be of
8405 // any integral type with C++11 enum classes, make sure we create the right
8406 // type of literal for it.
8407 QualType T = OrigT;
8408 if (const EnumType *ET = OrigT->getAs<EnumType>())
8409 T = ET->getDecl()->getIntegerType();
8410
8411 Expr *E;
8412 if (T->isAnyCharacterType()) {
8414 if (T->isWideCharType())
8416 else if (T->isChar8Type() && S.getLangOpts().Char8)
8418 else if (T->isChar16Type())
8420 else if (T->isChar32Type())
8422 else
8424
8425 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8426 } else if (T->isBooleanType()) {
8427 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8428 } else {
8429 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8430 }
8431
8432 if (OrigT->isEnumeralType()) {
8433 // FIXME: This is a hack. We need a better way to handle substituted
8434 // non-type template parameters.
8435 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8436 nullptr, S.CurFPFeatureOverrides(),
8437 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8438 Loc, Loc);
8439 }
8440
8441 return E;
8442}
8443
8445 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8446 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8447 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8448 ILE->setType(T);
8449 return ILE;
8450 };
8451
8452 switch (Val.getKind()) {
8454 // This cannot occur in a template argument at all.
8455 case APValue::Array:
8456 case APValue::Struct:
8457 case APValue::Union:
8458 // These can only occur within a template parameter object, which is
8459 // represented as a TemplateArgument::Declaration.
8460 llvm_unreachable("unexpected template argument value");
8461
8462 case APValue::Int:
8464 Loc);
8465
8466 case APValue::Float:
8467 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8468 T, Loc);
8469
8472 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8473 Val.getFixedPoint().getScale());
8474
8475 case APValue::ComplexInt: {
8476 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8478 S, ElemT, Val.getComplexIntReal(), Loc),
8480 S, ElemT, Val.getComplexIntImag(), Loc)});
8481 }
8482
8483 case APValue::ComplexFloat: {
8484 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8485 return MakeInitList(
8487 ElemT, Loc),
8489 ElemT, Loc)});
8490 }
8491
8492 case APValue::Vector: {
8493 QualType ElemT = T->castAs<VectorType>()->getElementType();
8495 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8497 S, ElemT, Val.getVectorElt(I), Loc));
8498 return MakeInitList(Elts);
8499 }
8500
8501 case APValue::None:
8503 llvm_unreachable("Unexpected APValue kind.");
8504 case APValue::LValue:
8506 // There isn't necessarily a valid equivalent source-level syntax for
8507 // these; in particular, a naive lowering might violate access control.
8508 // So for now we lower to a ConstantExpr holding the value, wrapped around
8509 // an OpaqueValueExpr.
8510 // FIXME: We should have a better representation for this.
8512 if (T->isReferenceType()) {
8513 T = T->getPointeeType();
8514 VK = VK_LValue;
8515 }
8516 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8517 return ConstantExpr::Create(S.Context, OVE, Val);
8518 }
8519 llvm_unreachable("Unhandled APValue::ValueKind enum");
8520}
8521
8524 SourceLocation Loc) {
8525 switch (Arg.getKind()) {
8531 llvm_unreachable("not a non-type template argument");
8532
8534 return Arg.getAsExpr();
8535
8539 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8540
8543 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8544
8547 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8548 }
8549 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8550}
8551
8552/// Match two template parameters within template parameter lists.
8554 Sema &S, NamedDecl *New,
8555 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8556 const NamedDecl *OldInstFrom, bool Complain,
8558 // Check the actual kind (type, non-type, template).
8559 if (Old->getKind() != New->getKind()) {
8560 if (Complain) {
8561 unsigned NextDiag = diag::err_template_param_different_kind;
8562 if (TemplateArgLoc.isValid()) {
8563 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8564 NextDiag = diag::note_template_param_different_kind;
8565 }
8566 S.Diag(New->getLocation(), NextDiag)
8567 << (Kind != Sema::TPL_TemplateMatch);
8568 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8569 << (Kind != Sema::TPL_TemplateMatch);
8570 }
8571
8572 return false;
8573 }
8574
8575 // Check that both are parameter packs or neither are parameter packs.
8576 // However, if we are matching a template template argument to a
8577 // template template parameter, the template template parameter can have
8578 // a parameter pack where the template template argument does not.
8579 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8581 Old->isTemplateParameterPack())) {
8582 if (Complain) {
8583 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8584 if (TemplateArgLoc.isValid()) {
8585 S.Diag(TemplateArgLoc,
8586 diag::err_template_arg_template_params_mismatch);
8587 NextDiag = diag::note_template_parameter_pack_non_pack;
8588 }
8589
8590 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8591 : isa<NonTypeTemplateParmDecl>(New)? 1
8592 : 2;
8593 S.Diag(New->getLocation(), NextDiag)
8594 << ParamKind << New->isParameterPack();
8595 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8596 << ParamKind << Old->isParameterPack();
8597 }
8598
8599 return false;
8600 }
8601
8602 // For non-type template parameters, check the type of the parameter.
8603 if (NonTypeTemplateParmDecl *OldNTTP
8604 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8605 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8606
8607 // If we are matching a template template argument to a template
8608 // template parameter and one of the non-type template parameter types
8609 // is dependent, then we must wait until template instantiation time
8610 // to actually compare the arguments.
8612 (!OldNTTP->getType()->isDependentType() &&
8613 !NewNTTP->getType()->isDependentType())) {
8614 // C++20 [temp.over.link]p6:
8615 // Two [non-type] template-parameters are equivalent [if] they have
8616 // equivalent types ignoring the use of type-constraints for
8617 // placeholder types
8618 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8619 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8620 if (!S.Context.hasSameType(OldType, NewType)) {
8621 if (Complain) {
8622 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8623 if (TemplateArgLoc.isValid()) {
8624 S.Diag(TemplateArgLoc,
8625 diag::err_template_arg_template_params_mismatch);
8626 NextDiag = diag::note_template_nontype_parm_different_type;
8627 }
8628 S.Diag(NewNTTP->getLocation(), NextDiag)
8629 << NewNTTP->getType()
8630 << (Kind != Sema::TPL_TemplateMatch);
8631 S.Diag(OldNTTP->getLocation(),
8632 diag::note_template_nontype_parm_prev_declaration)
8633 << OldNTTP->getType();
8634 }
8635
8636 return false;
8637 }
8638 }
8639 }
8640 // For template template parameters, check the template parameter types.
8641 // The template parameter lists of template template
8642 // parameters must agree.
8643 else if (TemplateTemplateParmDecl *OldTTP =
8644 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8645 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8647 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8648 OldTTP->getTemplateParameters(), Complain,
8651 : Kind),
8652 TemplateArgLoc))
8653 return false;
8654 }
8655
8658 !isa<TemplateTemplateParmDecl>(Old)) {
8659 const Expr *NewC = nullptr, *OldC = nullptr;
8660
8661 if (isa<TemplateTypeParmDecl>(New)) {
8662 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8663 NewC = TC->getImmediatelyDeclaredConstraint();
8664 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8665 OldC = TC->getImmediatelyDeclaredConstraint();
8666 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8667 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8668 ->getPlaceholderTypeConstraint())
8669 NewC = E;
8670 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8671 ->getPlaceholderTypeConstraint())
8672 OldC = E;
8673 } else
8674 llvm_unreachable("unexpected template parameter type");
8675
8676 auto Diagnose = [&] {
8677 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8678 diag::err_template_different_type_constraint);
8679 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8680 diag::note_template_prev_declaration) << /*declaration*/0;
8681 };
8682
8683 if (!NewC != !OldC) {
8684 if (Complain)
8685 Diagnose();
8686 return false;
8687 }
8688
8689 if (NewC) {
8690 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8691 NewC)) {
8692 if (Complain)
8693 Diagnose();
8694 return false;
8695 }
8696 }
8697 }
8698
8699 return true;
8700}
8701
8702/// Diagnose a known arity mismatch when comparing template argument
8703/// lists.
8704static
8709 SourceLocation TemplateArgLoc) {
8710 unsigned NextDiag = diag::err_template_param_list_different_arity;
8711 if (TemplateArgLoc.isValid()) {
8712 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8713 NextDiag = diag::note_template_param_list_different_arity;
8714 }
8715 S.Diag(New->getTemplateLoc(), NextDiag)
8716 << (New->size() > Old->size())
8717 << (Kind != Sema::TPL_TemplateMatch)
8718 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8719 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8720 << (Kind != Sema::TPL_TemplateMatch)
8721 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8722}
8723
8724/// Determine whether the given template parameter lists are
8725/// equivalent.
8726///
8727/// \param New The new template parameter list, typically written in the
8728/// source code as part of a new template declaration.
8729///
8730/// \param Old The old template parameter list, typically found via
8731/// name lookup of the template declared with this template parameter
8732/// list.
8733///
8734/// \param Complain If true, this routine will produce a diagnostic if
8735/// the template parameter lists are not equivalent.
8736///
8737/// \param Kind describes how we are to match the template parameter lists.
8738///
8739/// \param TemplateArgLoc If this source location is valid, then we
8740/// are actually checking the template parameter list of a template
8741/// argument (New) against the template parameter list of its
8742/// corresponding template template parameter (Old). We produce
8743/// slightly different diagnostics in this scenario.
8744///
8745/// \returns True if the template parameter lists are equal, false
8746/// otherwise.
8748 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8749 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8750 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8751 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8752 if (Complain)
8753 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8754 TemplateArgLoc);
8755
8756 return false;
8757 }
8758
8759 // C++0x [temp.arg.template]p3:
8760 // A template-argument matches a template template-parameter (call it P)
8761 // when each of the template parameters in the template-parameter-list of
8762 // the template-argument's corresponding class template or alias template
8763 // (call it A) matches the corresponding template parameter in the
8764 // template-parameter-list of P. [...]
8765 TemplateParameterList::iterator NewParm = New->begin();
8766 TemplateParameterList::iterator NewParmEnd = New->end();
8767 for (TemplateParameterList::iterator OldParm = Old->begin(),
8768 OldParmEnd = Old->end();
8769 OldParm != OldParmEnd; ++OldParm) {
8771 !(*OldParm)->isTemplateParameterPack()) {
8772 if (NewParm == NewParmEnd) {
8773 if (Complain)
8774 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8775 TemplateArgLoc);
8776
8777 return false;
8778 }
8779
8780 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8781 OldInstFrom, Complain, Kind,
8782 TemplateArgLoc))
8783 return false;
8784
8785 ++NewParm;
8786 continue;
8787 }
8788
8789 // C++0x [temp.arg.template]p3:
8790 // [...] When P's template- parameter-list contains a template parameter
8791 // pack (14.5.3), the template parameter pack will match zero or more
8792 // template parameters or template parameter packs in the
8793 // template-parameter-list of A with the same type and form as the
8794 // template parameter pack in P (ignoring whether those template
8795 // parameters are template parameter packs).
8796 for (; NewParm != NewParmEnd; ++NewParm) {
8797 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8798 OldInstFrom, Complain, Kind,
8799 TemplateArgLoc))
8800 return false;
8801 }
8802 }
8803
8804 // Make sure we exhausted all of the arguments.
8805 if (NewParm != NewParmEnd) {
8806 if (Complain)
8807 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8808 TemplateArgLoc);
8809
8810 return false;
8811 }
8812
8815 const Expr *NewRC = New->getRequiresClause();
8816 const Expr *OldRC = Old->getRequiresClause();
8817
8818 auto Diagnose = [&] {
8819 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8820 diag::err_template_different_requires_clause);
8821 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8822 diag::note_template_prev_declaration) << /*declaration*/0;
8823 };
8824
8825 if (!NewRC != !OldRC) {
8826 if (Complain)
8827 Diagnose();
8828 return false;
8829 }
8830
8831 if (NewRC) {
8832 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8833 NewRC)) {
8834 if (Complain)
8835 Diagnose();
8836 return false;
8837 }
8838 }
8839 }
8840
8841 return true;
8842}
8843
8844/// Check whether a template can be declared within this scope.
8845///
8846/// If the template declaration is valid in this scope, returns
8847/// false. Otherwise, issues a diagnostic and returns true.
8848bool
8850 if (!S)
8851 return false;
8852
8853 // Find the nearest enclosing declaration scope.
8854 S = S->getDeclParent();
8855
8856 // C++ [temp.pre]p6: [P2096]
8857 // A template, explicit specialization, or partial specialization shall not
8858 // have C linkage.
8859 DeclContext *Ctx = S->getEntity();
8860 if (Ctx && Ctx->isExternCContext()) {
8861 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8862 << TemplateParams->getSourceRange();
8863 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8864 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8865 return true;
8866 }
8867 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8868
8869 // C++ [temp]p2:
8870 // A template-declaration can appear only as a namespace scope or
8871 // class scope declaration.
8872 // C++ [temp.expl.spec]p3:
8873 // An explicit specialization may be declared in any scope in which the
8874 // corresponding primary template may be defined.
8875 // C++ [temp.class.spec]p6: [P2096]
8876 // A partial specialization may be declared in any scope in which the
8877 // corresponding primary template may be defined.
8878 if (Ctx) {
8879 if (Ctx->isFileContext())
8880 return false;
8881 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8882 // C++ [temp.mem]p2:
8883 // A local class shall not have member templates.
8884 if (RD->isLocalClass())
8885 return Diag(TemplateParams->getTemplateLoc(),
8886 diag::err_template_inside_local_class)
8887 << TemplateParams->getSourceRange();
8888 else
8889 return false;
8890 }
8891 }
8892
8893 return Diag(TemplateParams->getTemplateLoc(),
8894 diag::err_template_outside_namespace_or_class_scope)
8895 << TemplateParams->getSourceRange();
8896}
8897
8898/// Determine what kind of template specialization the given declaration
8899/// is.
8901 if (!D)
8902 return TSK_Undeclared;
8903
8904 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8905 return Record->getTemplateSpecializationKind();
8906 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8907 return Function->getTemplateSpecializationKind();
8908 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8909 return Var->getTemplateSpecializationKind();
8910
8911 return TSK_Undeclared;
8912}
8913
8914/// Check whether a specialization is well-formed in the current
8915/// context.
8916///
8917/// This routine determines whether a template specialization can be declared
8918/// in the current context (C++ [temp.expl.spec]p2).
8919///
8920/// \param S the semantic analysis object for which this check is being
8921/// performed.
8922///
8923/// \param Specialized the entity being specialized or instantiated, which
8924/// may be a kind of template (class template, function template, etc.) or
8925/// a member of a class template (member function, static data member,
8926/// member class).
8927///
8928/// \param PrevDecl the previous declaration of this entity, if any.
8929///
8930/// \param Loc the location of the explicit specialization or instantiation of
8931/// this entity.
8932///
8933/// \param IsPartialSpecialization whether this is a partial specialization of
8934/// a class template.
8935///
8936/// \returns true if there was an error that we cannot recover from, false
8937/// otherwise.
8939 NamedDecl *Specialized,
8940 NamedDecl *PrevDecl,
8941 SourceLocation Loc,
8943 // Keep these "kind" numbers in sync with the %select statements in the
8944 // various diagnostics emitted by this routine.
8945 int EntityKind = 0;
8946 if (isa<ClassTemplateDecl>(Specialized))
8947 EntityKind = IsPartialSpecialization? 1 : 0;
8948 else if (isa<VarTemplateDecl>(Specialized))
8949 EntityKind = IsPartialSpecialization ? 3 : 2;
8950 else if (isa<FunctionTemplateDecl>(Specialized))
8951 EntityKind = 4;
8952 else if (isa<CXXMethodDecl>(Specialized))
8953 EntityKind = 5;
8954 else if (isa<VarDecl>(Specialized))
8955 EntityKind = 6;
8956 else if (isa<RecordDecl>(Specialized))
8957 EntityKind = 7;
8958 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8959 EntityKind = 8;
8960 else {
8961 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8962 << S.getLangOpts().CPlusPlus11;
8963 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8964 return true;
8965 }
8966
8967 // C++ [temp.expl.spec]p2:
8968 // An explicit specialization may be declared in any scope in which
8969 // the corresponding primary template may be defined.
8971 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8972 << Specialized;
8973 return true;
8974 }
8975
8976 // C++ [temp.class.spec]p6:
8977 // A class template partial specialization may be declared in any
8978 // scope in which the primary template may be defined.
8979 DeclContext *SpecializedContext =
8980 Specialized->getDeclContext()->getRedeclContext();
8982
8983 // Make sure that this redeclaration (or definition) occurs in the same
8984 // scope or an enclosing namespace.
8985 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8986 : DC->Equals(SpecializedContext))) {
8987 if (isa<TranslationUnitDecl>(SpecializedContext))
8988 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8989 << EntityKind << Specialized;
8990 else {
8991 auto *ND = cast<NamedDecl>(SpecializedContext);
8992 int Diag = diag::err_template_spec_redecl_out_of_scope;
8993 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8994 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8995 S.Diag(Loc, Diag) << EntityKind << Specialized
8996 << ND << isa<CXXRecordDecl>(ND);
8997 }
8998
8999 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9000
9001 // Don't allow specializing in the wrong class during error recovery.
9002 // Otherwise, things can go horribly wrong.
9003 if (DC->isRecord())
9004 return true;
9005 }
9006
9007 return false;
9008}
9009
9011 if (!E->isTypeDependent())
9012 return SourceLocation();
9013 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9014 Checker.TraverseStmt(E);
9015 if (Checker.MatchLoc.isInvalid())
9016 return E->getSourceRange();
9017 return Checker.MatchLoc;
9018}
9019
9020static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
9021 if (!TL.getType()->isDependentType())
9022 return SourceLocation();
9023 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9024 Checker.TraverseTypeLoc(TL);
9025 if (Checker.MatchLoc.isInvalid())
9026 return TL.getSourceRange();
9027 return Checker.MatchLoc;
9028}
9029
9030/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
9031/// that checks non-type template partial specialization arguments.
9033 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
9034 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
9035 for (unsigned I = 0; I != NumArgs; ++I) {
9036 if (Args[I].getKind() == TemplateArgument::Pack) {
9038 S, TemplateNameLoc, Param, Args[I].pack_begin(),
9039 Args[I].pack_size(), IsDefaultArgument))
9040 return true;
9041
9042 continue;
9043 }
9044
9045 if (Args[I].getKind() != TemplateArgument::Expression)
9046 continue;
9047
9048 Expr *ArgExpr = Args[I].getAsExpr();
9049
9050 // We can have a pack expansion of any of the bullets below.
9051 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
9052 ArgExpr = Expansion->getPattern();
9053
9054 // Strip off any implicit casts we added as part of type checking.
9055 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9056 ArgExpr = ICE->getSubExpr();
9057
9058 // C++ [temp.class.spec]p8:
9059 // A non-type argument is non-specialized if it is the name of a
9060 // non-type parameter. All other non-type arguments are
9061 // specialized.
9062 //
9063 // Below, we check the two conditions that only apply to
9064 // specialized non-type arguments, so skip any non-specialized
9065 // arguments.
9066 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
9067 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
9068 continue;
9069
9070 // C++ [temp.class.spec]p9:
9071 // Within the argument list of a class template partial
9072 // specialization, the following restrictions apply:
9073 // -- A partially specialized non-type argument expression
9074 // shall not involve a template parameter of the partial
9075 // specialization except when the argument expression is a
9076 // simple identifier.
9077 // -- The type of a template parameter corresponding to a
9078 // specialized non-type argument shall not be dependent on a
9079 // parameter of the specialization.
9080 // DR1315 removes the first bullet, leaving an incoherent set of rules.
9081 // We implement a compromise between the original rules and DR1315:
9082 // -- A specialized non-type template argument shall not be
9083 // type-dependent and the corresponding template parameter
9084 // shall have a non-dependent type.
9085 SourceRange ParamUseRange =
9086 findTemplateParameterInType(Param->getDepth(), ArgExpr);
9087 if (ParamUseRange.isValid()) {
9088 if (IsDefaultArgument) {
9089 S.Diag(TemplateNameLoc,
9090 diag::err_dependent_non_type_arg_in_partial_spec);
9091 S.Diag(ParamUseRange.getBegin(),
9092 diag::note_dependent_non_type_default_arg_in_partial_spec)
9093 << ParamUseRange;
9094 } else {
9095 S.Diag(ParamUseRange.getBegin(),
9096 diag::err_dependent_non_type_arg_in_partial_spec)
9097 << ParamUseRange;
9098 }
9099 return true;
9100 }
9101
9102 ParamUseRange = findTemplateParameter(
9103 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
9104 if (ParamUseRange.isValid()) {
9105 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
9106 diag::err_dependent_typed_non_type_arg_in_partial_spec)
9107 << Param->getType();
9109 return true;
9110 }
9111 }
9112
9113 return false;
9114}
9115
9116/// Check the non-type template arguments of a class template
9117/// partial specialization according to C++ [temp.class.spec]p9.
9118///
9119/// \param TemplateNameLoc the location of the template name.
9120/// \param PrimaryTemplate the template parameters of the primary class
9121/// template.
9122/// \param NumExplicit the number of explicitly-specified template arguments.
9123/// \param TemplateArgs the template arguments of the class template
9124/// partial specialization.
9125///
9126/// \returns \c true if there was an error, \c false otherwise.
9128 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
9129 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
9130 // We have to be conservative when checking a template in a dependent
9131 // context.
9132 if (PrimaryTemplate->getDeclContext()->isDependentContext())
9133 return false;
9134
9135 TemplateParameterList *TemplateParams =
9136 PrimaryTemplate->getTemplateParameters();
9137 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9139 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
9140 if (!Param)
9141 continue;
9142
9143 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
9144 Param, &TemplateArgs[I],
9145 1, I >= NumExplicit))
9146 return true;
9147 }
9148
9149 return false;
9150}
9151
9153 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
9154 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
9156 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
9157 assert(TUK != TUK_Reference && "References are not specializations");
9158
9159 // NOTE: KWLoc is the location of the tag keyword. This will instead
9160 // store the location of the outermost template keyword in the declaration.
9161 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
9162 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
9163 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
9164 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
9165 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
9166
9167 // Find the class template we're specializing
9168 TemplateName Name = TemplateId.Template.get();
9170 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
9171
9172 if (!ClassTemplate) {
9173 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
9174 << (Name.getAsTemplateDecl() &&
9175 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
9176 return true;
9177 }
9178
9179 bool isMemberSpecialization = false;
9180 bool isPartialSpecialization = false;
9181
9182 if (SS.isSet()) {
9183 if (TUK != TUK_Reference && TUK != TUK_Friend &&
9184 diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
9185 ClassTemplate->getDeclName(),
9186 TemplateNameLoc, &TemplateId,
9187 /*IsMemberSpecialization=*/false))
9188 return true;
9189 }
9190
9191 // Check the validity of the template headers that introduce this
9192 // template.
9193 // FIXME: We probably shouldn't complain about these headers for
9194 // friend declarations.
9195 bool Invalid = false;
9196 TemplateParameterList *TemplateParams =
9198 KWLoc, TemplateNameLoc, SS, &TemplateId,
9199 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
9200 Invalid);
9201 if (Invalid)
9202 return true;
9203
9204 // Check that we can declare a template specialization here.
9205 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
9206 return true;
9207
9208 if (TemplateParams && TemplateParams->size() > 0) {
9209 isPartialSpecialization = true;
9210
9211 if (TUK == TUK_Friend) {
9212 Diag(KWLoc, diag::err_partial_specialization_friend)
9213 << SourceRange(LAngleLoc, RAngleLoc);
9214 return true;
9215 }
9216
9217 // C++ [temp.class.spec]p10:
9218 // The template parameter list of a specialization shall not
9219 // contain default template argument values.
9220 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9221 Decl *Param = TemplateParams->getParam(I);
9222 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
9223 if (TTP->hasDefaultArgument()) {
9224 Diag(TTP->getDefaultArgumentLoc(),
9225 diag::err_default_arg_in_partial_spec);
9226 TTP->removeDefaultArgument();
9227 }
9228 } else if (NonTypeTemplateParmDecl *NTTP
9229 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
9230 if (Expr *DefArg = NTTP->getDefaultArgument()) {
9231 Diag(NTTP->getDefaultArgumentLoc(),
9232 diag::err_default_arg_in_partial_spec)
9233 << DefArg->getSourceRange();
9234 NTTP->removeDefaultArgument();
9235 }
9236 } else {
9237 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
9238 if (TTP->hasDefaultArgument()) {
9240 diag::err_default_arg_in_partial_spec)
9242 TTP->removeDefaultArgument();
9243 }
9244 }
9245 }
9246 } else if (TemplateParams) {
9247 if (TUK == TUK_Friend)
9248 Diag(KWLoc, diag::err_template_spec_friend)
9250 SourceRange(TemplateParams->getTemplateLoc(),
9251 TemplateParams->getRAngleLoc()))
9252 << SourceRange(LAngleLoc, RAngleLoc);
9253 } else {
9254 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
9255 }
9256
9257 // Check that the specialization uses the same tag kind as the
9258 // original template.
9260 assert(Kind != TagTypeKind::Enum &&
9261 "Invalid enum tag in class template spec!");
9262 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9263 Kind, TUK == TUK_Definition, KWLoc,
9264 ClassTemplate->getIdentifier())) {
9265 Diag(KWLoc, diag::err_use_with_wrong_tag)
9266 << ClassTemplate
9268 ClassTemplate->getTemplatedDecl()->getKindName());
9269 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9270 diag::note_previous_use);
9271 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9272 }
9273
9274 // Translate the parser's template argument list in our AST format.
9275 TemplateArgumentListInfo TemplateArgs =
9276 makeTemplateArgumentListInfo(*this, TemplateId);
9277
9278 // Check for unexpanded parameter packs in any of the template arguments.
9279 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9280 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
9281 isPartialSpecialization
9284 return true;
9285
9286 // Check that the template argument list is well-formed for this
9287 // template.
9288 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9289 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9290 false, SugaredConverted, CanonicalConverted,
9291 /*UpdateArgsWithConversions=*/true))
9292 return true;
9293
9294 // Find the class template (partial) specialization declaration that
9295 // corresponds to these arguments.
9296 if (isPartialSpecialization) {
9298 TemplateArgs.size(),
9299 CanonicalConverted))
9300 return true;
9301
9302 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9303 // also do it during instantiation.
9304 if (!Name.isDependent() &&
9306 TemplateArgs, CanonicalConverted)) {
9307 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9308 << ClassTemplate->getDeclName();
9309 isPartialSpecialization = false;
9310 }
9311 }
9312
9313 void *InsertPos = nullptr;
9314 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9315
9316 if (isPartialSpecialization)
9317 PrevDecl = ClassTemplate->findPartialSpecialization(
9318 CanonicalConverted, TemplateParams, InsertPos);
9319 else
9320 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9321
9323
9324 // Check whether we can declare a class template specialization in
9325 // the current scope.
9326 if (TUK != TUK_Friend &&
9328 TemplateNameLoc,
9329 isPartialSpecialization))
9330 return true;
9331
9332 // The canonical type
9333 QualType CanonType;
9334 if (isPartialSpecialization) {
9335 // Build the canonical type that describes the converted template
9336 // arguments of the class template partial specialization.
9337 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9338 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9339 CanonicalConverted);
9340
9341 if (Context.hasSameType(CanonType,
9342 ClassTemplate->getInjectedClassNameSpecialization()) &&
9343 (!Context.getLangOpts().CPlusPlus20 ||
9344 !TemplateParams->hasAssociatedConstraints())) {
9345 // C++ [temp.class.spec]p9b3:
9346 //
9347 // -- The argument list of the specialization shall not be identical
9348 // to the implicit argument list of the primary template.
9349 //
9350 // This rule has since been removed, because it's redundant given DR1495,
9351 // but we keep it because it produces better diagnostics and recovery.
9352 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9353 << /*class template*/0 << (TUK == TUK_Definition)
9354 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9355 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
9356 ClassTemplate->getIdentifier(),
9357 TemplateNameLoc,
9358 Attr,
9359 TemplateParams,
9360 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9361 /*FriendLoc*/SourceLocation(),
9362 TemplateParameterLists.size() - 1,
9363 TemplateParameterLists.data());
9364 }
9365
9366 // Create a new class template partial specialization declaration node.
9368 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9371 Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
9372 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
9373 TemplateArgs, CanonType, PrevPartial);
9374 SetNestedNameSpecifier(*this, Partial, SS);
9375 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9377 Context, TemplateParameterLists.drop_back(1));
9378 }
9379
9380 if (!PrevPartial)
9381 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9382 Specialization = Partial;
9383
9384 // If we are providing an explicit specialization of a member class
9385 // template specialization, make a note of that.
9386 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9387 PrevPartial->setMemberSpecialization();
9388
9390 } else {
9391 // Create a new class template specialization declaration node for
9392 // this explicit specialization or friend declaration.
9394 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9395 ClassTemplate, CanonicalConverted, PrevDecl);
9397 if (TemplateParameterLists.size() > 0) {
9398 Specialization->setTemplateParameterListsInfo(Context,
9399 TemplateParameterLists);
9400 }
9401
9402 if (!PrevDecl)
9403 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9404
9406 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9407 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9408 CanonicalConverted);
9409 } else {
9411 }
9412 }
9413
9414 // C++ [temp.expl.spec]p6:
9415 // If a template, a member template or the member of a class template is
9416 // explicitly specialized then that specialization shall be declared
9417 // before the first use of that specialization that would cause an implicit
9418 // instantiation to take place, in every translation unit in which such a
9419 // use occurs; no diagnostic is required.
9420 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9421 bool Okay = false;
9422 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9423 // Is there any previous explicit specialization declaration?
9425 Okay = true;
9426 break;
9427 }
9428 }
9429
9430 if (!Okay) {
9431 SourceRange Range(TemplateNameLoc, RAngleLoc);
9432 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9434
9435 Diag(PrevDecl->getPointOfInstantiation(),
9436 diag::note_instantiation_required_here)
9437 << (PrevDecl->getTemplateSpecializationKind()
9439 return true;
9440 }
9441 }
9442
9443 // If this is not a friend, note that this is an explicit specialization.
9444 if (TUK != TUK_Friend)
9445 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9446
9447 // Check that this isn't a redefinition of this specialization.
9448 if (TUK == TUK_Definition) {
9449 RecordDecl *Def = Specialization->getDefinition();
9450 NamedDecl *Hidden = nullptr;
9451 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
9452 SkipBody->ShouldSkip = true;
9453 SkipBody->Previous = Def;
9455 } else if (Def) {
9456 SourceRange Range(TemplateNameLoc, RAngleLoc);
9457 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9458 Diag(Def->getLocation(), diag::note_previous_definition);
9459 Specialization->setInvalidDecl();
9460 return true;
9461 }
9462 }
9463
9466
9467 // Add alignment attributes if necessary; these attributes are checked when
9468 // the ASTContext lays out the structure.
9469 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9472 }
9473
9474 if (ModulePrivateLoc.isValid())
9475 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9476 << (isPartialSpecialization? 1 : 0)
9477 << FixItHint::CreateRemoval(ModulePrivateLoc);
9478
9479 // Build the fully-sugared type for this class template
9480 // specialization as the user wrote in the specialization
9481 // itself. This means that we'll pretty-print the type retrieved
9482 // from the specialization's declaration the way that the user
9483 // actually wrote the specialization, rather than formatting the
9484 // name based on the "canonical" representation used to store the
9485 // template arguments in the specialization.
9486 TypeSourceInfo *WrittenTy
9487 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9488 TemplateArgs, CanonType);
9489 if (TUK != TUK_Friend) {
9490 Specialization->setTypeAsWritten(WrittenTy);
9491 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
9492 }
9493
9494 // C++ [temp.expl.spec]p9:
9495 // A template explicit specialization is in the scope of the
9496 // namespace in which the template was defined.
9497 //
9498 // We actually implement this paragraph where we set the semantic
9499 // context (in the creation of the ClassTemplateSpecializationDecl),
9500 // but we also maintain the lexical context where the actual
9501 // definition occurs.
9502 Specialization->setLexicalDeclContext(CurContext);
9503
9504 // We may be starting the definition of this specialization.
9505 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
9506 Specialization->startDefinition();
9507
9508 if (TUK == TUK_Friend) {
9510 TemplateNameLoc,
9511 WrittenTy,
9512 /*FIXME:*/KWLoc);
9513 Friend->setAccess(AS_public);
9514 CurContext->addDecl(Friend);
9515 } else {
9516 // Add the specialization into its lexical context, so that it can
9517 // be seen when iterating through the list of declarations in that
9518 // context. However, specializations are not found by name lookup.
9520 }
9521
9522 if (SkipBody && SkipBody->ShouldSkip)
9523 return SkipBody->Previous;
9524
9525 return Specialization;
9526}
9527
9529 MultiTemplateParamsArg TemplateParameterLists,
9530 Declarator &D) {
9531 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9532 ActOnDocumentableDecl(NewDecl);
9533 return NewDecl;
9534}
9535
9537 MultiTemplateParamsArg TemplateParameterLists,
9538 IdentifierInfo *Name, SourceLocation NameLoc,
9539 Expr *ConstraintExpr) {
9540 DeclContext *DC = CurContext;
9541
9542 if (!DC->getRedeclContext()->isFileContext()) {
9543 Diag(NameLoc,
9544 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9545 return nullptr;
9546 }
9547
9548 if (TemplateParameterLists.size() > 1) {
9549 Diag(NameLoc, diag::err_concept_extra_headers);
9550 return nullptr;
9551 }
9552
9553 TemplateParameterList *Params = TemplateParameterLists.front();
9554
9555 if (Params->size() == 0) {
9556 Diag(NameLoc, diag::err_concept_no_parameters);
9557 return nullptr;
9558 }
9559
9560 // Ensure that the parameter pack, if present, is the last parameter in the
9561 // template.
9562 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9563 ParamEnd = Params->end();
9564 ParamIt != ParamEnd; ++ParamIt) {
9565 Decl const *Param = *ParamIt;
9566 if (Param->isParameterPack()) {
9567 if (++ParamIt == ParamEnd)
9568 break;
9569 Diag(Param->getLocation(),
9570 diag::err_template_param_pack_must_be_last_template_parameter);
9571 return nullptr;
9572 }
9573 }
9574
9575 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
9576 return nullptr;
9577
9578 ConceptDecl *NewDecl =
9579 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
9580
9581 if (NewDecl->hasAssociatedConstraints()) {
9582 // C++2a [temp.concept]p4:
9583 // A concept shall not have associated constraints.
9584 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9585 NewDecl->setInvalidDecl();
9586 }
9587
9588 // Check for conflicting previous declaration.
9589 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9590 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9592 LookupName(Previous, S);
9593 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
9594 /*AllowInlineNamespace*/false);
9595 bool AddToScope = true;
9596 CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9597
9598 ActOnDocumentableDecl(NewDecl);
9599 if (AddToScope)
9600 PushOnScopeChains(NewDecl, S);
9601 return NewDecl;
9602}
9603
9605 LookupResult &Previous, bool &AddToScope) {
9606 AddToScope = true;
9607
9608 if (Previous.empty())
9609 return;
9610
9611 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9612 if (!OldConcept) {
9613 auto *Old = Previous.getRepresentativeDecl();
9614 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9615 << NewDecl->getDeclName();
9616 notePreviousDefinition(Old, NewDecl->getLocation());
9617 AddToScope = false;
9618 return;
9619 }
9620 // Check if we can merge with a concept declaration.
9621 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9622 if (!IsSame) {
9623 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9624 << NewDecl->getDeclName();
9625 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9626 AddToScope = false;
9627 return;
9628 }
9629 if (hasReachableDefinition(OldConcept) &&
9630 IsRedefinitionInModule(NewDecl, OldConcept)) {
9631 Diag(NewDecl->getLocation(), diag::err_redefinition)
9632 << NewDecl->getDeclName();
9633 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9634 AddToScope = false;
9635 return;
9636 }
9637 if (!Previous.isSingleResult()) {
9638 // FIXME: we should produce an error in case of ambig and failed lookups.
9639 // Other decls (e.g. namespaces) also have this shortcoming.
9640 return;
9641 }
9642 // We unwrap canonical decl late to check for module visibility.
9643 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9644}
9645
9646/// \brief Strips various properties off an implicit instantiation
9647/// that has just been explicitly specialized.
9648static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9649 if (MinGW || (isa<FunctionDecl>(D) &&
9650 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9651 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9652
9653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9654 FD->setInlineSpecified(false);
9655}
9656
9657/// Compute the diagnostic location for an explicit instantiation
9658// declaration or definition.
9660 NamedDecl* D, SourceLocation PointOfInstantiation) {
9661 // Explicit instantiations following a specialization have no effect and
9662 // hence no PointOfInstantiation. In that case, walk decl backwards
9663 // until a valid name loc is found.
9664 SourceLocation PrevDiagLoc = PointOfInstantiation;
9665 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9666 Prev = Prev->getPreviousDecl()) {
9667 PrevDiagLoc = Prev->getLocation();
9668 }
9669 assert(PrevDiagLoc.isValid() &&
9670 "Explicit instantiation without point of instantiation?");
9671 return PrevDiagLoc;
9672}
9673
9674/// Diagnose cases where we have an explicit template specialization
9675/// before/after an explicit template instantiation, producing diagnostics
9676/// for those cases where they are required and determining whether the
9677/// new specialization/instantiation will have any effect.
9678///
9679/// \param NewLoc the location of the new explicit specialization or
9680/// instantiation.
9681///
9682/// \param NewTSK the kind of the new explicit specialization or instantiation.
9683///
9684/// \param PrevDecl the previous declaration of the entity.
9685///
9686/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9687///
9688/// \param PrevPointOfInstantiation if valid, indicates where the previous
9689/// declaration was instantiated (either implicitly or explicitly).
9690///
9691/// \param HasNoEffect will be set to true to indicate that the new
9692/// specialization or instantiation has no effect and should be ignored.
9693///
9694/// \returns true if there was an error that should prevent the introduction of
9695/// the new declaration into the AST, false otherwise.
9696bool
9699 NamedDecl *PrevDecl,
9701 SourceLocation PrevPointOfInstantiation,
9702 bool &HasNoEffect) {
9703 HasNoEffect = false;
9704
9705 switch (NewTSK) {
9706 case TSK_Undeclared:
9708 assert(
9709 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9710 "previous declaration must be implicit!");
9711 return false;
9712
9714 switch (PrevTSK) {
9715 case TSK_Undeclared:
9717 // Okay, we're just specializing something that is either already
9718 // explicitly specialized or has merely been mentioned without any
9719 // instantiation.
9720 return false;
9721
9723 if (PrevPointOfInstantiation.isInvalid()) {
9724 // The declaration itself has not actually been instantiated, so it is
9725 // still okay to specialize it.
9727 PrevDecl,
9728 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9729 return false;
9730 }
9731 // Fall through
9732 [[fallthrough]];
9733
9736 assert((PrevTSK == TSK_ImplicitInstantiation ||
9737 PrevPointOfInstantiation.isValid()) &&
9738 "Explicit instantiation without point of instantiation?");
9739
9740 // C++ [temp.expl.spec]p6:
9741 // If a template, a member template or the member of a class template
9742 // is explicitly specialized then that specialization shall be declared
9743 // before the first use of that specialization that would cause an
9744 // implicit instantiation to take place, in every translation unit in
9745 // which such a use occurs; no diagnostic is required.
9746 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9747 // Is there any previous explicit specialization declaration?
9749 return false;
9750 }
9751
9752 Diag(NewLoc, diag::err_specialization_after_instantiation)
9753 << PrevDecl;
9754 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9755 << (PrevTSK != TSK_ImplicitInstantiation);
9756
9757 return true;
9758 }
9759 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9760
9762 switch (PrevTSK) {
9764 // This explicit instantiation declaration is redundant (that's okay).
9765 HasNoEffect = true;
9766 return false;
9767
9768 case TSK_Undeclared:
9770 // We're explicitly instantiating something that may have already been
9771 // implicitly instantiated; that's fine.
9772 return false;
9773
9775 // C++0x [temp.explicit]p4:
9776 // For a given set of template parameters, if an explicit instantiation
9777 // of a template appears after a declaration of an explicit
9778 // specialization for that template, the explicit instantiation has no
9779 // effect.
9780 HasNoEffect = true;
9781 return false;
9782
9784 // C++0x [temp.explicit]p10:
9785 // If an entity is the subject of both an explicit instantiation
9786 // declaration and an explicit instantiation definition in the same
9787 // translation unit, the definition shall follow the declaration.
9788 Diag(NewLoc,
9789 diag::err_explicit_instantiation_declaration_after_definition);
9790
9791 // Explicit instantiations following a specialization have no effect and
9792 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9793 // until a valid name loc is found.
9794 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9795 diag::note_explicit_instantiation_definition_here);
9796 HasNoEffect = true;
9797 return false;
9798 }
9799 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9800
9802 switch (PrevTSK) {
9803 case TSK_Undeclared:
9805 // We're explicitly instantiating something that may have already been
9806 // implicitly instantiated; that's fine.
9807 return false;
9808
9810 // C++ DR 259, C++0x [temp.explicit]p4:
9811 // For a given set of template parameters, if an explicit
9812 // instantiation of a template appears after a declaration of
9813 // an explicit specialization for that template, the explicit
9814 // instantiation has no effect.
9815 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9816 << PrevDecl;
9817 Diag(PrevDecl->getLocation(),
9818 diag::note_previous_template_specialization);
9819 HasNoEffect = true;
9820 return false;
9821
9823 // We're explicitly instantiating a definition for something for which we
9824 // were previously asked to suppress instantiations. That's fine.
9825
9826 // C++0x [temp.explicit]p4:
9827 // For a given set of template parameters, if an explicit instantiation
9828 // of a template appears after a declaration of an explicit
9829 // specialization for that template, the explicit instantiation has no
9830 // effect.
9831 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9832 // Is there any previous explicit specialization declaration?
9834 HasNoEffect = true;
9835 break;
9836 }
9837 }
9838
9839 return false;
9840
9842 // C++0x [temp.spec]p5:
9843 // For a given template and a given set of template-arguments,
9844 // - an explicit instantiation definition shall appear at most once
9845 // in a program,
9846
9847 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9848 Diag(NewLoc, (getLangOpts().MSVCCompat)
9849 ? diag::ext_explicit_instantiation_duplicate
9850 : diag::err_explicit_instantiation_duplicate)
9851 << PrevDecl;
9852 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9853 diag::note_previous_explicit_instantiation);
9854 HasNoEffect = true;
9855 return false;
9856 }
9857 }
9858
9859 llvm_unreachable("Missing specialization/instantiation case?");
9860}
9861
9862/// Perform semantic analysis for the given dependent function
9863/// template specialization.
9864///
9865/// The only possible way to get a dependent function template specialization
9866/// is with a friend declaration, like so:
9867///
9868/// \code
9869/// template <class T> void foo(T);
9870/// template <class T> class A {
9871/// friend void foo<>(T);
9872/// };
9873/// \endcode
9874///
9875/// There really isn't any useful analysis we can do here, so we
9876/// just store the information.
9878 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9880 // Remove anything from Previous that isn't a function template in
9881 // the correct context.
9882 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9883 LookupResult::Filter F = Previous.makeFilter();
9884 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9885 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9886 while (F.hasNext()) {
9887 NamedDecl *D = F.next()->getUnderlyingDecl();
9888 if (!isa<FunctionTemplateDecl>(D)) {
9889 F.erase();
9890 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9891 continue;
9892 }
9893
9894 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9896 F.erase();
9897 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9898 continue;
9899 }
9900 }
9901 F.done();
9902
9903 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9904 if (Previous.empty()) {
9905 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9906 << IsFriend;
9907 for (auto &P : DiscardedCandidates)
9908 Diag(P.second->getLocation(),
9909 diag::note_dependent_function_template_spec_discard_reason)
9910 << P.first << IsFriend;
9911 return true;
9912 }
9913
9915 ExplicitTemplateArgs);
9916 return false;
9917}
9918
9919/// Perform semantic analysis for the given function template
9920/// specialization.
9921///
9922/// This routine performs all of the semantic analysis required for an
9923/// explicit function template specialization. On successful completion,
9924/// the function declaration \p FD will become a function template
9925/// specialization.
9926///
9927/// \param FD the function declaration, which will be updated to become a
9928/// function template specialization.
9929///
9930/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
9931/// if any. Note that this may be valid info even when 0 arguments are
9932/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
9933/// as it anyway contains info on the angle brackets locations.
9934///
9935/// \param Previous the set of declarations that may be specialized by
9936/// this function specialization.
9937///
9938/// \param QualifiedFriend whether this is a lookup for a qualified friend
9939/// declaration with no explicit template argument list that might be
9940/// befriending a function template specialization.
9942 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9943 LookupResult &Previous, bool QualifiedFriend) {
9944 // The set of function template specializations that could match this
9945 // explicit function template specialization.
9946 UnresolvedSet<8> Candidates;
9947 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9948 /*ForTakingAddress=*/false);
9949
9950 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9951 ConvertedTemplateArgs;
9952
9953 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9954 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9955 I != E; ++I) {
9956 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9957 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9958 // Only consider templates found within the same semantic lookup scope as
9959 // FD.
9960 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9962 continue;
9963
9964 // When matching a constexpr member function template specialization
9965 // against the primary template, we don't yet know whether the
9966 // specialization has an implicit 'const' (because we don't know whether
9967 // it will be a static member function until we know which template it
9968 // specializes), so adjust it now assuming it specializes this template.
9969 QualType FT = FD->getType();
9970 if (FD->isConstexpr()) {
9971 CXXMethodDecl *OldMD =
9972 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9973 if (OldMD && OldMD->isConst()) {
9974 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9976 EPI.TypeQuals.addConst();
9978 FPT->getParamTypes(), EPI);
9979 }
9980 }
9981
9983 if (ExplicitTemplateArgs)
9984 Args = *ExplicitTemplateArgs;
9985
9986 // C++ [temp.expl.spec]p11:
9987 // A trailing template-argument can be left unspecified in the
9988 // template-id naming an explicit function template specialization
9989 // provided it can be deduced from the function argument type.
9990 // Perform template argument deduction to determine whether we may be
9991 // specializing this template.
9992 // FIXME: It is somewhat wasteful to build
9993 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9994 FunctionDecl *Specialization = nullptr;
9996 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9997 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9999 // Template argument deduction failed; record why it failed, so
10000 // that we can provide nifty diagnostics.
10001 FailedCandidates.addCandidate().set(
10002 I.getPair(), FunTmpl->getTemplatedDecl(),
10003 MakeDeductionFailureInfo(Context, TDK, Info));
10004 (void)TDK;
10005 continue;
10006 }
10007
10008 // Target attributes are part of the cuda function signature, so
10009 // the deduced template's cuda target must match that of the
10010 // specialization. Given that C++ template deduction does not
10011 // take target attributes into account, we reject candidates
10012 // here that have a different target.
10013 if (LangOpts.CUDA &&
10015 /* IgnoreImplicitHDAttr = */ true) !=
10016 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
10017 FailedCandidates.addCandidate().set(
10018 I.getPair(), FunTmpl->getTemplatedDecl(),
10021 continue;
10022 }
10023
10024 // Record this candidate.
10025 if (ExplicitTemplateArgs)
10026 ConvertedTemplateArgs[Specialization] = std::move(Args);
10027 Candidates.addDecl(Specialization, I.getAccess());
10028 }
10029 }
10030
10031 // For a qualified friend declaration (with no explicit marker to indicate
10032 // that a template specialization was intended), note all (template and
10033 // non-template) candidates.
10034 if (QualifiedFriend && Candidates.empty()) {
10035 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
10036 << FD->getDeclName() << FDLookupContext;
10037 // FIXME: We should form a single candidate list and diagnose all
10038 // candidates at once, to get proper sorting and limiting.
10039 for (auto *OldND : Previous) {
10040 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
10041 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
10042 }
10043 FailedCandidates.NoteCandidates(*this, FD->getLocation());
10044 return true;
10045 }
10046
10047 // Find the most specialized function template.
10049 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
10050 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
10051 PDiag(diag::err_function_template_spec_ambiguous)
10052 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
10053 PDiag(diag::note_function_template_spec_matched));
10054
10055 if (Result == Candidates.end())
10056 return true;
10057
10058 // Ignore access information; it doesn't figure into redeclaration checking.
10059 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
10060
10061 // C++23 [except.spec]p13:
10062 // An exception specification is considered to be needed when:
10063 // - [...]
10064 // - the exception specification is compared to that of another declaration
10065 // (e.g., an explicit specialization or an overriding virtual function);
10066 // - [...]
10067 //
10068 // The exception specification of a defaulted function is evaluated as
10069 // described above only when needed; similarly, the noexcept-specifier of a
10070 // specialization of a function template or member function of a class
10071 // template is instantiated only when needed.
10072 //
10073 // The standard doesn't specify what the "comparison with another declaration"
10074 // entails, nor the exact circumstances in which it occurs. Moreover, it does
10075 // not state which properties of an explicit specialization must match the
10076 // primary template.
10077 //
10078 // We assume that an explicit specialization must correspond with (per
10079 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
10080 // the declaration produced by substitution into the function template.
10081 //
10082 // Since the determination whether two function declarations correspond does
10083 // not consider exception specification, we only need to instantiate it once
10084 // we determine the primary template when comparing types per
10085 // [basic.link]p11.1.
10086 auto *SpecializationFPT =
10087 Specialization->getType()->castAs<FunctionProtoType>();
10088 // If the function has a dependent exception specification, resolve it after
10089 // we have selected the primary template so we can check whether it matches.
10090 if (getLangOpts().CPlusPlus17 &&
10091 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
10092 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
10093 return true;
10094
10096 = Specialization->getTemplateSpecializationInfo();
10097 assert(SpecInfo && "Function template specialization info missing?");
10098
10099 // Note: do not overwrite location info if previous template
10100 // specialization kind was explicit.
10102 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
10103 Specialization->setLocation(FD->getLocation());
10104 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
10105 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
10106 // function can differ from the template declaration with respect to
10107 // the constexpr specifier.
10108 // FIXME: We need an update record for this AST mutation.
10109 // FIXME: What if there are multiple such prior declarations (for instance,
10110 // from different modules)?
10111 Specialization->setConstexprKind(FD->getConstexprKind());
10112 }
10113
10114 // FIXME: Check if the prior specialization has a point of instantiation.
10115 // If so, we have run afoul of .
10116
10117 // If this is a friend declaration, then we're not really declaring
10118 // an explicit specialization.
10119 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
10120
10121 // Check the scope of this explicit specialization.
10122 if (!isFriend &&
10124 Specialization->getPrimaryTemplate(),
10126 false))
10127 return true;
10128
10129 // C++ [temp.expl.spec]p6:
10130 // If a template, a member template or the member of a class template is
10131 // explicitly specialized then that specialization shall be declared
10132 // before the first use of that specialization that would cause an implicit
10133 // instantiation to take place, in every translation unit in which such a
10134 // use occurs; no diagnostic is required.
10135 bool HasNoEffect = false;
10136 if (!isFriend &&
10141 SpecInfo->getPointOfInstantiation(),
10142 HasNoEffect))
10143 return true;
10144
10145 // Mark the prior declaration as an explicit specialization, so that later
10146 // clients know that this is an explicit specialization.
10147 if (!isFriend) {
10148 // Since explicit specializations do not inherit '=delete' from their
10149 // primary function template - check if the 'specialization' that was
10150 // implicitly generated (during template argument deduction for partial
10151 // ordering) from the most specialized of all the function templates that
10152 // 'FD' could have been specializing, has a 'deleted' definition. If so,
10153 // first check that it was implicitly generated during template argument
10154 // deduction by making sure it wasn't referenced, and then reset the deleted
10155 // flag to not-deleted, so that we can inherit that information from 'FD'.
10156 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
10157 !Specialization->getCanonicalDecl()->isReferenced()) {
10158 // FIXME: This assert will not hold in the presence of modules.
10159 assert(
10160 Specialization->getCanonicalDecl() == Specialization &&
10161 "This must be the only existing declaration of this specialization");
10162 // FIXME: We need an update record for this AST mutation.
10163 Specialization->setDeletedAsWritten(false);
10164 }
10165 // FIXME: We need an update record for this AST mutation.
10168 }
10169
10170 // Turn the given function declaration into a function template
10171 // specialization, with the template arguments from the previous
10172 // specialization.
10173 // Take copies of (semantic and syntactic) template argument lists.
10175 Context, Specialization->getTemplateSpecializationArgs()->asArray());
10176 FD->setFunctionTemplateSpecialization(
10177 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
10179 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
10180
10181 // A function template specialization inherits the target attributes
10182 // of its template. (We require the attributes explicitly in the
10183 // code to match, but a template may have implicit attributes by
10184 // virtue e.g. of being constexpr, and it passes these implicit
10185 // attributes on to its specializations.)
10186 if (LangOpts.CUDA)
10187 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
10188
10189 // The "previous declaration" for this function template specialization is
10190 // the prior function template specialization.
10191 Previous.clear();
10192 Previous.addDecl(Specialization);
10193 return false;
10194}
10195
10196/// Perform semantic analysis for the given non-template member
10197/// specialization.
10198///
10199/// This routine performs all of the semantic analysis required for an
10200/// explicit member function specialization. On successful completion,
10201/// the function declaration \p FD will become a member function
10202/// specialization.
10203///
10204/// \param Member the member declaration, which will be updated to become a
10205/// specialization.
10206///
10207/// \param Previous the set of declarations, one of which may be specialized
10208/// by this function specialization; the set will be modified to contain the
10209/// redeclared member.
10210bool
10212 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
10213
10214 // Try to find the member we are instantiating.
10215 NamedDecl *FoundInstantiation = nullptr;
10216 NamedDecl *Instantiation = nullptr;
10217 NamedDecl *InstantiatedFrom = nullptr;
10218 MemberSpecializationInfo *MSInfo = nullptr;
10219
10220 if (Previous.empty()) {
10221 // Nowhere to look anyway.
10222 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
10223 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10224 I != E; ++I) {
10225 NamedDecl *D = (*I)->getUnderlyingDecl();
10226 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
10227 QualType Adjusted = Function->getType();
10228 if (!hasExplicitCallingConv(Adjusted))
10229 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
10230 // This doesn't handle deduced return types, but both function
10231 // declarations should be undeduced at this point.
10232 if (Context.hasSameType(Adjusted, Method->getType())) {
10233 FoundInstantiation = *I;
10234 Instantiation = Method;
10235 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
10236 MSInfo = Method->getMemberSpecializationInfo();
10237 break;
10238 }
10239 }
10240 }
10241 } else if (isa<VarDecl>(Member)) {
10242 VarDecl *PrevVar;
10243 if (Previous.isSingleResult() &&
10244 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10245 if (PrevVar->isStaticDataMember()) {
10246 FoundInstantiation = Previous.getRepresentativeDecl();
10247 Instantiation = PrevVar;
10248 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10249 MSInfo = PrevVar->getMemberSpecializationInfo();
10250 }
10251 } else if (isa<RecordDecl>(Member)) {
10252 CXXRecordDecl *PrevRecord;
10253 if (Previous.isSingleResult() &&
10254 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10255 FoundInstantiation = Previous.getRepresentativeDecl();
10256 Instantiation = PrevRecord;
10257 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10258 MSInfo = PrevRecord->getMemberSpecializationInfo();
10259 }
10260 } else if (isa<EnumDecl>(Member)) {
10261 EnumDecl *PrevEnum;
10262 if (Previous.isSingleResult() &&
10263 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10264 FoundInstantiation = Previous.getRepresentativeDecl();
10265 Instantiation = PrevEnum;
10266 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10267 MSInfo = PrevEnum->getMemberSpecializationInfo();
10268 }
10269 }
10270
10271 if (!Instantiation) {
10272 // There is no previous declaration that matches. Since member
10273 // specializations are always out-of-line, the caller will complain about
10274 // this mismatch later.
10275 return false;
10276 }
10277
10278 // A member specialization in a friend declaration isn't really declaring
10279 // an explicit specialization, just identifying a specific (possibly implicit)
10280 // specialization. Don't change the template specialization kind.
10281 //
10282 // FIXME: Is this really valid? Other compilers reject.
10283 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10284 // Preserve instantiation information.
10285 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10286 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10287 cast<CXXMethodDecl>(InstantiatedFrom),
10288 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
10289 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10290 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10291 cast<CXXRecordDecl>(InstantiatedFrom),
10292 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
10293 }
10294
10295 Previous.clear();
10296 Previous.addDecl(FoundInstantiation);
10297 return false;
10298 }
10299
10300 // Make sure that this is a specialization of a member.
10301 if (!InstantiatedFrom) {
10302 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10303 << Member;
10304 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10305 return true;
10306 }
10307
10308 // C++ [temp.expl.spec]p6:
10309 // If a template, a member template or the member of a class template is
10310 // explicitly specialized then that specialization shall be declared
10311 // before the first use of that specialization that would cause an implicit
10312 // instantiation to take place, in every translation unit in which such a
10313 // use occurs; no diagnostic is required.
10314 assert(MSInfo && "Member specialization info missing?");
10315
10316 bool HasNoEffect = false;
10319 Instantiation,
10321 MSInfo->getPointOfInstantiation(),
10322 HasNoEffect))
10323 return true;
10324
10325 // Check the scope of this explicit specialization.
10327 InstantiatedFrom,
10328 Instantiation, Member->getLocation(),
10329 false))
10330 return true;
10331
10332 // Note that this member specialization is an "instantiation of" the
10333 // corresponding member of the original template.
10334 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10335 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10336 if (InstantiationFunction->getTemplateSpecializationKind() ==
10338 // Explicit specializations of member functions of class templates do not
10339 // inherit '=delete' from the member function they are specializing.
10340 if (InstantiationFunction->isDeleted()) {
10341 // FIXME: This assert will not hold in the presence of modules.
10342 assert(InstantiationFunction->getCanonicalDecl() ==
10343 InstantiationFunction);
10344 // FIXME: We need an update record for this AST mutation.
10345 InstantiationFunction->setDeletedAsWritten(false);
10346 }
10347 }
10348
10349 MemberFunction->setInstantiationOfMemberFunction(
10350 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10351 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10352 MemberVar->setInstantiationOfStaticDataMember(
10353 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10354 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10355 MemberClass->setInstantiationOfMemberClass(
10356 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10357 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10358 MemberEnum->setInstantiationOfMemberEnum(
10359 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10360 } else {
10361 llvm_unreachable("unknown member specialization kind");
10362 }
10363
10364 // Save the caller the trouble of having to figure out which declaration
10365 // this specialization matches.
10366 Previous.clear();
10367 Previous.addDecl(FoundInstantiation);
10368 return false;
10369}
10370
10371/// Complete the explicit specialization of a member of a class template by
10372/// updating the instantiated member to be marked as an explicit specialization.
10373///
10374/// \param OrigD The member declaration instantiated from the template.
10375/// \param Loc The location of the explicit specialization of the member.
10376template<typename DeclT>
10377static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10378 SourceLocation Loc) {
10379 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10380 return;
10381
10382 // FIXME: Inform AST mutation listeners of this AST mutation.
10383 // FIXME: If there are multiple in-class declarations of the member (from
10384 // multiple modules, or a declaration and later definition of a member type),
10385 // should we update all of them?
10386 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10387 OrigD->setLocation(Loc);
10388}
10389
10392 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10393 if (Instantiation == Member)
10394 return;
10395
10396 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10397 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10398 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10399 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10400 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10401 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10402 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10403 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10404 else
10405 llvm_unreachable("unknown member specialization kind");
10406}
10407
10408/// Check the scope of an explicit instantiation.
10409///
10410/// \returns true if a serious error occurs, false otherwise.
10412 SourceLocation InstLoc,
10413 bool WasQualifiedName) {
10415 DeclContext *CurContext = S.CurContext->getRedeclContext();
10416
10417 if (CurContext->isRecord()) {
10418 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10419 << D;
10420 return true;
10421 }
10422
10423 // C++11 [temp.explicit]p3:
10424 // An explicit instantiation shall appear in an enclosing namespace of its
10425 // template. If the name declared in the explicit instantiation is an
10426 // unqualified name, the explicit instantiation shall appear in the
10427 // namespace where its template is declared or, if that namespace is inline
10428 // (7.3.1), any namespace from its enclosing namespace set.
10429 //
10430 // This is DR275, which we do not retroactively apply to C++98/03.
10431 if (WasQualifiedName) {
10432 if (CurContext->Encloses(OrigContext))
10433 return false;
10434 } else {
10435 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10436 return false;
10437 }
10438
10439 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10440 if (WasQualifiedName)
10441 S.Diag(InstLoc,
10442 S.getLangOpts().CPlusPlus11?
10443 diag::err_explicit_instantiation_out_of_scope :
10444 diag::warn_explicit_instantiation_out_of_scope_0x)
10445 << D << NS;
10446 else
10447 S.Diag(InstLoc,
10448 S.getLangOpts().CPlusPlus11?
10449 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10450 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10451 << D << NS;
10452 } else
10453 S.Diag(InstLoc,
10454 S.getLangOpts().CPlusPlus11?
10455 diag::err_explicit_instantiation_must_be_global :
10456 diag::warn_explicit_instantiation_must_be_global_0x)
10457 << D;
10458 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10459 return false;
10460}
10461
10462/// Common checks for whether an explicit instantiation of \p D is valid.
10464 SourceLocation InstLoc,
10465 bool WasQualifiedName,
10467 // C++ [temp.explicit]p13:
10468 // An explicit instantiation declaration shall not name a specialization of
10469 // a template with internal linkage.
10472 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10473 return true;
10474 }
10475
10476 // C++11 [temp.explicit]p3: [DR 275]
10477 // An explicit instantiation shall appear in an enclosing namespace of its
10478 // template.
10479 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10480 return true;
10481
10482 return false;
10483}
10484
10485/// Determine whether the given scope specifier has a template-id in it.
10487 if (!SS.isSet())
10488 return false;
10489
10490 // C++11 [temp.explicit]p3:
10491 // If the explicit instantiation is for a member function, a member class
10492 // or a static data member of a class template specialization, the name of
10493 // the class template specialization in the qualified-id for the member
10494 // name shall be a simple-template-id.
10495 //
10496 // C++98 has the same restriction, just worded differently.
10497 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
10498 NNS = NNS->getPrefix())
10499 if (const Type *T = NNS->getAsType())
10500 if (isa<TemplateSpecializationType>(T))
10501 return true;
10502
10503 return false;
10504}
10505
10506/// Make a dllexport or dllimport attr on a class template specialization take
10507/// effect.
10510 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10511 assert(A && "dllExportImportClassTemplateSpecialization called "
10512 "on Def without dllexport or dllimport");
10513
10514 // We reject explicit instantiations in class scope, so there should
10515 // never be any delayed exported classes to worry about.
10516 assert(S.DelayedDllExportClasses.empty() &&
10517 "delayed exports present at explicit instantiation");
10519
10520 // Propagate attribute to base class templates.
10521 for (auto &B : Def->bases()) {
10522 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10523 B.getType()->getAsCXXRecordDecl()))
10525 }
10526
10528}
10529
10530// Explicit instantiation of a class template specialization
10532 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10533 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10534 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10535 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10536 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10537 // Find the class template we're specializing
10538 TemplateName Name = TemplateD.get();
10539 TemplateDecl *TD = Name.getAsTemplateDecl();
10540 // Check that the specialization uses the same tag kind as the
10541 // original template.
10543 assert(Kind != TagTypeKind::Enum &&
10544 "Invalid enum tag in class template explicit instantiation!");
10545
10546 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10547
10548 if (!ClassTemplate) {
10549 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10550 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
10551 << TD << NTK << llvm::to_underlying(Kind);
10552 Diag(TD->getLocation(), diag::note_previous_use);
10553 return true;
10554 }
10555
10556 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10557 Kind, /*isDefinition*/false, KWLoc,
10558 ClassTemplate->getIdentifier())) {
10559 Diag(KWLoc, diag::err_use_with_wrong_tag)
10560 << ClassTemplate
10562 ClassTemplate->getTemplatedDecl()->getKindName());
10563 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10564 diag::note_previous_use);
10565 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10566 }
10567
10568 // C++0x [temp.explicit]p2:
10569 // There are two forms of explicit instantiation: an explicit instantiation
10570 // definition and an explicit instantiation declaration. An explicit
10571 // instantiation declaration begins with the extern keyword. [...]
10572 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10575
10577 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10578 // Check for dllexport class template instantiation declarations,
10579 // except for MinGW mode.
10580 for (const ParsedAttr &AL : Attr) {
10581 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10582 Diag(ExternLoc,
10583 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10584 Diag(AL.getLoc(), diag::note_attribute);
10585 break;
10586 }
10587 }
10588
10589 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10590 Diag(ExternLoc,
10591 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10592 Diag(A->getLocation(), diag::note_attribute);
10593 }
10594 }
10595
10596 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10597 // instantiation declarations for most purposes.
10598 bool DLLImportExplicitInstantiationDef = false;
10601 // Check for dllimport class template instantiation definitions.
10602 bool DLLImport =
10603 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10604 for (const ParsedAttr &AL : Attr) {
10605 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10606 DLLImport = true;
10607 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10608 // dllexport trumps dllimport here.
10609 DLLImport = false;
10610 break;
10611 }
10612 }
10613 if (DLLImport) {
10615 DLLImportExplicitInstantiationDef = true;
10616 }
10617 }
10618
10619 // Translate the parser's template argument list in our AST format.
10620 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10621 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10622
10623 // Check that the template argument list is well-formed for this
10624 // template.
10625 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10626 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10627 false, SugaredConverted, CanonicalConverted,
10628 /*UpdateArgsWithConversions=*/true))
10629 return true;
10630
10631 // Find the class template specialization declaration that
10632 // corresponds to these arguments.
10633 void *InsertPos = nullptr;
10635 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
10636
10637 TemplateSpecializationKind PrevDecl_TSK
10638 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10639
10640 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10641 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10642 // Check for dllexport class template instantiation definitions in MinGW
10643 // mode, if a previous declaration of the instantiation was seen.
10644 for (const ParsedAttr &AL : Attr) {
10645 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10646 Diag(AL.getLoc(),
10647 diag::warn_attribute_dllexport_explicit_instantiation_def);
10648 break;
10649 }
10650 }
10651 }
10652
10653 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10654 SS.isSet(), TSK))
10655 return true;
10656
10658
10659 bool HasNoEffect = false;
10660 if (PrevDecl) {
10661 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10662 PrevDecl, PrevDecl_TSK,
10663 PrevDecl->getPointOfInstantiation(),
10664 HasNoEffect))
10665 return PrevDecl;
10666
10667 // Even though HasNoEffect == true means that this explicit instantiation
10668 // has no effect on semantics, we go on to put its syntax in the AST.
10669
10670 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10671 PrevDecl_TSK == TSK_Undeclared) {
10672 // Since the only prior class template specialization with these
10673 // arguments was referenced but not declared, reuse that
10674 // declaration node as our own, updating the source location
10675 // for the template name to reflect our new declaration.
10676 // (Other source locations will be updated later.)
10677 Specialization = PrevDecl;
10678 Specialization->setLocation(TemplateNameLoc);
10679 PrevDecl = nullptr;
10680 }
10681
10682 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10683 DLLImportExplicitInstantiationDef) {
10684 // The new specialization might add a dllimport attribute.
10685 HasNoEffect = false;
10686 }
10687 }
10688
10689 if (!Specialization) {
10690 // Create a new class template specialization declaration node for
10691 // this explicit specialization.
10693 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10694 ClassTemplate, CanonicalConverted, PrevDecl);
10696
10697 // A MSInheritanceAttr attached to the previous declaration must be
10698 // propagated to the new node prior to instantiation.
10699 if (PrevDecl) {
10700 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10701 auto *Clone = A->clone(getASTContext());
10702 Clone->setInherited(true);
10703 Specialization->addAttr(Clone);
10705 }
10706 }
10707
10708 if (!HasNoEffect && !PrevDecl) {
10709 // Insert the new specialization.
10710 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10711 }
10712 }
10713
10714 // Build the fully-sugared type for this explicit instantiation as
10715 // the user wrote in the explicit instantiation itself. This means
10716 // that we'll pretty-print the type retrieved from the
10717 // specialization's declaration the way that the user actually wrote
10718 // the explicit instantiation, rather than formatting the name based
10719 // on the "canonical" representation used to store the template
10720 // arguments in the specialization.
10721 TypeSourceInfo *WrittenTy
10722 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
10723 TemplateArgs,
10725 Specialization->setTypeAsWritten(WrittenTy);
10726
10727 // Set source locations for keywords.
10728 Specialization->setExternLoc(ExternLoc);
10729 Specialization->setTemplateKeywordLoc(TemplateLoc);
10730 Specialization->setBraceRange(SourceRange());
10731
10732 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10735
10736 // Add the explicit instantiation into its lexical context. However,
10737 // since explicit instantiations are never found by name lookup, we
10738 // just put it into the declaration context directly.
10739 Specialization->setLexicalDeclContext(CurContext);
10741
10742 // Syntax is now OK, so return if it has no other effect on semantics.
10743 if (HasNoEffect) {
10744 // Set the template specialization kind.
10745 Specialization->setTemplateSpecializationKind(TSK);
10746 return Specialization;
10747 }
10748
10749 // C++ [temp.explicit]p3:
10750 // A definition of a class template or class member template
10751 // shall be in scope at the point of the explicit instantiation of
10752 // the class template or class member template.
10753 //
10754 // This check comes when we actually try to perform the
10755 // instantiation.
10757 = cast_or_null<ClassTemplateSpecializationDecl>(
10758 Specialization->getDefinition());
10759 if (!Def)
10761 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10762 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10763 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10764 }
10765
10766 // Instantiate the members of this class template specialization.
10767 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10768 Specialization->getDefinition());
10769 if (Def) {
10771 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10772 // TSK_ExplicitInstantiationDefinition
10773 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10775 DLLImportExplicitInstantiationDef)) {
10776 // FIXME: Need to notify the ASTMutationListener that we did this.
10778
10779 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10781 !Context.getTargetInfo().getTriple().isPS())) {
10782 // An explicit instantiation definition can add a dll attribute to a
10783 // template with a previous instantiation declaration. MinGW doesn't
10784 // allow this.
10785 auto *A = cast<InheritableAttr>(
10787 A->setInherited(true);
10788 Def->addAttr(A);
10790 }
10791 }
10792
10793 // Fix a TSK_ImplicitInstantiation followed by a
10794 // TSK_ExplicitInstantiationDefinition
10795 bool NewlyDLLExported =
10796 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10797 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10799 !Context.getTargetInfo().getTriple().isPS())) {
10800 // An explicit instantiation definition can add a dll attribute to a
10801 // template with a previous implicit instantiation. MinGW doesn't allow
10802 // this. We limit clang to only adding dllexport, to avoid potentially
10803 // strange codegen behavior. For example, if we extend this conditional
10804 // to dllimport, and we have a source file calling a method on an
10805 // implicitly instantiated template class instance and then declaring a
10806 // dllimport explicit instantiation definition for the same template
10807 // class, the codegen for the method call will not respect the dllimport,
10808 // while it will with cl. The Def will already have the DLL attribute,
10809 // since the Def and Specialization will be the same in the case of
10810 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10811 // attribute to the Specialization; we just need to make it take effect.
10812 assert(Def == Specialization &&
10813 "Def and Specialization should match for implicit instantiation");
10815 }
10816
10817 // In MinGW mode, export the template instantiation if the declaration
10818 // was marked dllexport.
10819 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10820 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10821 PrevDecl->hasAttr<DLLExportAttr>()) {
10823 }
10824
10825 // Set the template specialization kind. Make sure it is set before
10826 // instantiating the members which will trigger ASTConsumer callbacks.
10827 Specialization->setTemplateSpecializationKind(TSK);
10828 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10829 } else {
10830
10831 // Set the template specialization kind.
10832 Specialization->setTemplateSpecializationKind(TSK);
10833 }
10834
10835 return Specialization;
10836}
10837
10838// Explicit instantiation of a member class of a class template.
10841 SourceLocation TemplateLoc, unsigned TagSpec,
10842 SourceLocation KWLoc, CXXScopeSpec &SS,
10843 IdentifierInfo *Name, SourceLocation NameLoc,
10844 const ParsedAttributesView &Attr) {
10845
10846 bool Owned = false;
10847 bool IsDependent = false;
10848 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
10849 NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10850 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10851 false, TypeResult(), /*IsTypeSpecifier*/ false,
10852 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
10853 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10854
10855 if (!TagD)
10856 return true;
10857
10858 TagDecl *Tag = cast<TagDecl>(TagD);
10859 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10860
10861 if (Tag->isInvalidDecl())
10862 return true;
10863
10864 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10865 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10866 if (!Pattern) {
10867 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10869 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10870 return true;
10871 }
10872
10873 // C++0x [temp.explicit]p2:
10874 // If the explicit instantiation is for a class or member class, the
10875 // elaborated-type-specifier in the declaration shall include a
10876 // simple-template-id.
10877 //
10878 // C++98 has the same restriction, just worded differently.
10880 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10881 << Record << SS.getRange();
10882
10883 // C++0x [temp.explicit]p2:
10884 // There are two forms of explicit instantiation: an explicit instantiation
10885 // definition and an explicit instantiation declaration. An explicit
10886 // instantiation declaration begins with the extern keyword. [...]
10890
10891 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10892
10893 // Verify that it is okay to explicitly instantiate here.
10894 CXXRecordDecl *PrevDecl
10895 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10896 if (!PrevDecl && Record->getDefinition())
10897 PrevDecl = Record;
10898 if (PrevDecl) {
10900 bool HasNoEffect = false;
10901 assert(MSInfo && "No member specialization information?");
10902 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10903 PrevDecl,
10905 MSInfo->getPointOfInstantiation(),
10906 HasNoEffect))
10907 return true;
10908 if (HasNoEffect)
10909 return TagD;
10910 }
10911
10912 CXXRecordDecl *RecordDef
10913 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10914 if (!RecordDef) {
10915 // C++ [temp.explicit]p3:
10916 // A definition of a member class of a class template shall be in scope
10917 // at the point of an explicit instantiation of the member class.
10918 CXXRecordDecl *Def
10919 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10920 if (!Def) {
10921 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10922 << 0 << Record->getDeclName() << Record->getDeclContext();
10923 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10924 << Pattern;
10925 return true;
10926 } else {
10927 if (InstantiateClass(NameLoc, Record, Def,
10929 TSK))
10930 return true;
10931
10932 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10933 if (!RecordDef)
10934 return true;
10935 }
10936 }
10937
10938 // Instantiate all of the members of the class.
10939 InstantiateClassMembers(NameLoc, RecordDef,
10941
10943 MarkVTableUsed(NameLoc, RecordDef, true);
10944
10945 // FIXME: We don't have any representation for explicit instantiations of
10946 // member classes. Such a representation is not needed for compilation, but it
10947 // should be available for clients that want to see all of the declarations in
10948 // the source code.
10949 return TagD;
10950}
10951
10953 SourceLocation ExternLoc,
10954 SourceLocation TemplateLoc,
10955 Declarator &D) {
10956 // Explicit instantiations always require a name.
10957 // TODO: check if/when DNInfo should replace Name.
10959 DeclarationName Name = NameInfo.getName();
10960 if (!Name) {
10961 if (!D.isInvalidType())
10963 diag::err_explicit_instantiation_requires_name)
10965
10966 return true;
10967 }
10968
10969 // Get the innermost enclosing declaration scope.
10970 S = S->getDeclParent();
10971
10972 // Determine the type of the declaration.
10974 QualType R = T->getType();
10975 if (R.isNull())
10976 return true;
10977
10978 // C++ [dcl.stc]p1:
10979 // A storage-class-specifier shall not be specified in [...] an explicit
10980 // instantiation (14.7.2) directive.
10982 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10983 << Name;
10984 return true;
10985 } else if (D.getDeclSpec().getStorageClassSpec()
10987 // Complain about then remove the storage class specifier.
10988 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10990
10992 }
10993
10994 // C++0x [temp.explicit]p1:
10995 // [...] An explicit instantiation of a function template shall not use the
10996 // inline or constexpr specifiers.
10997 // Presumably, this also applies to member functions of class templates as
10998 // well.
11002 diag::err_explicit_instantiation_inline :
11003 diag::warn_explicit_instantiation_inline_0x)
11006 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
11007 // not already specified.
11009 diag::err_explicit_instantiation_constexpr);
11010
11011 // A deduction guide is not on the list of entities that can be explicitly
11012 // instantiated.
11013 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
11014 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
11015 << /*explicit instantiation*/ 0;
11016 return true;
11017 }
11018
11019 // C++0x [temp.explicit]p2:
11020 // There are two forms of explicit instantiation: an explicit instantiation
11021 // definition and an explicit instantiation declaration. An explicit
11022 // instantiation declaration begins with the extern keyword. [...]
11026
11027 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
11029
11030 if (!R->isFunctionType()) {
11031 // C++ [temp.explicit]p1:
11032 // A [...] static data member of a class template can be explicitly
11033 // instantiated from the member definition associated with its class
11034 // template.
11035 // C++1y [temp.explicit]p1:
11036 // A [...] variable [...] template specialization can be explicitly
11037 // instantiated from its template.
11038 if (Previous.isAmbiguous())
11039 return true;
11040
11041 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
11042 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
11043
11044 if (!PrevTemplate) {
11045 if (!Prev || !Prev->isStaticDataMember()) {
11046 // We expect to see a static data member here.
11047 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
11048 << Name;
11049 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11050 P != PEnd; ++P)
11051 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
11052 return true;
11053 }
11054
11056 // FIXME: Check for explicit specialization?
11058 diag::err_explicit_instantiation_data_member_not_instantiated)
11059 << Prev;
11060 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
11061 // FIXME: Can we provide a note showing where this was declared?
11062 return true;
11063 }
11064 } else {
11065 // Explicitly instantiate a variable template.
11066
11067 // C++1y [dcl.spec.auto]p6:
11068 // ... A program that uses auto or decltype(auto) in a context not
11069 // explicitly allowed in this section is ill-formed.
11070 //
11071 // This includes auto-typed variable template instantiations.
11072 if (R->isUndeducedType()) {
11074 diag::err_auto_not_allowed_var_inst);
11075 return true;
11076 }
11077
11079 // C++1y [temp.explicit]p3:
11080 // If the explicit instantiation is for a variable, the unqualified-id
11081 // in the declaration shall be a template-id.
11083 diag::err_explicit_instantiation_without_template_id)
11084 << PrevTemplate;
11085 Diag(PrevTemplate->getLocation(),
11086 diag::note_explicit_instantiation_here);
11087 return true;
11088 }
11089
11090 // Translate the parser's template argument list into our AST format.
11091 TemplateArgumentListInfo TemplateArgs =
11093
11094 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
11095 D.getIdentifierLoc(), TemplateArgs);
11096 if (Res.isInvalid())
11097 return true;
11098
11099 if (!Res.isUsable()) {
11100 // We somehow specified dependent template arguments in an explicit
11101 // instantiation. This should probably only happen during error
11102 // recovery.
11103 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
11104 return true;
11105 }
11106
11107 // Ignore access control bits, we don't need them for redeclaration
11108 // checking.
11109 Prev = cast<VarDecl>(Res.get());
11110 }
11111
11112 // C++0x [temp.explicit]p2:
11113 // If the explicit instantiation is for a member function, a member class
11114 // or a static data member of a class template specialization, the name of
11115 // the class template specialization in the qualified-id for the member
11116 // name shall be a simple-template-id.
11117 //
11118 // C++98 has the same restriction, just worded differently.
11119 //
11120 // This does not apply to variable template specializations, where the
11121 // template-id is in the unqualified-id instead.
11122 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
11124 diag::ext_explicit_instantiation_without_qualified_id)
11125 << Prev << D.getCXXScopeSpec().getRange();
11126
11127 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
11128
11129 // Verify that it is okay to explicitly instantiate here.
11132 bool HasNoEffect = false;
11134 PrevTSK, POI, HasNoEffect))
11135 return true;
11136
11137 if (!HasNoEffect) {
11138 // Instantiate static data member or variable template.
11140 // Merge attributes.
11142 if (PrevTemplate)
11143 ProcessAPINotes(Prev);
11144
11147 }
11148
11149 // Check the new variable specialization against the parsed input.
11150 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
11152 diag::err_invalid_var_template_spec_type)
11153 << 0 << PrevTemplate << R << Prev->getType();
11154 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
11155 << 2 << PrevTemplate->getDeclName();
11156 return true;
11157 }
11158
11159 // FIXME: Create an ExplicitInstantiation node?
11160 return (Decl*) nullptr;
11161 }
11162
11163 // If the declarator is a template-id, translate the parser's template
11164 // argument list into our AST format.
11165 bool HasExplicitTemplateArgs = false;
11166 TemplateArgumentListInfo TemplateArgs;
11168 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
11169 HasExplicitTemplateArgs = true;
11170 }
11171
11172 // C++ [temp.explicit]p1:
11173 // A [...] function [...] can be explicitly instantiated from its template.
11174 // A member function [...] of a class template can be explicitly
11175 // instantiated from the member definition associated with its class
11176 // template.
11177 UnresolvedSet<8> TemplateMatches;
11178 FunctionDecl *NonTemplateMatch = nullptr;
11179 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
11180 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11181 P != PEnd; ++P) {
11182 NamedDecl *Prev = *P;
11183 if (!HasExplicitTemplateArgs) {
11184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11185 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11186 /*AdjustExceptionSpec*/true);
11187 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11188 if (Method->getPrimaryTemplate()) {
11189 TemplateMatches.addDecl(Method, P.getAccess());
11190 } else {
11191 // FIXME: Can this assert ever happen? Needs a test.
11192 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
11193 NonTemplateMatch = Method;
11194 }
11195 }
11196 }
11197 }
11198
11199 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11200 if (!FunTmpl)
11201 continue;
11202
11203 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11204 FunctionDecl *Specialization = nullptr;
11206 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11207 Specialization, Info);
11209 // Keep track of almost-matches.
11210 FailedCandidates.addCandidate()
11211 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
11212 MakeDeductionFailureInfo(Context, TDK, Info));
11213 (void)TDK;
11214 continue;
11215 }
11216
11217 // Target attributes are part of the cuda function signature, so
11218 // the cuda target of the instantiated function must match that of its
11219 // template. Given that C++ template deduction does not take
11220 // target attributes into account, we reject candidates here that
11221 // have a different target.
11222 if (LangOpts.CUDA &&
11224 /* IgnoreImplicitHDAttr = */ true) !=
11226 FailedCandidates.addCandidate().set(
11227 P.getPair(), FunTmpl->getTemplatedDecl(),
11230 continue;
11231 }
11232
11233 TemplateMatches.addDecl(Specialization, P.getAccess());
11234 }
11235
11236 FunctionDecl *Specialization = NonTemplateMatch;
11237 if (!Specialization) {
11238 // Find the most specialized function template specialization.
11240 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
11241 D.getIdentifierLoc(),
11242 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11243 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11244 PDiag(diag::note_explicit_instantiation_candidate));
11245
11246 if (Result == TemplateMatches.end())
11247 return true;
11248
11249 // Ignore access control bits, we don't need them for redeclaration checking.
11250 Specialization = cast<FunctionDecl>(*Result);
11251 }
11252
11253 // C++11 [except.spec]p4
11254 // In an explicit instantiation an exception-specification may be specified,
11255 // but is not required.
11256 // If an exception-specification is specified in an explicit instantiation
11257 // directive, it shall be compatible with the exception-specifications of
11258 // other declarations of that function.
11259 if (auto *FPT = R->getAs<FunctionProtoType>())
11260 if (FPT->hasExceptionSpec()) {
11261 unsigned DiagID =
11262 diag::err_mismatched_exception_spec_explicit_instantiation;
11263 if (getLangOpts().MicrosoftExt)
11264 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11266 PDiag(DiagID) << Specialization->getType(),
11267 PDiag(diag::note_explicit_instantiation_here),
11268 Specialization->getType()->getAs<FunctionProtoType>(),
11269 Specialization->getLocation(), FPT, D.getBeginLoc());
11270 // In Microsoft mode, mismatching exception specifications just cause a
11271 // warning.
11272 if (!getLangOpts().MicrosoftExt && Result)
11273 return true;
11274 }
11275
11276 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11278 diag::err_explicit_instantiation_member_function_not_instantiated)
11280 << (Specialization->getTemplateSpecializationKind() ==
11282 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11283 return true;
11284 }
11285
11286 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11287 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11288 PrevDecl = Specialization;
11289
11290 if (PrevDecl) {
11291 bool HasNoEffect = false;
11293 PrevDecl,
11295 PrevDecl->getPointOfInstantiation(),
11296 HasNoEffect))
11297 return true;
11298
11299 // FIXME: We may still want to build some representation of this
11300 // explicit specialization.
11301 if (HasNoEffect)
11302 return (Decl*) nullptr;
11303 }
11304
11305 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11306 // functions
11307 // valarray<size_t>::valarray(size_t) and
11308 // valarray<size_t>::~valarray()
11309 // that it declared to have internal linkage with the internal_linkage
11310 // attribute. Ignore the explicit instantiation declaration in this case.
11311 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11313 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11314 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11315 RD->isInStdNamespace())
11316 return (Decl*) nullptr;
11317 }
11318
11321
11322 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11323 // instantiation declarations.
11325 Specialization->hasAttr<DLLImportAttr>() &&
11328
11329 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11330
11331 if (Specialization->isDefined()) {
11332 // Let the ASTConsumer know that this function has been explicitly
11333 // instantiated now, and its linkage might have changed.
11335 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11337
11338 // C++0x [temp.explicit]p2:
11339 // If the explicit instantiation is for a member function, a member class
11340 // or a static data member of a class template specialization, the name of
11341 // the class template specialization in the qualified-id for the member
11342 // name shall be a simple-template-id.
11343 //
11344 // C++98 has the same restriction, just worded differently.
11345 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11346 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11347 D.getCXXScopeSpec().isSet() &&
11350 diag::ext_explicit_instantiation_without_qualified_id)
11352
11354 *this,
11355 FunTmpl ? (NamedDecl *)FunTmpl
11356 : Specialization->getInstantiatedFromMemberFunction(),
11357 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11358
11359 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11360 return (Decl*) nullptr;
11361}
11362
11364Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11365 const CXXScopeSpec &SS, IdentifierInfo *Name,
11366 SourceLocation TagLoc, SourceLocation NameLoc) {
11367 // This has to hold, because SS is expected to be defined.
11368 assert(Name && "Expected a name in a dependent tag");
11369
11370 NestedNameSpecifier *NNS = SS.getScopeRep();
11371 if (!NNS)
11372 return true;
11373
11375
11376 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
11377 Diag(NameLoc, diag::err_dependent_tag_decl)
11378 << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
11379 << SS.getRange();
11380 return true;
11381 }
11382
11383 // Create the resulting type.
11385 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11386
11387 // Create type-source location information for this type.
11388 TypeLocBuilder TLB;
11390 TL.setElaboratedKeywordLoc(TagLoc);
11392 TL.setNameLoc(NameLoc);
11394}
11395
11397 const CXXScopeSpec &SS,
11398 const IdentifierInfo &II,
11399 SourceLocation IdLoc,
11400 ImplicitTypenameContext IsImplicitTypename) {
11401 if (SS.isInvalid())
11402 return true;
11403
11404 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11405 Diag(TypenameLoc,
11407 diag::warn_cxx98_compat_typename_outside_of_template :
11408 diag::ext_typename_outside_of_template)
11409 << FixItHint::CreateRemoval(TypenameLoc);
11410
11412 TypeSourceInfo *TSI = nullptr;
11413 QualType T =
11414 CheckTypenameType((TypenameLoc.isValid() ||
11415 IsImplicitTypename == ImplicitTypenameContext::Yes)
11418 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11419 /*DeducedTSTContext=*/true);
11420 if (T.isNull())
11421 return true;
11422 return CreateParsedType(T, TSI);
11423}
11424
11427 SourceLocation TypenameLoc,
11428 const CXXScopeSpec &SS,
11429 SourceLocation TemplateKWLoc,
11430 TemplateTy TemplateIn,
11431 IdentifierInfo *TemplateII,
11432 SourceLocation TemplateIILoc,
11433 SourceLocation LAngleLoc,
11434 ASTTemplateArgsPtr TemplateArgsIn,
11435 SourceLocation RAngleLoc) {
11436 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11437 Diag(TypenameLoc,
11439 diag::warn_cxx98_compat_typename_outside_of_template :
11440 diag::ext_typename_outside_of_template)
11441 << FixItHint::CreateRemoval(TypenameLoc);
11442
11443 // Strangely, non-type results are not ignored by this lookup, so the
11444 // program is ill-formed if it finds an injected-class-name.
11445 if (TypenameLoc.isValid()) {
11446 auto *LookupRD =
11447 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11448 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11449 Diag(TemplateIILoc,
11450 diag::ext_out_of_line_qualified_id_type_names_constructor)
11451 << TemplateII << 0 /*injected-class-name used as template name*/
11452 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11453 }
11454 }
11455
11456 // Translate the parser's template argument list in our AST format.
11457 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11458 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11459
11460 TemplateName Template = TemplateIn.get();
11461 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11462 // Construct a dependent template specialization type.
11463 assert(DTN && "dependent template has non-dependent name?");
11464 assert(DTN->getQualifier() == SS.getScopeRep());
11466 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
11467 DTN->getIdentifier(), TemplateArgs.arguments());
11468
11469 // Create source-location information for this type.
11470 TypeLocBuilder Builder;
11472 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
11473 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11475 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11476 SpecTL.setTemplateNameLoc(TemplateIILoc);
11477 SpecTL.setLAngleLoc(LAngleLoc);
11478 SpecTL.setRAngleLoc(RAngleLoc);
11479 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11480 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11481 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11482 }
11483
11484 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
11485 if (T.isNull())
11486 return true;
11487
11488 // Provide source-location information for the template specialization type.
11489 TypeLocBuilder Builder;
11491 = Builder.push<TemplateSpecializationTypeLoc>(T);
11492 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11493 SpecTL.setTemplateNameLoc(TemplateIILoc);
11494 SpecTL.setLAngleLoc(LAngleLoc);
11495 SpecTL.setRAngleLoc(RAngleLoc);
11496 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11497 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11498
11500 SS.getScopeRep(), T);
11501 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
11502 TL.setElaboratedKeywordLoc(TypenameLoc);
11504
11505 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11506 return CreateParsedType(T, TSI);
11507}
11508
11509
11510/// Determine whether this failed name lookup should be treated as being
11511/// disabled by a usage of std::enable_if.
11513 SourceRange &CondRange, Expr *&Cond) {
11514 // We must be looking for a ::type...
11515 if (!II.isStr("type"))
11516 return false;
11517
11518 // ... within an explicitly-written template specialization...
11519 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
11520 return false;
11521 TypeLoc EnableIfTy = NNS.getTypeLoc();
11522 TemplateSpecializationTypeLoc EnableIfTSTLoc =
11524 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11525 return false;
11526 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11527
11528 // ... which names a complete class template declaration...
11529 const TemplateDecl *EnableIfDecl =
11530 EnableIfTST->getTemplateName().getAsTemplateDecl();
11531 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11532 return false;
11533
11534 // ... called "enable_if".
11535 const IdentifierInfo *EnableIfII =
11536 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11537 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11538 return false;
11539
11540 // Assume the first template argument is the condition.
11541 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11542
11543 // Dig out the condition.
11544 Cond = nullptr;
11545 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11547 return true;
11548
11549 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11550
11551 // Ignore Boolean literals; they add no value.
11552 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11553 Cond = nullptr;
11554
11555 return true;
11556}
11557
11560 SourceLocation KeywordLoc,
11561 NestedNameSpecifierLoc QualifierLoc,
11562 const IdentifierInfo &II,
11563 SourceLocation IILoc,
11564 TypeSourceInfo **TSI,
11565 bool DeducedTSTContext) {
11566 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11567 DeducedTSTContext);
11568 if (T.isNull())
11569 return QualType();
11570
11571 *TSI = Context.CreateTypeSourceInfo(T);
11572 if (isa<DependentNameType>(T)) {
11574 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11575 TL.setElaboratedKeywordLoc(KeywordLoc);
11576 TL.setQualifierLoc(QualifierLoc);
11577 TL.setNameLoc(IILoc);
11578 } else {
11579 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11580 TL.setElaboratedKeywordLoc(KeywordLoc);
11581 TL.setQualifierLoc(QualifierLoc);
11582 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11583 }
11584 return T;
11585}
11586
11587/// Build the type that describes a C++ typename specifier,
11588/// e.g., "typename T::type".
11591 SourceLocation KeywordLoc,
11592 NestedNameSpecifierLoc QualifierLoc,
11593 const IdentifierInfo &II,
11594 SourceLocation IILoc, bool DeducedTSTContext) {
11595 CXXScopeSpec SS;
11596 SS.Adopt(QualifierLoc);
11597
11598 DeclContext *Ctx = nullptr;
11599 if (QualifierLoc) {
11600 Ctx = computeDeclContext(SS);
11601 if (!Ctx) {
11602 // If the nested-name-specifier is dependent and couldn't be
11603 // resolved to a type, build a typename type.
11604 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11605 return Context.getDependentNameType(Keyword,
11606 QualifierLoc.getNestedNameSpecifier(),
11607 &II);
11608 }
11609
11610 // If the nested-name-specifier refers to the current instantiation,
11611 // the "typename" keyword itself is superfluous. In C++03, the
11612 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11613 // allows such extraneous "typename" keywords, and we retroactively
11614 // apply this DR to C++03 code with only a warning. In any case we continue.
11615
11616 if (RequireCompleteDeclContext(SS, Ctx))
11617 return QualType();
11618 }
11619
11620 DeclarationName Name(&II);
11621 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11622 if (Ctx)
11623 LookupQualifiedName(Result, Ctx, SS);
11624 else
11625 LookupName(Result, CurScope);
11626 unsigned DiagID = 0;
11627 Decl *Referenced = nullptr;
11628 switch (Result.getResultKind()) {
11630 // If we're looking up 'type' within a template named 'enable_if', produce
11631 // a more specific diagnostic.
11632 SourceRange CondRange;
11633 Expr *Cond = nullptr;
11634 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11635 // If we have a condition, narrow it down to the specific failed
11636 // condition.
11637 if (Cond) {
11638 Expr *FailedCond;
11639 std::string FailedDescription;
11640 std::tie(FailedCond, FailedDescription) =
11642
11643 Diag(FailedCond->getExprLoc(),
11644 diag::err_typename_nested_not_found_requirement)
11645 << FailedDescription
11646 << FailedCond->getSourceRange();
11647 return QualType();
11648 }
11649
11650 Diag(CondRange.getBegin(),
11651 diag::err_typename_nested_not_found_enable_if)
11652 << Ctx << CondRange;
11653 return QualType();
11654 }
11655
11656 DiagID = Ctx ? diag::err_typename_nested_not_found
11657 : diag::err_unknown_typename;
11658 break;
11659 }
11660
11662 // We found a using declaration that is a value. Most likely, the using
11663 // declaration itself is meant to have the 'typename' keyword.
11664 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11665 IILoc);
11666 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11667 << Name << Ctx << FullRange;
11668 if (UnresolvedUsingValueDecl *Using
11669 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11670 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11671 Diag(Loc, diag::note_using_value_decl_missing_typename)
11672 << FixItHint::CreateInsertion(Loc, "typename ");
11673 }
11674 }
11675 // Fall through to create a dependent typename type, from which we can recover
11676 // better.
11677 [[fallthrough]];
11678
11680 // Okay, it's a member of an unknown instantiation.
11681 return Context.getDependentNameType(Keyword,
11682 QualifierLoc.getNestedNameSpecifier(),
11683 &II);
11684
11686 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11687 // C++ [class.qual]p2:
11688 // In a lookup in which function names are not ignored and the
11689 // nested-name-specifier nominates a class C, if the name specified
11690 // after the nested-name-specifier, when looked up in C, is the
11691 // injected-class-name of C [...] then the name is instead considered
11692 // to name the constructor of class C.
11693 //
11694 // Unlike in an elaborated-type-specifier, function names are not ignored
11695 // in typename-specifier lookup. However, they are ignored in all the
11696 // contexts where we form a typename type with no keyword (that is, in
11697 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11698 //
11699 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11700 // ignore functions, but that appears to be an oversight.
11701 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
11702 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
11703 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
11704 FoundRD->isInjectedClassName() &&
11705 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11706 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11707 << &II << 1 << 0 /*'typename' keyword used*/;
11708
11709 // We found a type. Build an ElaboratedType, since the
11710 // typename-specifier was just sugar.
11711 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
11712 return Context.getElaboratedType(Keyword,
11713 QualifierLoc.getNestedNameSpecifier(),
11715 }
11716
11717 // C++ [dcl.type.simple]p2:
11718 // A type-specifier of the form
11719 // typename[opt] nested-name-specifier[opt] template-name
11720 // is a placeholder for a deduced class type [...].
11721 if (getLangOpts().CPlusPlus17) {
11722 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11723 if (!DeducedTSTContext) {
11724 QualType T(QualifierLoc
11725 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11726 : nullptr, 0);
11727 if (!T.isNull())
11728 Diag(IILoc, diag::err_dependent_deduced_tst)
11730 else
11731 Diag(IILoc, diag::err_deduced_tst)
11734 return QualType();
11735 }
11737 Keyword, QualifierLoc.getNestedNameSpecifier(),
11739 QualType(), false));
11740 }
11741 }
11742
11743 DiagID = Ctx ? diag::err_typename_nested_not_type
11744 : diag::err_typename_not_type;
11745 Referenced = Result.getFoundDecl();
11746 break;
11747
11749 DiagID = Ctx ? diag::err_typename_nested_not_type
11750 : diag::err_typename_not_type;
11751 Referenced = *Result.begin();
11752 break;
11753
11755 return QualType();
11756 }
11757
11758 // If we get here, it's because name lookup did not find a
11759 // type. Emit an appropriate diagnostic and return an error.
11760 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11761 IILoc);
11762 if (Ctx)
11763 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11764 else
11765 Diag(IILoc, DiagID) << FullRange << Name;
11766 if (Referenced)
11767 Diag(Referenced->getLocation(),
11768 Ctx ? diag::note_typename_member_refers_here
11769 : diag::note_typename_refers_here)
11770 << Name;
11771 return QualType();
11772}
11773
11774namespace {
11775 // See Sema::RebuildTypeInCurrentInstantiation
11776 class CurrentInstantiationRebuilder
11777 : public TreeTransform<CurrentInstantiationRebuilder> {
11778 SourceLocation Loc;
11779 DeclarationName Entity;
11780
11781 public:
11783
11784 CurrentInstantiationRebuilder(Sema &SemaRef,
11785 SourceLocation Loc,
11786 DeclarationName Entity)
11787 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11788 Loc(Loc), Entity(Entity) { }
11789
11790 /// Determine whether the given type \p T has already been
11791 /// transformed.
11792 ///
11793 /// For the purposes of type reconstruction, a type has already been
11794 /// transformed if it is NULL or if it is not dependent.
11795 bool AlreadyTransformed(QualType T) {
11796 return T.isNull() || !T->isInstantiationDependentType();
11797 }
11798
11799 /// Returns the location of the entity whose type is being
11800 /// rebuilt.
11801 SourceLocation getBaseLocation() { return Loc; }
11802
11803 /// Returns the name of the entity whose type is being rebuilt.
11804 DeclarationName getBaseEntity() { return Entity; }
11805
11806 /// Sets the "base" location and entity when that
11807 /// information is known based on another transformation.
11808 void setBase(SourceLocation Loc, DeclarationName Entity) {
11809 this->Loc = Loc;
11810 this->Entity = Entity;
11811 }
11812
11813 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11814 // Lambdas never need to be transformed.
11815 return E;
11816 }
11817 };
11818} // end anonymous namespace
11819
11820/// Rebuilds a type within the context of the current instantiation.
11821///
11822/// The type \p T is part of the type of an out-of-line member definition of
11823/// a class template (or class template partial specialization) that was parsed
11824/// and constructed before we entered the scope of the class template (or
11825/// partial specialization thereof). This routine will rebuild that type now
11826/// that we have entered the declarator's scope, which may produce different
11827/// canonical types, e.g.,
11828///
11829/// \code
11830/// template<typename T>
11831/// struct X {
11832/// typedef T* pointer;
11833/// pointer data();
11834/// };
11835///
11836/// template<typename T>
11837/// typename X<T>::pointer X<T>::data() { ... }
11838/// \endcode
11839///
11840/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11841/// since we do not know that we can look into X<T> when we parsed the type.
11842/// This function will rebuild the type, performing the lookup of "pointer"
11843/// in X<T> and returning an ElaboratedType whose canonical type is the same
11844/// as the canonical type of T*, allowing the return types of the out-of-line
11845/// definition and the declaration to match.
11847 SourceLocation Loc,
11848 DeclarationName Name) {
11849 if (!T || !T->getType()->isInstantiationDependentType())
11850 return T;
11851
11852 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11853 return Rebuilder.TransformType(T);
11854}
11855
11857 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11858 DeclarationName());
11859 return Rebuilder.TransformExpr(E);
11860}
11861
11863 if (SS.isInvalid())
11864 return true;
11865
11867 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11868 DeclarationName());
11870 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11871 if (!Rebuilt)
11872 return true;
11873
11874 SS.Adopt(Rebuilt);
11875 return false;
11876}
11877
11878/// Rebuild the template parameters now that we know we're in a current
11879/// instantiation.
11881 TemplateParameterList *Params) {
11882 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11883 Decl *Param = Params->getParam(I);
11884
11885 // There is nothing to rebuild in a type parameter.
11886 if (isa<TemplateTypeParmDecl>(Param))
11887 continue;
11888
11889 // Rebuild the template parameter list of a template template parameter.
11891 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11893 TTP->getTemplateParameters()))
11894 return true;
11895
11896 continue;
11897 }
11898
11899 // Rebuild the type of a non-type template parameter.
11900 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11901 TypeSourceInfo *NewTSI
11903 NTTP->getLocation(),
11904 NTTP->getDeclName());
11905 if (!NewTSI)
11906 return true;
11907
11908 if (NewTSI->getType()->isUndeducedType()) {
11909 // C++17 [temp.dep.expr]p3:
11910 // An id-expression is type-dependent if it contains
11911 // - an identifier associated by name lookup with a non-type
11912 // template-parameter declared with a type that contains a
11913 // placeholder type (7.1.7.4),
11914 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11915 }
11916
11917 if (NewTSI != NTTP->getTypeSourceInfo()) {
11918 NTTP->setTypeSourceInfo(NewTSI);
11919 NTTP->setType(NewTSI->getType());
11920 }
11921 }
11922
11923 return false;
11924}
11925
11926/// Produces a formatted string that describes the binding of
11927/// template parameters to template arguments.
11928std::string
11930 const TemplateArgumentList &Args) {
11931 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11932}
11933
11934std::string
11936 const TemplateArgument *Args,
11937 unsigned NumArgs) {
11938 SmallString<128> Str;
11939 llvm::raw_svector_ostream Out(Str);
11940
11941 if (!Params || Params->size() == 0 || NumArgs == 0)
11942 return std::string();
11943
11944 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11945 if (I >= NumArgs)
11946 break;
11947
11948 if (I == 0)
11949 Out << "[with ";
11950 else
11951 Out << ", ";
11952
11953 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11954 Out << Id->getName();
11955 } else {
11956 Out << '$' << I;
11957 }
11958
11959 Out << " = ";
11960 Args[I].print(getPrintingPolicy(), Out,
11962 getPrintingPolicy(), Params, I));
11963 }
11964
11965 Out << ']';
11966 return std::string(Out.str());
11967}
11968
11970 CachedTokens &Toks) {
11971 if (!FD)
11972 return;
11973
11974 auto LPT = std::make_unique<LateParsedTemplate>();
11975
11976 // Take tokens to avoid allocations
11977 LPT->Toks.swap(Toks);
11978 LPT->D = FnD;
11979 LPT->FPO = getCurFPFeatures();
11980 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11981
11982 FD->setLateTemplateParsed(true);
11983}
11984
11986 if (!FD)
11987 return;
11988 FD->setLateTemplateParsed(false);
11989}
11990
11992 DeclContext *DC = CurContext;
11993
11994 while (DC) {
11995 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11996 const FunctionDecl *FD = RD->isLocalClass();
11997 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11998 } else if (DC->isTranslationUnit() || DC->isNamespace())
11999 return false;
12000
12001 DC = DC->getParent();
12002 }
12003 return false;
12004}
12005
12006namespace {
12007/// Walk the path from which a declaration was instantiated, and check
12008/// that every explicit specialization along that path is visible. This enforces
12009/// C++ [temp.expl.spec]/6:
12010///
12011/// If a template, a member template or a member of a class template is
12012/// explicitly specialized then that specialization shall be declared before
12013/// the first use of that specialization that would cause an implicit
12014/// instantiation to take place, in every translation unit in which such a
12015/// use occurs; no diagnostic is required.
12016///
12017/// and also C++ [temp.class.spec]/1:
12018///
12019/// A partial specialization shall be declared before the first use of a
12020/// class template specialization that would make use of the partial
12021/// specialization as the result of an implicit or explicit instantiation
12022/// in every translation unit in which such a use occurs; no diagnostic is
12023/// required.
12024class ExplicitSpecializationVisibilityChecker {
12025 Sema &S;
12026 SourceLocation Loc;
12029
12030public:
12031 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
12033 : S(S), Loc(Loc), Kind(Kind) {}
12034
12035 void check(NamedDecl *ND) {
12036 if (auto *FD = dyn_cast<FunctionDecl>(ND))
12037 return checkImpl(FD);
12038 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
12039 return checkImpl(RD);
12040 if (auto *VD = dyn_cast<VarDecl>(ND))
12041 return checkImpl(VD);
12042 if (auto *ED = dyn_cast<EnumDecl>(ND))
12043 return checkImpl(ED);
12044 }
12045
12046private:
12047 void diagnose(NamedDecl *D, bool IsPartialSpec) {
12048 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
12049 : Sema::MissingImportKind::ExplicitSpecialization;
12050 const bool Recover = true;
12051
12052 // If we got a custom set of modules (because only a subset of the
12053 // declarations are interesting), use them, otherwise let
12054 // diagnoseMissingImport intelligently pick some.
12055 if (Modules.empty())
12056 S.diagnoseMissingImport(Loc, D, Kind, Recover);
12057 else
12058 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
12059 }
12060
12061 bool CheckMemberSpecialization(const NamedDecl *D) {
12062 return Kind == Sema::AcceptableKind::Visible
12065 }
12066
12067 bool CheckExplicitSpecialization(const NamedDecl *D) {
12068 return Kind == Sema::AcceptableKind::Visible
12071 }
12072
12073 bool CheckDeclaration(const NamedDecl *D) {
12074 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
12076 }
12077
12078 // Check a specific declaration. There are three problematic cases:
12079 //
12080 // 1) The declaration is an explicit specialization of a template
12081 // specialization.
12082 // 2) The declaration is an explicit specialization of a member of an
12083 // templated class.
12084 // 3) The declaration is an instantiation of a template, and that template
12085 // is an explicit specialization of a member of a templated class.
12086 //
12087 // We don't need to go any deeper than that, as the instantiation of the
12088 // surrounding class / etc is not triggered by whatever triggered this
12089 // instantiation, and thus should be checked elsewhere.
12090 template<typename SpecDecl>
12091 void checkImpl(SpecDecl *Spec) {
12092 bool IsHiddenExplicitSpecialization = false;
12093 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
12094 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
12095 ? !CheckMemberSpecialization(Spec)
12096 : !CheckExplicitSpecialization(Spec);
12097 } else {
12098 checkInstantiated(Spec);
12099 }
12100
12101 if (IsHiddenExplicitSpecialization)
12102 diagnose(Spec->getMostRecentDecl(), false);
12103 }
12104
12105 void checkInstantiated(FunctionDecl *FD) {
12106 if (auto *TD = FD->getPrimaryTemplate())
12107 checkTemplate(TD);
12108 }
12109
12110 void checkInstantiated(CXXRecordDecl *RD) {
12111 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
12112 if (!SD)
12113 return;
12114
12115 auto From = SD->getSpecializedTemplateOrPartial();
12116 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
12117 checkTemplate(TD);
12118 else if (auto *TD =
12119 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
12120 if (!CheckDeclaration(TD))
12121 diagnose(TD, true);
12122 checkTemplate(TD);
12123 }
12124 }
12125
12126 void checkInstantiated(VarDecl *RD) {
12127 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
12128 if (!SD)
12129 return;
12130
12131 auto From = SD->getSpecializedTemplateOrPartial();
12132 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
12133 checkTemplate(TD);
12134 else if (auto *TD =
12135 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
12136 if (!CheckDeclaration(TD))
12137 diagnose(TD, true);
12138 checkTemplate(TD);
12139 }
12140 }
12141
12142 void checkInstantiated(EnumDecl *FD) {}
12143
12144 template<typename TemplDecl>
12145 void checkTemplate(TemplDecl *TD) {
12146 if (TD->isMemberSpecialization()) {
12147 if (!CheckMemberSpecialization(TD))
12148 diagnose(TD->getMostRecentDecl(), false);
12149 }
12150 }
12151};
12152} // end anonymous namespace
12153
12155 if (!getLangOpts().Modules)
12156 return;
12157
12158 ExplicitSpecializationVisibilityChecker(*this, Loc,
12160 .check(Spec);
12161}
12162
12164 NamedDecl *Spec) {
12165 if (!getLangOpts().CPlusPlusModules)
12166 return checkSpecializationVisibility(Loc, Spec);
12167
12168 ExplicitSpecializationVisibilityChecker(*this, Loc,
12170 .check(Spec);
12171}
12172
12173/// Returns the top most location responsible for the definition of \p N.
12174/// If \p N is a a template specialization, this is the location
12175/// of the top of the instantiation stack.
12176/// Otherwise, the location of \p N is returned.
12179 return N->getLocation();
12180 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12182 return FD->getLocation();
12185 return N->getLocation();
12186 }
12187 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12188 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12189 continue;
12190 return CSC.PointOfInstantiation;
12191 }
12192 return N->getLocation();
12193}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1110
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
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:28
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
MatchFinder::MatchResult MatchResult
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6958
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 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 NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
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 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 TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *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 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 bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *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 SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
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 bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static TypeSourceInfo * SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted)
Substitute template arguments into the default template argument for the given template type paramete...
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 QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
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 void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, IdentifierInfo *Name)
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.
Defines utilities for dealing with stack allocation and stack space.
static const TemplateArgument & getArgument(const TemplateArgument &A)
StateNode * Previous
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:970
APSInt & getInt()
Definition: APValue.h:423
APSInt & getComplexIntImag()
Definition: APValue.h:461
ValueKind getKind() const
Definition: APValue.h:395
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1053
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isMemberPointer() const
Definition: APValue.h:411
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:942
@ 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:1006
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1068
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:643
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1113
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1575
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
CanQualType IntTy
Definition: ASTContext.h:1095
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1114
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2315
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1553
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1034
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
QualType getElementType() const
Definition: Type.h:3159
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6732
Attr - This represents one attribute.
Definition: Attr.h:42
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2158
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2176
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2226
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2200
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2219
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2194
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2206
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5524
A fixed int type of a specified bitwidth.
Definition: Type.h:6785
Pointer to a block type.
Definition: Type.h:2978
QualType getPointeeType() const
Definition: Type.h:2990
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: Type.h:2740
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:2091
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2599
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition: DeclCXX.cpp:2156
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3645
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:1484
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
bool isConst() const
Definition: DeclCXX.h:2105
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1875
base_class_range bases()
Definition: DeclCXX.h:618
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1904
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1900
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1882
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1915
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:531
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:209
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:235
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1062
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
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
void setMemberSpecialization()
Note that this member template is a specialization.
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
Represents a class template specialization, which refers to a class template with a given set of temp...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
Complex values, per C99 6.2.5p11.
Definition: Type.h:2845
QualType getElementType() const
Definition: Type.h:2855
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
bool isTypeConcept() const
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr)
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:93
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3186
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3710
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2201
bool isFileContext() const
Definition: DeclBase.h:2147
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1976
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1299
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1265
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...
Definition: DeclBase.cpp:1958
bool isNamespace() const
Definition: DeclBase.h:2161
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
bool isTranslationUnit() const
Definition: DeclBase.h:2152
bool isRecord() const
Definition: DeclBase.h:2156
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1699
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1939
bool isFunctionOrMethod() const
Definition: DeclBase.h:2128
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1216
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1316
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1320
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1335
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1365
ValueDecl * getDecl()
Definition: Expr.h:1328
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1355
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
bool isNoreturnSpecified() const
Definition: DeclSpec.h:657
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:658
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:440
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:578
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
@ 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:262
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:843
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:813
void dropAttrs()
Definition: DeclBase.cpp:968
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1016
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:2749
bool isInvalidDecl() const
Definition: DeclBase.h:593
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:507
SourceLocation getLocation() const
Definition: DeclBase.h:444
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
DeclContext * getDeclContext()
Definition: DeclBase.h:453
AccessSpecifier getAccess() const
Definition: DeclBase.h:512
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
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:582
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
Kind getKind() const
Definition: DeclBase.h:447
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
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.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1899
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2046
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2335
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2725
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2082
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2065
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2061
bool hasEllipsis() const
Definition: DeclSpec.h:2724
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2329
bool isInvalidType() const
Definition: DeclSpec.h:2713
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2081
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2053
Represents the type decltype(expr) (C++11).
Definition: Type.h:4901
Represents a C++17 deduced template specialization type.
Definition: Type.h:5572
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5490
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5511
bool isDeduced() const
Definition: Type.h:5512
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3402
QualType getPointeeType() const
Definition: Type.h:3414
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2392
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2372
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2381
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:5995
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:6013
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3285
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:482
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3344
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3442
QualType getElementType() const
Definition: Type.h:3457
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:3769
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:488
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:547
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:544
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2441
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2461
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2429
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2485
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2477
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2493
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2469
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6047
NestedNameSpecifier * getQualifier() const
Definition: Type.h:6063
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3564
QualType getElementType() const
Definition: Type.h:3576
bool isEmpty() const
Definition: TypeLoc.h:2334
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2292
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2330
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2306
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:5914
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3832
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4091
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4905
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5118
EnumDecl * getDecl() const
Definition: Type.h:5125
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1892
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3050
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3045
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
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:3025
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:3904
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:3604
Represents a member of a struct/union/class.
Definition: Decl.h:3025
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:979
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1058
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, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1959
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2413
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4019
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4327
QualType getReturnType() const
Definition: Decl.h:2722
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4127
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3582
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2477
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3958
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2407
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:4193
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2306
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4233
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2485
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4154
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4555
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4443
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4439
ArrayRef< QualType > param_types() const
Definition: Type.h:4587
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:543
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:554
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:526
unsigned getNumParams() const
Definition: TypeLoc.h:1474
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1426
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1422
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1438
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1481
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1465
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1446
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1430
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1460
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1418
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1434
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1442
QualType getReturnType() const
Definition: Type.h:4116
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.
StringRef getName() const
Return the actual identifier string.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3649
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3246
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4841
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...
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:8578
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:5764
CXXRecordDecl * getDecl() const
Definition: Type.cpp:4002
QualType getInjectedSpecializationType() const
Definition: Type.h:5795
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:957
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3053
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1938
Represents a linkage specification.
Definition: DeclCXX.h:2927
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:670
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:716
bool hasNext() const
Definition: Lookup.h:701
NamedDecl * next()
Definition: Lookup.h:705
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:492
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:600
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition: Lookup.h:315
DeclClass * getAsSingle() const
Definition: Lookup.h:553
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:472
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:268
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:359
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:659
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:744
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:563
bool isAmbiguous() const
Definition: Lookup.h:321
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:328
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:449
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:273
bool isSuppressingAmbiguousDiagnostics() const
Determines whether this lookup is suppressing ambiguous lookup diagnostics.
Definition: Lookup.h:643
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:570
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:629
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:263
iterator end() const
Definition: Lookup.h:356
iterator begin() const
Definition: Lookup.h:355
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:253
A global _GUID constant.
Definition: DeclCXX.h:4282
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:3688
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3089
QualType getPointeeType() const
Definition: Type.h:3105
const Type * getClass() const
Definition: Type.h:3119
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:656
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:244
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:257
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 setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
NamedDecl * getMostRecentDecl()
Definition: Decl.h:476
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:696
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
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.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
void setDefaultArgument(Expr *DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6495
Represents a pointer to an Objective C object.
Definition: Type.h:6551
Represents a class type in Objective C.
Definition: Type.h:6297
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(TemplateName P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4142
Represents a pack expansion of types.
Definition: Type.h:6112
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:6133
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2129
Represents a parameter to a function.
Definition: Decl.h:1749
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1809
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1782
Expr * getDefaultArg()
Definition: Decl.cpp:2968
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1799
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
Represents the parsed form of a C++ template argument.
KindType getKind() const
Determine what kind of template argument we have.
SourceLocation getLocation() const
Retrieve the location of the template argument.
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.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition: Type.h:6751
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
QualType getPointeeType() const
Definition: Type.h:2908
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:737
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3403
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7102
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
void * getAsOpaquePtr() const
Definition: Type.h:784
bool isCanonical() const
Definition: Type.h:6959
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6948
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1124
The collection of all-type qualifiers we support.
Definition: Type.h:147
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
void addConst()
Definition: Type.h:267
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:355
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3071
Represents a struct/union/class.
Definition: Decl.h:4133
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:861
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:866
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4959
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3009
QualType getPointeeType() const
Definition: Type.h:3027
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:256
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:264
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10543
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6786
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2671
Whether and why a template name is required in this lookup.
Definition: Sema.h:9103
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:9111
bool hasTemplateKeyword() const
Definition: Sema.h:9114
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:598
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5994
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9388
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6768
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10477
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:10034
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
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',...
Definition: SemaDecl.cpp:1575
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16292
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7603
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7607
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7615
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7610
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:20416
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:39
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc)
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.
Definition: SemaDecl.cpp:6215
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...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, 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....
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:7806
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6182
void NoteAllFoundTemplates(TemplateName Name)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
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.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, 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...
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 * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
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)
Definition: SemaDecl.cpp:6344
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17996
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:53
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
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 ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1556
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)
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:9074
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:9422
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9425
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:9429
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:1030
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...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:3075
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5883
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1517
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.
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
ASTContext & getASTContext() const
Definition: Sema.h:501
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.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Definition: SemaDecl.cpp:1746
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
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 RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9635
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:947
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...
Definition: SemaDecl.cpp:17092
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2199
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:9064
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:9508
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:9526
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:9537
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9516
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:9547
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:9124
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
@ None
This is not assumed to be a template name.
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
FunctionTemplateDecl * DeclareImplicitDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition: Sema.h:9057
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:496
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
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:11077
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:11065
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:11074
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:11068
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:11092
const LangOptions & getLangOpts() const
Definition: Sema.h:494
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.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition: Sema.h:1029
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, std::optional< unsigned > NumExpansions)
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...
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:636
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, 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:11484
const LangOptions & LangOpts
Definition: Sema.h:1028
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.
Definition: SemaExpr.cpp:20815
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.
AcceptableKind
Definition: Sema.h:7595
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.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9733
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8323
Decl * ActOnConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr)
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...
Definition: SemaDecl.cpp:17063
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1219
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)
Definition: SemaInit.cpp:10712
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:645
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3423
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:1163
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:7694
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15065
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5889
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6505
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1469
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1305
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4789
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,...
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9371
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3298
@ NTK_TypeAliasTemplate
Definition: Sema.h:3306
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg)
Check a template argument against its corresponding template template parameter.
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
RedeclarationKind forRedeclarationInCurContext() const
Definition: Sema.h:7701
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
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...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
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:89
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:224
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11943
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
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...
@ CTK_ErrorRecovery
Definition: Sema.h:7859
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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.
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:8278
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3179
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1938
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
ASTConsumer & Consumer
Definition: Sema.h:1031
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1028
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)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
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...
Definition: SemaType.cpp:9828
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.
Definition: SemaType.cpp:6102
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 {'.
Definition: SemaDecl.cpp:17286
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9249
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
@ TemplateNameIsRequired
Definition: Sema.h:9101
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.
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:521
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
@ TUK_Definition
Definition: Sema.h:3321
@ TUK_Declaration
Definition: Sema.h:3320
@ TUK_Friend
Definition: Sema.h:3322
@ TUK_Reference
Definition: Sema.h:3319
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 ...
Definition: SemaDecl.cpp:15102
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:9252
@ TPC_ClassTemplate
Definition: Sema.h:9253
@ TPC_FriendFunctionTemplate
Definition: Sema.h:9258
@ TPC_ClassTemplateMember
Definition: Sema.h:9256
@ TPC_FunctionTemplate
Definition: Sema.h:9255
@ TPC_FriendClassTemplate
Definition: Sema.h:9257
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:9259
@ TPC_TypeAliasTemplate
Definition: Sema.h:9260
@ TPC_VarTemplate
Definition: Sema.h:9254
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.
Definition: SemaDecl.cpp:1597
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose=true)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1580
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2358
@ OOK_Outside
Definition: Sema.h:3327
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:511
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:4800
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)
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)
Definition: SemaDecl.cpp:1720
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output)
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3213
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:2664
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:9066
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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.
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)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:7815
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:9969
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6138
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6967
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
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
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:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4435
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5432
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4069
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:5362
QualType getReplacementType() const
Gets the type that was substituted for the template parameter.
Definition: Type.h:5374
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3549
bool isEnum() const
Definition: Decl.h:3756
StringRef getKindName() const
Definition: Decl.h:3740
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4704
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4750
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4787
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3773
TagKind getTagKind() const
Definition: Decl.h:3744
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:3906
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1291
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1258
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:283
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.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
SourceLocation getLocation() const
Definition: TemplateBase.h:563
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:623
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:616
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:609
Expr * getSourceExpression() const
Definition: TemplateBase.h:584
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
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.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
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.
Definition: TemplateBase.h:343
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.
Definition: TemplateBase.h:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
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.
Definition: TemplateBase.h:377
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
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,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:426
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
bool hasAssociatedConstraints() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
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.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &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
Definition: DeclTemplate.h:199
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 setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1656
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1632
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1664
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1673
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1640
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1648
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5632
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:5700
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:5698
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4094
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.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
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...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
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.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument's source information, if any.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
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, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
void setDefaultArgument(TypeSourceInfo *DefArg)
Set the default argument for this template parameter.
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
unsigned getNumExpansionParameters() const
Retrieves the number of parameters in an expanded parameter pack.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:5325
unsigned getIndex() const
Definition: Type.h:5322
unsigned getDepth() const
Definition: Type.h:5321
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:3521
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5512
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
Represents a declaration of a type.
Definition: Decl.h:3357
const Type * getTypeForDecl() const
Definition: Decl.h:3381
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3384
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:153
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:735
bool isNull() const
Definition: TypeLoc.h:121
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2653
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:4817
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:4865
QualType getUnmodifiedType() const
Definition: Type.h:4880
A container of type source information.
Definition: Type.h:6873
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6884
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
An operation on a type.
Definition: TypeVisitor.h:64
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3088
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3070
The base class of the type hierarchy.
Definition: Type.h:1606
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2170
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isBooleanType() const
Definition: Type.h:7567
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2104
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2154
bool isRValueReferenceType() const
Definition: Type.h:7174
bool isVoidPointerType() const
Definition: Type.cpp:615
bool isArrayType() const
Definition: Type.h:7220
bool isPointerType() const
Definition: Type.h:7154
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isReferenceType() const
Definition: Type.h:7166
bool isEnumeralType() const
Definition: Type.h:7248
bool isScalarType() const
Definition: Type.h:7538
bool isChar8Type() const
Definition: Type.cpp:2042
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1995
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:391
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7554
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2062
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7290
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2525
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2428
bool isLValueReferenceType() const
Definition: Type.h:7170
bool isBitIntType() const
Definition: Type.h:7378
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:2894
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
bool isChar16Type() const
Definition: Type.cpp:2048
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1948
QualType getCanonicalTypeInternal() const
Definition: Type.h:2703
bool isMemberPointerType() const
Definition: Type.h:7202
bool isChar32Type() const
Definition: Type.cpp:2054
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2438
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4778
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7573
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4411
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2299
bool isFunctionType() const
Definition: Type.h:7150
bool isVectorType() const
Definition: Type.h:7256
bool isWideCharType() const
Definition: Type.cpp:2035
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isNullPtrType() const
Definition: Type.h:7472
bool isRecordType() const
Definition: Type.h:7244
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5462
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3399
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3449
QualType getUnderlyingType() const
Definition: Decl.h:3454
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
TypedefNameDecl * getTypedefNameDecl() const
Definition: TypeLoc.h:695
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:2182
A unary type transform, which is a type constructed from another.
Definition: Type.h:5009
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3163
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:373
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:4687
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3855
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3313
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3377
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1267
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
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:2876
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1152
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:2777
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:2756
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setMemberSpecialization()
Note that this member template is a specialization.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos)
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.
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: Type.h:3290
Represents a GCC generic vector type.
Definition: Type.h:3512
QualType getElementType() const
Definition: Type.h:3526
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 * takeCanonical()
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
ImplicitTypenameContext
Definition: DeclSpec.h:1882
bool isa(CodeGen::Address addr)
Definition: Address.h:155
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus11
Definition: LangStandard.h:55
@ CPlusPlus17
Definition: LangStandard.h:57
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Extern
Definition: Specifiers.h:248
@ SC_None
Definition: Specifiers.h:247
@ TSCS_unspecified
Definition: Specifiers.h:233
@ 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...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:5842
@ Enum
The "enum" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
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...
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:304
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
CastKind
CastKind - The kind of operation required for a conversion.
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, const NamedDecl *Param, ArrayRef< TemplateArgument > Args, unsigned Depth)
Make a best-effort determination of whether the type T can be produced by substituting Args into the ...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Non_template
The name does not refer to a template.
Definition: TemplateKinds.h:22
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5817
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ Parens
New-expression has a C++98 paren-delimited initializer.
CharacterLiteralKind
Definition: Expr.h:1584
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
#define false
Definition: stdbool.h:22
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
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.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:4278
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
unsigned TerseOutput
Provide a 'terse' output.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:10051
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:10158
A stack object to be created when performing template instantiation.
Definition: Sema.h:10233
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10381
NamedDecl * Previous
Definition: Sema.h:2784
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
Information about a template-id annotation token.
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.
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.