clang 20.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
28#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/StringExtras.h"
41
42#include <optional>
43using namespace clang;
44using namespace sema;
45
46// Exported for use by Parser.
49 unsigned N) {
50 if (!N) return SourceRange();
51 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
52}
53
54unsigned Sema::getTemplateDepth(Scope *S) const {
55 unsigned Depth = 0;
56
57 // Each template parameter scope represents one level of template parameter
58 // depth.
59 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
60 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
61 ++Depth;
62 }
63
64 // Note that there are template parameters with the given depth.
65 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
66
67 // Look for parameters of an enclosing generic lambda. We don't create a
68 // template parameter scope for these.
70 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
71 if (!LSI->TemplateParams.empty()) {
72 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
73 break;
74 }
75 if (LSI->GLTemplateParameterList) {
76 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
77 break;
78 }
79 }
80 }
81
82 // Look for parameters of an enclosing terse function template. We don't
83 // create a template parameter scope for these either.
84 for (const InventedTemplateParameterInfo &Info :
86 if (!Info.TemplateParams.empty()) {
87 ParamsAtDepth(Info.AutoTemplateParameterDepth);
88 break;
89 }
90 }
91
92 return Depth;
93}
94
95/// \brief Determine whether the declaration found is acceptable as the name
96/// of a template and, if so, return that template declaration. Otherwise,
97/// returns null.
98///
99/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
100/// is true. In all other cases it will return a TemplateDecl (or null).
102 bool AllowFunctionTemplates,
103 bool AllowDependent) {
104 D = D->getUnderlyingDecl();
105
106 if (isa<TemplateDecl>(D)) {
107 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
108 return nullptr;
109
110 return D;
111 }
112
113 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
114 // C++ [temp.local]p1:
115 // Like normal (non-template) classes, class templates have an
116 // injected-class-name (Clause 9). The injected-class-name
117 // can be used with or without a template-argument-list. When
118 // it is used without a template-argument-list, it is
119 // equivalent to the injected-class-name followed by the
120 // template-parameters of the class template enclosed in
121 // <>. When it is used with a template-argument-list, it
122 // refers to the specified class template specialization,
123 // which could be the current specialization or another
124 // specialization.
125 if (Record->isInjectedClassName()) {
126 Record = cast<CXXRecordDecl>(Record->getDeclContext());
127 if (Record->getDescribedClassTemplate())
128 return Record->getDescribedClassTemplate();
129
130 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
131 return Spec->getSpecializedTemplate();
132 }
133
134 return nullptr;
135 }
136
137 // 'using Dependent::foo;' can resolve to a template name.
138 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
139 // injected-class-name).
140 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
141 return D;
142
143 return nullptr;
144}
145
147 bool AllowFunctionTemplates,
148 bool AllowDependent) {
149 LookupResult::Filter filter = R.makeFilter();
150 while (filter.hasNext()) {
151 NamedDecl *Orig = filter.next();
152 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
153 filter.erase();
154 }
155 filter.done();
156}
157
159 bool AllowFunctionTemplates,
160 bool AllowDependent,
161 bool AllowNonTemplateFunctions) {
162 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
163 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
164 return true;
165 if (AllowNonTemplateFunctions &&
166 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
167 return true;
168 }
169
170 return false;
171}
172
174 CXXScopeSpec &SS,
175 bool hasTemplateKeyword,
176 const UnqualifiedId &Name,
177 ParsedType ObjectTypePtr,
178 bool EnteringContext,
179 TemplateTy &TemplateResult,
180 bool &MemberOfUnknownSpecialization,
181 bool Disambiguation) {
182 assert(getLangOpts().CPlusPlus && "No template names in C!");
183
184 DeclarationName TName;
185 MemberOfUnknownSpecialization = false;
186
187 switch (Name.getKind()) {
189 TName = DeclarationName(Name.Identifier);
190 break;
191
194 Name.OperatorFunctionId.Operator);
195 break;
196
198 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
199 break;
200
201 default:
202 return TNK_Non_template;
203 }
204
205 QualType ObjectType = ObjectTypePtr.get();
206
207 AssumedTemplateKind AssumedTemplate;
208 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
209 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
210 /*RequiredTemplate=*/SourceLocation(),
211 &AssumedTemplate,
212 /*AllowTypoCorrection=*/!Disambiguation))
213 return TNK_Non_template;
214 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
215
216 if (AssumedTemplate != AssumedTemplateKind::None) {
217 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
218 // Let the parser know whether we found nothing or found functions; if we
219 // found nothing, we want to more carefully check whether this is actually
220 // a function template name versus some other kind of undeclared identifier.
221 return AssumedTemplate == AssumedTemplateKind::FoundNothing
224 }
225
226 if (R.empty())
227 return TNK_Non_template;
228
229 NamedDecl *D = nullptr;
230 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
231 if (R.isAmbiguous()) {
232 // If we got an ambiguity involving a non-function template, treat this
233 // as a template name, and pick an arbitrary template for error recovery.
234 bool AnyFunctionTemplates = false;
235 for (NamedDecl *FoundD : R) {
236 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
237 if (isa<FunctionTemplateDecl>(FoundTemplate))
238 AnyFunctionTemplates = true;
239 else {
240 D = FoundTemplate;
241 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
242 break;
243 }
244 }
245 }
246
247 // If we didn't find any templates at all, this isn't a template name.
248 // Leave the ambiguity for a later lookup to diagnose.
249 if (!D && !AnyFunctionTemplates) {
250 R.suppressDiagnostics();
251 return TNK_Non_template;
252 }
253
254 // If the only templates were function templates, filter out the rest.
255 // We'll diagnose the ambiguity later.
256 if (!D)
258 }
259
260 // At this point, we have either picked a single template name declaration D
261 // or we have a non-empty set of results R containing either one template name
262 // declaration or a set of function templates.
263
264 TemplateName Template;
265 TemplateNameKind TemplateKind;
266
267 unsigned ResultCount = R.end() - R.begin();
268 if (!D && ResultCount > 1) {
269 // We assume that we'll preserve the qualifier from a function
270 // template name in other ways.
271 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
272 TemplateKind = TNK_Function_template;
273
274 // We'll do this lookup again later.
276 } else {
277 if (!D) {
279 assert(D && "unambiguous result is not a template name");
280 }
281
282 if (isa<UnresolvedUsingValueDecl>(D)) {
283 // We don't yet know whether this is a template-name or not.
284 MemberOfUnknownSpecialization = true;
285 return TNK_Non_template;
286 }
287
288 TemplateDecl *TD = cast<TemplateDecl>(D);
289 Template =
290 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
291 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
292 if (!SS.isInvalid()) {
293 NestedNameSpecifier *Qualifier = SS.getScopeRep();
294 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
295 Template);
296 }
297
298 if (isa<FunctionTemplateDecl>(TD)) {
299 TemplateKind = TNK_Function_template;
300
301 // We'll do this lookup again later.
303 } else {
304 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
305 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
306 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
307 TemplateKind =
308 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
309 isa<ConceptDecl>(TD) ? TNK_Concept_template :
311 }
312 }
313
314 TemplateResult = TemplateTy::make(Template);
315 return TemplateKind;
316}
317
319 SourceLocation NameLoc, CXXScopeSpec &SS,
320 ParsedTemplateTy *Template /*=nullptr*/) {
321 // We could use redeclaration lookup here, but we don't need to: the
322 // syntactic form of a deduction guide is enough to identify it even
323 // if we can't look up the template name at all.
324 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
325 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
326 /*EnteringContext*/ false))
327 return false;
328
329 if (R.empty()) return false;
330 if (R.isAmbiguous()) {
331 // FIXME: Diagnose an ambiguity if we find at least one template.
333 return false;
334 }
335
336 // We only treat template-names that name type templates as valid deduction
337 // guide names.
339 if (!TD || !getAsTypeTemplateDecl(TD))
340 return false;
341
342 if (Template) {
344 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
345 *Template = TemplateTy::make(Name);
346 }
347 return true;
348}
349
351 SourceLocation IILoc,
352 Scope *S,
353 const CXXScopeSpec *SS,
354 TemplateTy &SuggestedTemplate,
355 TemplateNameKind &SuggestedKind) {
356 // We can't recover unless there's a dependent scope specifier preceding the
357 // template name.
358 // FIXME: Typo correction?
359 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
361 return false;
362
363 // The code is missing a 'template' keyword prior to the dependent template
364 // name.
366 Diag(IILoc, diag::err_template_kw_missing)
367 << Qualifier << II.getName()
368 << FixItHint::CreateInsertion(IILoc, "template ");
369 SuggestedTemplate
371 SuggestedKind = TNK_Dependent_template_name;
372 return true;
373}
374
376 QualType ObjectType, bool EnteringContext,
377 RequiredTemplateKind RequiredTemplate,
379 bool AllowTypoCorrection) {
380 if (ATK)
382
383 if (SS.isInvalid())
384 return true;
385
386 Found.setTemplateNameLookup(true);
387
388 // Determine where to perform name lookup
389 DeclContext *LookupCtx = nullptr;
390 bool IsDependent = false;
391 if (!ObjectType.isNull()) {
392 // This nested-name-specifier occurs in a member access expression, e.g.,
393 // x->B::f, and we are looking into the type of the object.
394 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
395 LookupCtx = computeDeclContext(ObjectType);
396 IsDependent = !LookupCtx && ObjectType->isDependentType();
397 assert((IsDependent || !ObjectType->isIncompleteType() ||
398 !ObjectType->getAs<TagType>() ||
399 ObjectType->castAs<TagType>()->isBeingDefined()) &&
400 "Caller should have completed object type");
401
402 // Template names cannot appear inside an Objective-C class or object type
403 // or a vector type.
404 //
405 // FIXME: This is wrong. For example:
406 //
407 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
408 // Vec<int> vi;
409 // vi.Vec<int>::~Vec<int>();
410 //
411 // ... should be accepted but we will not treat 'Vec' as a template name
412 // here. The right thing to do would be to check if the name is a valid
413 // vector component name, and look up a template name if not. And similarly
414 // for lookups into Objective-C class and object types, where the same
415 // problem can arise.
416 if (ObjectType->isObjCObjectOrInterfaceType() ||
417 ObjectType->isVectorType()) {
418 Found.clear();
419 return false;
420 }
421 } else if (SS.isNotEmpty()) {
422 // This nested-name-specifier occurs after another nested-name-specifier,
423 // so long into the context associated with the prior nested-name-specifier.
424 LookupCtx = computeDeclContext(SS, EnteringContext);
425 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
426
427 // The declaration context must be complete.
428 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
429 return true;
430 }
431
432 bool ObjectTypeSearchedInScope = false;
433 bool AllowFunctionTemplatesInLookup = true;
434 if (LookupCtx) {
435 // Perform "qualified" name lookup into the declaration context we
436 // computed, which is either the type of the base of a member access
437 // expression or the declaration context associated with a prior
438 // nested-name-specifier.
439 LookupQualifiedName(Found, LookupCtx);
440
441 // FIXME: The C++ standard does not clearly specify what happens in the
442 // case where the object type is dependent, and implementations vary. In
443 // Clang, we treat a name after a . or -> as a template-name if lookup
444 // finds a non-dependent member or member of the current instantiation that
445 // is a type template, or finds no such members and lookup in the context
446 // of the postfix-expression finds a type template. In the latter case, the
447 // name is nonetheless dependent, and we may resolve it to a member of an
448 // unknown specialization when we come to instantiate the template.
449 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
450 }
451
452 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
453 // C++ [basic.lookup.classref]p1:
454 // In a class member access expression (5.2.5), if the . or -> token is
455 // immediately followed by an identifier followed by a <, the
456 // identifier must be looked up to determine whether the < is the
457 // beginning of a template argument list (14.2) or a less-than operator.
458 // The identifier is first looked up in the class of the object
459 // expression. If the identifier is not found, it is then looked up in
460 // the context of the entire postfix-expression and shall name a class
461 // template.
462 if (S)
463 LookupName(Found, S);
464
465 if (!ObjectType.isNull()) {
466 // FIXME: We should filter out all non-type templates here, particularly
467 // variable templates and concepts. But the exclusion of alias templates
468 // and template template parameters is a wording defect.
469 AllowFunctionTemplatesInLookup = false;
470 ObjectTypeSearchedInScope = true;
471 }
472
473 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
474 }
475
476 if (Found.isAmbiguous())
477 return false;
478
479 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
480 !RequiredTemplate.hasTemplateKeyword()) {
481 // C++2a [temp.names]p2:
482 // A name is also considered to refer to a template if it is an
483 // unqualified-id followed by a < and name lookup finds either one or more
484 // functions or finds nothing.
485 //
486 // To keep our behavior consistent, we apply the "finds nothing" part in
487 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
488 // successfully form a call to an undeclared template-id.
489 bool AllFunctions =
490 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
491 return isa<FunctionDecl>(ND->getUnderlyingDecl());
492 });
493 if (AllFunctions || (Found.empty() && !IsDependent)) {
494 // If lookup found any functions, or if this is a name that can only be
495 // used for a function, then strongly assume this is a function
496 // template-id.
497 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
500 Found.clear();
501 return false;
502 }
503 }
504
505 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
506 // If we did not find any names, and this is not a disambiguation, attempt
507 // to correct any typos.
508 DeclarationName Name = Found.getLookupName();
509 Found.clear();
510 // Simple filter callback that, for keywords, only accepts the C++ *_cast
511 DefaultFilterCCC FilterCCC{};
512 FilterCCC.WantTypeSpecifiers = false;
513 FilterCCC.WantExpressionKeywords = false;
514 FilterCCC.WantRemainingKeywords = false;
515 FilterCCC.WantCXXNamedCasts = true;
516 if (TypoCorrection Corrected =
517 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
518 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
519 if (auto *ND = Corrected.getFoundDecl())
520 Found.addDecl(ND);
522 if (Found.isAmbiguous()) {
523 Found.clear();
524 } else if (!Found.empty()) {
525 Found.setLookupName(Corrected.getCorrection());
526 if (LookupCtx) {
527 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
528 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
529 Name.getAsString() == CorrectedStr;
530 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
531 << Name << LookupCtx << DroppedSpecifier
532 << SS.getRange());
533 } else {
534 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
535 }
536 }
537 }
538 }
539
540 NamedDecl *ExampleLookupResult =
541 Found.empty() ? nullptr : Found.getRepresentativeDecl();
542 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
543 if (Found.empty()) {
544 if (IsDependent) {
545 Found.setNotFoundInCurrentInstantiation();
546 return false;
547 }
548
549 // If a 'template' keyword was used, a lookup that finds only non-template
550 // names is an error.
551 if (ExampleLookupResult && RequiredTemplate) {
552 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
553 << Found.getLookupName() << SS.getRange()
554 << RequiredTemplate.hasTemplateKeyword()
555 << RequiredTemplate.getTemplateKeywordLoc();
556 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
557 diag::note_template_kw_refers_to_non_template)
558 << Found.getLookupName();
559 return true;
560 }
561
562 return false;
563 }
564
565 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
567 // C++03 [basic.lookup.classref]p1:
568 // [...] If the lookup in the class of the object expression finds a
569 // template, the name is also looked up in the context of the entire
570 // postfix-expression and [...]
571 //
572 // Note: C++11 does not perform this second lookup.
573 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
575 FoundOuter.setTemplateNameLookup(true);
576 LookupName(FoundOuter, S);
577 // FIXME: We silently accept an ambiguous lookup here, in violation of
578 // [basic.lookup]/1.
579 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
580
581 NamedDecl *OuterTemplate;
582 if (FoundOuter.empty()) {
583 // - if the name is not found, the name found in the class of the
584 // object expression is used, otherwise
585 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
586 !(OuterTemplate =
587 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
588 // - if the name is found in the context of the entire
589 // postfix-expression and does not name a class template, the name
590 // found in the class of the object expression is used, otherwise
591 FoundOuter.clear();
592 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
593 // - if the name found is a class template, it must refer to the same
594 // entity as the one found in the class of the object expression,
595 // otherwise the program is ill-formed.
596 if (!Found.isSingleResult() ||
597 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
598 OuterTemplate->getCanonicalDecl()) {
599 Diag(Found.getNameLoc(),
600 diag::ext_nested_name_member_ref_lookup_ambiguous)
601 << Found.getLookupName()
602 << ObjectType;
603 Diag(Found.getRepresentativeDecl()->getLocation(),
604 diag::note_ambig_member_ref_object_type)
605 << ObjectType;
606 Diag(FoundOuter.getFoundDecl()->getLocation(),
607 diag::note_ambig_member_ref_scope);
608
609 // Recover by taking the template that we found in the object
610 // expression's type.
611 }
612 }
613 }
614
615 return false;
616}
617
621 if (TemplateName.isInvalid())
622 return;
623
624 DeclarationNameInfo NameInfo;
625 CXXScopeSpec SS;
626 LookupNameKind LookupKind;
627
628 DeclContext *LookupCtx = nullptr;
629 NamedDecl *Found = nullptr;
630 bool MissingTemplateKeyword = false;
631
632 // Figure out what name we looked up.
633 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
634 NameInfo = DRE->getNameInfo();
635 SS.Adopt(DRE->getQualifierLoc());
636 LookupKind = LookupOrdinaryName;
637 Found = DRE->getFoundDecl();
638 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
639 NameInfo = ME->getMemberNameInfo();
640 SS.Adopt(ME->getQualifierLoc());
641 LookupKind = LookupMemberName;
642 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
643 Found = ME->getMemberDecl();
644 } else if (auto *DSDRE =
645 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
646 NameInfo = DSDRE->getNameInfo();
647 SS.Adopt(DSDRE->getQualifierLoc());
648 MissingTemplateKeyword = true;
649 } else if (auto *DSME =
650 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
651 NameInfo = DSME->getMemberNameInfo();
652 SS.Adopt(DSME->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else {
655 llvm_unreachable("unexpected kind of potential template name");
656 }
657
658 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
659 // was missing.
660 if (MissingTemplateKeyword) {
661 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
662 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
663 return;
664 }
665
666 // Try to correct the name by looking for templates and C++ named casts.
667 struct TemplateCandidateFilter : CorrectionCandidateCallback {
668 Sema &S;
669 TemplateCandidateFilter(Sema &S) : S(S) {
670 WantTypeSpecifiers = false;
671 WantExpressionKeywords = false;
672 WantRemainingKeywords = false;
673 WantCXXNamedCasts = true;
674 };
675 bool ValidateCandidate(const TypoCorrection &Candidate) override {
676 if (auto *ND = Candidate.getCorrectionDecl())
677 return S.getAsTemplateNameDecl(ND);
678 return Candidate.isKeyword();
679 }
680
681 std::unique_ptr<CorrectionCandidateCallback> clone() override {
682 return std::make_unique<TemplateCandidateFilter>(*this);
683 }
684 };
685
686 DeclarationName Name = NameInfo.getName();
687 TemplateCandidateFilter CCC(*this);
688 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
689 CTK_ErrorRecovery, LookupCtx)) {
690 auto *ND = Corrected.getFoundDecl();
691 if (ND)
692 ND = getAsTemplateNameDecl(ND);
693 if (ND || Corrected.isKeyword()) {
694 if (LookupCtx) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 Name.getAsString() == CorrectedStr;
698 diagnoseTypo(Corrected,
699 PDiag(diag::err_non_template_in_member_template_id_suggest)
700 << Name << LookupCtx << DroppedSpecifier
701 << SS.getRange(), false);
702 } else {
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_template_id_suggest)
705 << Name, false);
706 }
707 if (Found)
708 Diag(Found->getLocation(),
709 diag::note_non_template_in_template_id_found);
710 return;
711 }
712 }
713
714 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
715 << Name << SourceRange(Less, Greater);
716 if (Found)
717 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
718}
719
722 SourceLocation TemplateKWLoc,
723 const DeclarationNameInfo &NameInfo,
724 bool isAddressOfOperand,
725 const TemplateArgumentListInfo *TemplateArgs) {
726 if (SS.isEmpty()) {
727 // FIXME: This codepath is only used by dependent unqualified names
728 // (e.g. a dependent conversion-function-id, or operator= once we support
729 // it). It doesn't quite do the right thing, and it will silently fail if
730 // getCurrentThisType() returns null.
731 QualType ThisType = getCurrentThisType();
732 if (ThisType.isNull())
733 return ExprError();
734
736 Context, /*Base=*/nullptr, ThisType,
737 /*IsArrow=*/!Context.getLangOpts().HLSL,
738 /*OperatorLoc=*/SourceLocation(),
739 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
740 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
741 }
742 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
743}
744
747 SourceLocation TemplateKWLoc,
748 const DeclarationNameInfo &NameInfo,
749 const TemplateArgumentListInfo *TemplateArgs) {
750 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
751 if (!SS.isValid())
752 return CreateRecoveryExpr(
753 SS.getBeginLoc(),
754 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
755
757 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
758 TemplateArgs);
759}
760
762 NamedDecl *Instantiation,
763 bool InstantiatedFromMember,
764 const NamedDecl *Pattern,
765 const NamedDecl *PatternDef,
767 bool Complain /*= true*/) {
768 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
769 isa<VarDecl>(Instantiation));
770
771 bool IsEntityBeingDefined = false;
772 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
773 IsEntityBeingDefined = TD->isBeingDefined();
774
775 if (PatternDef && !IsEntityBeingDefined) {
776 NamedDecl *SuggestedDef = nullptr;
777 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
778 &SuggestedDef,
779 /*OnlyNeedComplete*/ false)) {
780 // If we're allowed to diagnose this and recover, do so.
781 bool Recover = Complain && !isSFINAEContext();
782 if (Complain)
783 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
785 return !Recover;
786 }
787 return false;
788 }
789
790 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
791 return true;
792
793 QualType InstantiationTy;
794 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
795 InstantiationTy = Context.getTypeDeclType(TD);
796 if (PatternDef) {
797 Diag(PointOfInstantiation,
798 diag::err_template_instantiate_within_definition)
799 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
800 << InstantiationTy;
801 // Not much point in noting the template declaration here, since
802 // we're lexically inside it.
803 Instantiation->setInvalidDecl();
804 } else if (InstantiatedFromMember) {
805 if (isa<FunctionDecl>(Instantiation)) {
806 Diag(PointOfInstantiation,
807 diag::err_explicit_instantiation_undefined_member)
808 << /*member function*/ 1 << Instantiation->getDeclName()
809 << Instantiation->getDeclContext();
810 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
811 } else {
812 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
813 Diag(PointOfInstantiation,
814 diag::err_implicit_instantiate_member_undefined)
815 << InstantiationTy;
816 Diag(Pattern->getLocation(), diag::note_member_declared_at);
817 }
818 } else {
819 if (isa<FunctionDecl>(Instantiation)) {
820 Diag(PointOfInstantiation,
821 diag::err_explicit_instantiation_undefined_func_template)
822 << Pattern;
823 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
824 } else if (isa<TagDecl>(Instantiation)) {
825 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
826 << (TSK != TSK_ImplicitInstantiation)
827 << InstantiationTy;
828 NoteTemplateLocation(*Pattern);
829 } else {
830 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
831 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
832 Diag(PointOfInstantiation,
833 diag::err_explicit_instantiation_undefined_var_template)
834 << Instantiation;
835 Instantiation->setInvalidDecl();
836 } else
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*static data member*/ 2 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
842 }
843 }
844
845 // In general, Instantiation isn't marked invalid to get more than one
846 // error for multiple undefined instantiations. But the code that does
847 // explicit declaration -> explicit definition conversion can't handle
848 // invalid declarations, so mark as invalid in that case.
850 Instantiation->setInvalidDecl();
851 return true;
852}
853
855 bool SupportedForCompatibility) {
856 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
857
858 // C++23 [temp.local]p6:
859 // The name of a template-parameter shall not be bound to any following.
860 // declaration whose locus is contained by the scope to which the
861 // template-parameter belongs.
862 //
863 // When MSVC compatibility is enabled, the diagnostic is always a warning
864 // by default. Otherwise, it an error unless SupportedForCompatibility is
865 // true, in which case it is a default-to-error warning.
866 unsigned DiagId =
867 getLangOpts().MSVCCompat
868 ? diag::ext_template_param_shadow
869 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
870 : diag::err_template_param_shadow);
871 const auto *ND = cast<NamedDecl>(PrevDecl);
872 Diag(Loc, DiagId) << ND->getDeclName();
874}
875
877 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
878 D = Temp->getTemplatedDecl();
879 return Temp;
880 }
881 return nullptr;
882}
883
885 SourceLocation EllipsisLoc) const {
886 assert(Kind == Template &&
887 "Only template template arguments can be pack expansions here");
888 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
889 "Template template argument pack expansion without packs");
891 Result.EllipsisLoc = EllipsisLoc;
892 return Result;
893}
894
896 const ParsedTemplateArgument &Arg) {
897
898 switch (Arg.getKind()) {
900 TypeSourceInfo *DI;
901 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
902 if (!DI)
903 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
905 }
906
908 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
910 }
911
913 TemplateName Template = Arg.getAsTemplate().get();
914 TemplateArgument TArg;
915 if (Arg.getEllipsisLoc().isValid())
916 TArg = TemplateArgument(Template, std::optional<unsigned int>());
917 else
918 TArg = Template;
919 return TemplateArgumentLoc(
920 SemaRef.Context, TArg,
922 Arg.getLocation(), Arg.getEllipsisLoc());
923 }
924 }
925
926 llvm_unreachable("Unhandled parsed template argument");
927}
928
930 TemplateArgumentListInfo &TemplateArgs) {
931 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
932 TemplateArgs.addArgument(translateTemplateArgument(*this,
933 TemplateArgsIn[I]));
934}
935
938 const IdentifierInfo *Name) {
939 NamedDecl *PrevDecl =
941 RedeclarationKind::ForVisibleRedeclaration);
942 if (PrevDecl && PrevDecl->isTemplateParameter())
943 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
944}
945
947 TypeSourceInfo *TInfo;
949 if (T.isNull())
950 return ParsedTemplateArgument();
951 assert(TInfo && "template argument with no location");
952
953 // If we might have formed a deduced template specialization type, convert
954 // it to a template template argument.
955 if (getLangOpts().CPlusPlus17) {
956 TypeLoc TL = TInfo->getTypeLoc();
957 SourceLocation EllipsisLoc;
958 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
959 EllipsisLoc = PET.getEllipsisLoc();
960 TL = PET.getPatternLoc();
961 }
962
963 CXXScopeSpec SS;
964 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
965 SS.Adopt(ET.getQualifierLoc());
966 TL = ET.getNamedTypeLoc();
967 }
968
969 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
970 TemplateName Name = DTST.getTypePtr()->getTemplateName();
972 DTST.getTemplateNameLoc());
973 if (EllipsisLoc.isValid())
974 Result = Result.getTemplatePackExpansion(EllipsisLoc);
975 return Result;
976 }
977 }
978
979 // This is a normal type template argument. Note, if the type template
980 // argument is an injected-class-name for a template, it has a dual nature
981 // and can be used as either a type or a template. We handle that in
982 // convertTypeTemplateArgumentToTemplate.
985 TInfo->getTypeLoc().getBeginLoc());
986}
987
989 SourceLocation EllipsisLoc,
990 SourceLocation KeyLoc,
991 IdentifierInfo *ParamName,
992 SourceLocation ParamNameLoc,
993 unsigned Depth, unsigned Position,
994 SourceLocation EqualLoc,
995 ParsedType DefaultArg,
996 bool HasTypeConstraint) {
997 assert(S->isTemplateParamScope() &&
998 "Template type parameter not in template parameter scope!");
999
1000 bool IsParameterPack = EllipsisLoc.isValid();
1003 KeyLoc, ParamNameLoc, Depth, Position,
1004 ParamName, Typename, IsParameterPack,
1005 HasTypeConstraint);
1006 Param->setAccess(AS_public);
1007
1008 if (Param->isParameterPack())
1009 if (auto *CSI = getEnclosingLambdaOrBlock())
1010 CSI->LocalPacks.push_back(Param);
1011
1012 if (ParamName) {
1013 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1014
1015 // Add the template parameter into the current scope.
1016 S->AddDecl(Param);
1017 IdResolver.AddDecl(Param);
1018 }
1019
1020 // C++0x [temp.param]p9:
1021 // A default template-argument may be specified for any kind of
1022 // template-parameter that is not a template parameter pack.
1023 if (DefaultArg && IsParameterPack) {
1024 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1025 DefaultArg = nullptr;
1026 }
1027
1028 // Handle the default argument, if provided.
1029 if (DefaultArg) {
1030 TypeSourceInfo *DefaultTInfo;
1031 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1032
1033 assert(DefaultTInfo && "expected source information for type");
1034
1035 // Check for unexpanded parameter packs.
1036 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1038 return Param;
1039
1040 // Check the template argument itself.
1041 if (CheckTemplateArgument(DefaultTInfo)) {
1042 Param->setInvalidDecl();
1043 return Param;
1044 }
1045
1046 Param->setDefaultArgument(
1047 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1048 }
1049
1050 return Param;
1051}
1052
1053/// Convert the parser's template argument list representation into our form.
1056 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1057 TemplateId.RAngleLoc);
1058 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1059 TemplateId.NumArgs);
1060 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1061 return TemplateArgs;
1062}
1063
1065
1066 TemplateName TN = TypeConstr->Template.get();
1067 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1068
1069 // C++2a [temp.param]p4:
1070 // [...] The concept designated by a type-constraint shall be a type
1071 // concept ([temp.concept]).
1072 if (!CD->isTypeConcept()) {
1073 Diag(TypeConstr->TemplateNameLoc,
1074 diag::err_type_constraint_non_type_concept);
1075 return true;
1076 }
1077
1078 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1079 return true;
1080
1081 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1082
1083 if (!WereArgsSpecified &&
1085 Diag(TypeConstr->TemplateNameLoc,
1086 diag::err_type_constraint_missing_arguments)
1087 << CD;
1088 return true;
1089 }
1090 return false;
1091}
1092
1094 TemplateIdAnnotation *TypeConstr,
1095 TemplateTypeParmDecl *ConstrainedParameter,
1096 SourceLocation EllipsisLoc) {
1097 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1098 false);
1099}
1100
1102 TemplateIdAnnotation *TypeConstr,
1103 TemplateTypeParmDecl *ConstrainedParameter,
1104 SourceLocation EllipsisLoc,
1105 bool AllowUnexpandedPack) {
1106
1107 if (CheckTypeConstraint(TypeConstr))
1108 return true;
1109
1110 TemplateName TN = TypeConstr->Template.get();
1111 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1113
1114 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1115 TypeConstr->TemplateNameLoc);
1116
1117 TemplateArgumentListInfo TemplateArgs;
1118 if (TypeConstr->LAngleLoc.isValid()) {
1119 TemplateArgs =
1120 makeTemplateArgumentListInfo(*this, *TypeConstr);
1121
1122 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1123 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1125 return true;
1126 }
1127 }
1128 }
1129 return AttachTypeConstraint(
1131 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1132 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1133 ConstrainedParameter, Context.getTypeDeclType(ConstrainedParameter),
1134 EllipsisLoc);
1135}
1136
1137template <typename ArgumentLocAppender>
1140 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1141 SourceLocation RAngleLoc, QualType ConstrainedType,
1142 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1143 SourceLocation EllipsisLoc) {
1144
1145 TemplateArgumentListInfo ConstraintArgs;
1146 ConstraintArgs.addArgument(
1148 /*NTTPType=*/QualType(), ParamNameLoc));
1149
1150 ConstraintArgs.setRAngleLoc(RAngleLoc);
1151 ConstraintArgs.setLAngleLoc(LAngleLoc);
1152 Appender(ConstraintArgs);
1153
1154 // C++2a [temp.param]p4:
1155 // [...] This constraint-expression E is called the immediately-declared
1156 // constraint of T. [...]
1157 CXXScopeSpec SS;
1158 SS.Adopt(NS);
1159 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1160 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1161 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1162 &ConstraintArgs);
1163 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1164 return ImmediatelyDeclaredConstraint;
1165
1166 // C++2a [temp.param]p4:
1167 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1168 //
1169 // We have the following case:
1170 //
1171 // template<typename T> concept C1 = true;
1172 // template<C1... T> struct s1;
1173 //
1174 // The constraint: (C1<T> && ...)
1175 //
1176 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1177 // any unqualified lookups for 'operator&&' here.
1178 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1179 /*LParenLoc=*/SourceLocation(),
1180 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1181 EllipsisLoc, /*RHS=*/nullptr,
1182 /*RParenLoc=*/SourceLocation(),
1183 /*NumExpansions=*/std::nullopt);
1184}
1185
1187 DeclarationNameInfo NameInfo,
1188 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1189 const TemplateArgumentListInfo *TemplateArgs,
1190 TemplateTypeParmDecl *ConstrainedParameter,
1191 QualType ConstrainedType,
1192 SourceLocation EllipsisLoc) {
1193 // C++2a [temp.param]p4:
1194 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1195 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1196 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1198 *TemplateArgs) : nullptr;
1199
1200 QualType ParamAsArgument = ConstrainedType;
1201
1202 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1203 *this, NS, NameInfo, NamedConcept, FoundDecl,
1204 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1205 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1206 ParamAsArgument, ConstrainedParameter->getLocation(),
1207 [&](TemplateArgumentListInfo &ConstraintArgs) {
1208 if (TemplateArgs)
1209 for (const auto &ArgLoc : TemplateArgs->arguments())
1210 ConstraintArgs.addArgument(ArgLoc);
1211 },
1212 EllipsisLoc);
1213 if (ImmediatelyDeclaredConstraint.isInvalid())
1214 return true;
1215
1216 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1217 /*TemplateKWLoc=*/SourceLocation{},
1218 /*ConceptNameInfo=*/NameInfo,
1219 /*FoundDecl=*/FoundDecl,
1220 /*NamedConcept=*/NamedConcept,
1221 /*ArgsWritten=*/ArgsAsWritten);
1222 ConstrainedParameter->setTypeConstraint(CL,
1223 ImmediatelyDeclaredConstraint.get());
1224 return false;
1225}
1226
1228 NonTypeTemplateParmDecl *NewConstrainedParm,
1229 NonTypeTemplateParmDecl *OrigConstrainedParm,
1230 SourceLocation EllipsisLoc) {
1231 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1233 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1234 diag::err_unsupported_placeholder_constraint)
1235 << NewConstrainedParm->getTypeSourceInfo()
1236 ->getTypeLoc()
1237 .getSourceRange();
1238 return true;
1239 }
1240 // FIXME: Concepts: This should be the type of the placeholder, but this is
1241 // unclear in the wording right now.
1242 DeclRefExpr *Ref =
1243 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1244 VK_PRValue, OrigConstrainedParm->getLocation());
1245 if (!Ref)
1246 return true;
1247 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1249 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1251 OrigConstrainedParm->getLocation(),
1252 [&](TemplateArgumentListInfo &ConstraintArgs) {
1253 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1254 ConstraintArgs.addArgument(TL.getArgLoc(I));
1255 },
1256 EllipsisLoc);
1257 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1258 !ImmediatelyDeclaredConstraint.isUsable())
1259 return true;
1260
1261 NewConstrainedParm->setPlaceholderTypeConstraint(
1262 ImmediatelyDeclaredConstraint.get());
1263 return false;
1264}
1265
1268 if (TSI->getType()->isUndeducedType()) {
1269 // C++17 [temp.dep.expr]p3:
1270 // An id-expression is type-dependent if it contains
1271 // - an identifier associated by name lookup with a non-type
1272 // template-parameter declared with a type that contains a
1273 // placeholder type (7.1.7.4),
1275 }
1276
1278}
1279
1281 if (T->isDependentType())
1282 return false;
1283
1284 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1285 return true;
1286
1287 if (T->isStructuralType())
1288 return false;
1289
1290 // Structural types are required to be object types or lvalue references.
1291 if (T->isRValueReferenceType()) {
1292 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1293 return true;
1294 }
1295
1296 // Don't mention structural types in our diagnostic prior to C++20. Also,
1297 // there's not much more we can say about non-scalar non-class types --
1298 // because we can't see functions or arrays here, those can only be language
1299 // extensions.
1300 if (!getLangOpts().CPlusPlus20 ||
1301 (!T->isScalarType() && !T->isRecordType())) {
1302 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1303 return true;
1304 }
1305
1306 // Structural types are required to be literal types.
1307 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1308 return true;
1309
1310 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1311
1312 // Drill down into the reason why the class is non-structural.
1313 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1314 // All members are required to be public and non-mutable, and can't be of
1315 // rvalue reference type. Check these conditions first to prefer a "local"
1316 // reason over a more distant one.
1317 for (const FieldDecl *FD : RD->fields()) {
1318 if (FD->getAccess() != AS_public) {
1319 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1320 return true;
1321 }
1322 if (FD->isMutable()) {
1323 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1324 return true;
1325 }
1326 if (FD->getType()->isRValueReferenceType()) {
1327 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1328 << T;
1329 return true;
1330 }
1331 }
1332
1333 // All bases are required to be public.
1334 for (const auto &BaseSpec : RD->bases()) {
1335 if (BaseSpec.getAccessSpecifier() != AS_public) {
1336 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1337 << T << 1;
1338 return true;
1339 }
1340 }
1341
1342 // All subobjects are required to be of structural types.
1343 SourceLocation SubLoc;
1344 QualType SubType;
1345 int Kind = -1;
1346
1347 for (const FieldDecl *FD : RD->fields()) {
1348 QualType T = Context.getBaseElementType(FD->getType());
1349 if (!T->isStructuralType()) {
1350 SubLoc = FD->getLocation();
1351 SubType = T;
1352 Kind = 0;
1353 break;
1354 }
1355 }
1356
1357 if (Kind == -1) {
1358 for (const auto &BaseSpec : RD->bases()) {
1359 QualType T = BaseSpec.getType();
1360 if (!T->isStructuralType()) {
1361 SubLoc = BaseSpec.getBaseTypeLoc();
1362 SubType = T;
1363 Kind = 1;
1364 break;
1365 }
1366 }
1367 }
1368
1369 assert(Kind != -1 && "couldn't find reason why type is not structural");
1370 Diag(SubLoc, diag::note_not_structural_subobject)
1371 << T << Kind << SubType;
1372 T = SubType;
1373 RD = T->getAsCXXRecordDecl();
1374 }
1375
1376 return true;
1377}
1378
1381 // We don't allow variably-modified types as the type of non-type template
1382 // parameters.
1383 if (T->isVariablyModifiedType()) {
1384 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1385 << T;
1386 return QualType();
1387 }
1388
1389 // C++ [temp.param]p4:
1390 //
1391 // A non-type template-parameter shall have one of the following
1392 // (optionally cv-qualified) types:
1393 //
1394 // -- integral or enumeration type,
1396 // -- pointer to object or pointer to function,
1397 T->isPointerType() ||
1398 // -- lvalue reference to object or lvalue reference to function,
1400 // -- pointer to member,
1402 // -- std::nullptr_t, or
1403 T->isNullPtrType() ||
1404 // -- a type that contains a placeholder type.
1405 T->isUndeducedType()) {
1406 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1407 // are ignored when determining its type.
1408 return T.getUnqualifiedType();
1409 }
1410
1411 // C++ [temp.param]p8:
1412 //
1413 // A non-type template-parameter of type "array of T" or
1414 // "function returning T" is adjusted to be of type "pointer to
1415 // T" or "pointer to function returning T", respectively.
1416 if (T->isArrayType() || T->isFunctionType())
1417 return Context.getDecayedType(T);
1418
1419 // If T is a dependent type, we can't do the check now, so we
1420 // assume that it is well-formed. Note that stripping off the
1421 // qualifiers here is not really correct if T turns out to be
1422 // an array type, but we'll recompute the type everywhere it's
1423 // used during instantiation, so that should be OK. (Using the
1424 // qualified type is equally wrong.)
1425 if (T->isDependentType())
1426 return T.getUnqualifiedType();
1427
1428 // C++20 [temp.param]p6:
1429 // -- a structural type
1431 return QualType();
1432
1433 if (!getLangOpts().CPlusPlus20) {
1434 // FIXME: Consider allowing structural types as an extension in C++17. (In
1435 // earlier language modes, the template argument evaluation rules are too
1436 // inflexible.)
1437 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1438 return QualType();
1439 }
1440
1441 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1442 return T.getUnqualifiedType();
1443}
1444
1446 unsigned Depth,
1447 unsigned Position,
1448 SourceLocation EqualLoc,
1449 Expr *Default) {
1451
1452 // Check that we have valid decl-specifiers specified.
1453 auto CheckValidDeclSpecifiers = [this, &D] {
1454 // C++ [temp.param]
1455 // p1
1456 // template-parameter:
1457 // ...
1458 // parameter-declaration
1459 // p2
1460 // ... A storage class shall not be specified in a template-parameter
1461 // declaration.
1462 // [dcl.typedef]p1:
1463 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1464 // of a parameter-declaration
1465 const DeclSpec &DS = D.getDeclSpec();
1466 auto EmitDiag = [this](SourceLocation Loc) {
1467 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1469 };
1471 EmitDiag(DS.getStorageClassSpecLoc());
1472
1474 EmitDiag(DS.getThreadStorageClassSpecLoc());
1475
1476 // [dcl.inline]p1:
1477 // The inline specifier can be applied only to the declaration or
1478 // definition of a variable or function.
1479
1480 if (DS.isInlineSpecified())
1481 EmitDiag(DS.getInlineSpecLoc());
1482
1483 // [dcl.constexpr]p1:
1484 // The constexpr specifier shall be applied only to the definition of a
1485 // variable or variable template or the declaration of a function or
1486 // function template.
1487
1488 if (DS.hasConstexprSpecifier())
1489 EmitDiag(DS.getConstexprSpecLoc());
1490
1491 // [dcl.fct.spec]p1:
1492 // Function-specifiers can be used only in function declarations.
1493
1494 if (DS.isVirtualSpecified())
1495 EmitDiag(DS.getVirtualSpecLoc());
1496
1497 if (DS.hasExplicitSpecifier())
1498 EmitDiag(DS.getExplicitSpecLoc());
1499
1500 if (DS.isNoreturnSpecified())
1501 EmitDiag(DS.getNoreturnSpecLoc());
1502 };
1503
1504 CheckValidDeclSpecifiers();
1505
1506 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1507 if (isa<AutoType>(T))
1508 Diag(D.getIdentifierLoc(),
1509 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1510 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1511
1512 assert(S->isTemplateParamScope() &&
1513 "Non-type template parameter not in template parameter scope!");
1514 bool Invalid = false;
1515
1516 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1517 if (T.isNull()) {
1518 T = Context.IntTy; // Recover with an 'int' type.
1519 Invalid = true;
1520 }
1521
1523
1524 const IdentifierInfo *ParamName = D.getIdentifier();
1525 bool IsParameterPack = D.hasEllipsis();
1528 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1529 TInfo);
1530 Param->setAccess(AS_public);
1531
1533 if (TL.isConstrained()) {
1534 if (D.getEllipsisLoc().isInvalid() &&
1536 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1537 for (auto &Loc :
1538 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1541 }
1542 if (!Invalid &&
1543 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1544 Invalid = true;
1545 }
1546
1547 if (Invalid)
1548 Param->setInvalidDecl();
1549
1550 if (Param->isParameterPack())
1551 if (auto *CSI = getEnclosingLambdaOrBlock())
1552 CSI->LocalPacks.push_back(Param);
1553
1554 if (ParamName) {
1555 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1556 ParamName);
1557
1558 // Add the template parameter into the current scope.
1559 S->AddDecl(Param);
1560 IdResolver.AddDecl(Param);
1561 }
1562
1563 // C++0x [temp.param]p9:
1564 // A default template-argument may be specified for any kind of
1565 // template-parameter that is not a template parameter pack.
1566 if (Default && IsParameterPack) {
1567 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1568 Default = nullptr;
1569 }
1570
1571 // Check the well-formedness of the default template argument, if provided.
1572 if (Default) {
1573 // Check for unexpanded parameter packs.
1575 return Param;
1576
1577 Param->setDefaultArgument(
1579 QualType(), SourceLocation()));
1580 }
1581
1582 return Param;
1583}
1584
1586 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1587 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1588 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1590 assert(S->isTemplateParamScope() &&
1591 "Template template parameter not in template parameter scope!");
1592
1593 // Construct the parameter object.
1594 bool IsParameterPack = EllipsisLoc.isValid();
1597 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1598 Name, Typename, Params);
1599 Param->setAccess(AS_public);
1600
1601 if (Param->isParameterPack())
1602 if (auto *LSI = getEnclosingLambdaOrBlock())
1603 LSI->LocalPacks.push_back(Param);
1604
1605 // If the template template parameter has a name, then link the identifier
1606 // into the scope and lookup mechanisms.
1607 if (Name) {
1608 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1609
1610 S->AddDecl(Param);
1611 IdResolver.AddDecl(Param);
1612 }
1613
1614 if (Params->size() == 0) {
1615 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1616 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1617 Param->setInvalidDecl();
1618 }
1619
1620 // C++0x [temp.param]p9:
1621 // A default template-argument may be specified for any kind of
1622 // template-parameter that is not a template parameter pack.
1623 if (IsParameterPack && !Default.isInvalid()) {
1624 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1626 }
1627
1628 if (!Default.isInvalid()) {
1629 // Check only that we have a template template argument. We don't want to
1630 // try to check well-formedness now, because our template template parameter
1631 // might have dependent types in its template parameters, which we wouldn't
1632 // be able to match now.
1633 //
1634 // If none of the template template parameter's template arguments mention
1635 // other template parameters, we could actually perform more checking here.
1636 // However, it isn't worth doing.
1638 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1639 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1640 << DefaultArg.getSourceRange();
1641 return Param;
1642 }
1643
1644 // Check for unexpanded parameter packs.
1646 DefaultArg.getArgument().getAsTemplate(),
1648 return Param;
1649
1650 Param->setDefaultArgument(Context, DefaultArg);
1651 }
1652
1653 return Param;
1654}
1655
1656namespace {
1657class ConstraintRefersToContainingTemplateChecker
1658 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1659 bool Result = false;
1660 const FunctionDecl *Friend = nullptr;
1661 unsigned TemplateDepth = 0;
1662
1663 // Check a record-decl that we've seen to see if it is a lexical parent of the
1664 // Friend, likely because it was referred to without its template arguments.
1665 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1666 CheckingRD = CheckingRD->getMostRecentDecl();
1667 if (!CheckingRD->isTemplated())
1668 return;
1669
1670 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1671 DC && !DC->isFileContext(); DC = DC->getParent())
1672 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1673 if (CheckingRD == RD->getMostRecentDecl())
1674 Result = true;
1675 }
1676
1677 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1678 if (D->getDepth() < TemplateDepth)
1679 Result = true;
1680
1681 // Necessary because the type of the NTTP might be what refers to the parent
1682 // constriant.
1683 TransformType(D->getType());
1684 }
1685
1686public:
1688
1689 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1690 const FunctionDecl *Friend,
1691 unsigned TemplateDepth)
1692 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1693 bool getResult() const { return Result; }
1694
1695 // This should be the only template parm type that we have to deal with.
1696 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1697 // FunctionParmPackExpr are all partially substituted, which cannot happen
1698 // with concepts at this point in translation.
1699 using inherited::TransformTemplateTypeParmType;
1700 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1701 TemplateTypeParmTypeLoc TL, bool) {
1702 if (TL.getDecl()->getDepth() < TemplateDepth)
1703 Result = true;
1704 return inherited::TransformTemplateTypeParmType(
1705 TLB, TL,
1706 /*SuppressObjCLifetime=*/false);
1707 }
1708
1709 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1710 if (!D)
1711 return D;
1712 // FIXME : This is possibly an incomplete list, but it is unclear what other
1713 // Decl kinds could be used to refer to the template parameters. This is a
1714 // best guess so far based on examples currently available, but the
1715 // unreachable should catch future instances/cases.
1716 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1717 TransformType(TD->getUnderlyingType());
1718 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1719 CheckNonTypeTemplateParmDecl(NTTPD);
1720 else if (auto *VD = dyn_cast<ValueDecl>(D))
1721 TransformType(VD->getType());
1722 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1723 TransformTemplateParameterList(TD->getTemplateParameters());
1724 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1725 CheckIfContainingRecord(RD);
1726 else if (isa<NamedDecl>(D)) {
1727 // No direct types to visit here I believe.
1728 } else
1729 llvm_unreachable("Don't know how to handle this declaration type yet");
1730 return D;
1731 }
1732};
1733} // namespace
1734
1736 const FunctionDecl *Friend, unsigned TemplateDepth,
1737 const Expr *Constraint) {
1738 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1739 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1740 TemplateDepth);
1741 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1742 return Checker.getResult();
1743}
1744
1747 SourceLocation ExportLoc,
1748 SourceLocation TemplateLoc,
1749 SourceLocation LAngleLoc,
1750 ArrayRef<NamedDecl *> Params,
1751 SourceLocation RAngleLoc,
1752 Expr *RequiresClause) {
1753 if (ExportLoc.isValid())
1754 Diag(ExportLoc, diag::warn_template_export_unsupported);
1755
1756 for (NamedDecl *P : Params)
1758
1760 Context, TemplateLoc, LAngleLoc,
1761 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1762}
1763
1765 const CXXScopeSpec &SS) {
1766 if (SS.isSet())
1767 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1768}
1769
1770// Returns the template parameter list with all default template argument
1771// information.
1773 // Make sure we get the template parameter list from the most
1774 // recent declaration, since that is the only one that is guaranteed to
1775 // have all the default template argument information.
1776 Decl *D = TD->getMostRecentDecl();
1777 // C++11 N3337 [temp.param]p12:
1778 // A default template argument shall not be specified in a friend class
1779 // template declaration.
1780 //
1781 // Skip past friend *declarations* because they are not supposed to contain
1782 // default template arguments. Moreover, these declarations may introduce
1783 // template parameters living in different template depths than the
1784 // corresponding template parameters in TD, causing unmatched constraint
1785 // substitution.
1786 //
1787 // FIXME: Diagnose such cases within a class template:
1788 // template <class T>
1789 // struct S {
1790 // template <class = void> friend struct C;
1791 // };
1792 // template struct S<int>;
1794 D->getPreviousDecl())
1795 D = D->getPreviousDecl();
1796 return cast<TemplateDecl>(D)->getTemplateParameters();
1797}
1798
1800 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1801 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1802 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1803 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1804 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1805 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1806 assert(TemplateParams && TemplateParams->size() > 0 &&
1807 "No template parameters");
1808 assert(TUK != TagUseKind::Reference &&
1809 "Can only declare or define class templates");
1810 bool Invalid = false;
1811
1812 // Check that we can declare a template here.
1813 if (CheckTemplateDeclScope(S, TemplateParams))
1814 return true;
1815
1817 assert(Kind != TagTypeKind::Enum &&
1818 "can't build template of enumerated type");
1819
1820 // There is no such thing as an unnamed class template.
1821 if (!Name) {
1822 Diag(KWLoc, diag::err_template_unnamed_class);
1823 return true;
1824 }
1825
1826 // Find any previous declaration with this name. For a friend with no
1827 // scope explicitly specified, we only look for tag declarations (per
1828 // C++11 [basic.lookup.elab]p2).
1829 DeclContext *SemanticContext;
1830 LookupResult Previous(*this, Name, NameLoc,
1831 (SS.isEmpty() && TUK == TagUseKind::Friend)
1835 if (SS.isNotEmpty() && !SS.isInvalid()) {
1836 SemanticContext = computeDeclContext(SS, true);
1837 if (!SemanticContext) {
1838 // FIXME: Horrible, horrible hack! We can't currently represent this
1839 // in the AST, and historically we have just ignored such friend
1840 // class templates, so don't complain here.
1841 Diag(NameLoc, TUK == TagUseKind::Friend
1842 ? diag::warn_template_qualified_friend_ignored
1843 : diag::err_template_qualified_declarator_no_match)
1844 << SS.getScopeRep() << SS.getRange();
1845 return TUK != TagUseKind::Friend;
1846 }
1847
1848 if (RequireCompleteDeclContext(SS, SemanticContext))
1849 return true;
1850
1851 // If we're adding a template to a dependent context, we may need to
1852 // rebuilding some of the types used within the template parameter list,
1853 // now that we know what the current instantiation is.
1854 if (SemanticContext->isDependentContext()) {
1855 ContextRAII SavedContext(*this, SemanticContext);
1857 Invalid = true;
1858 }
1859
1860 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1861 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1862 /*TemplateId-*/ nullptr,
1863 /*IsMemberSpecialization*/ false);
1864
1865 LookupQualifiedName(Previous, SemanticContext);
1866 } else {
1867 SemanticContext = CurContext;
1868
1869 // C++14 [class.mem]p14:
1870 // If T is the name of a class, then each of the following shall have a
1871 // name different from T:
1872 // -- every member template of class T
1873 if (TUK != TagUseKind::Friend &&
1874 DiagnoseClassNameShadow(SemanticContext,
1875 DeclarationNameInfo(Name, NameLoc)))
1876 return true;
1877
1878 LookupName(Previous, S);
1879 }
1880
1881 if (Previous.isAmbiguous())
1882 return true;
1883
1884 // Let the template parameter scope enter the lookup chain of the current
1885 // class template. For example, given
1886 //
1887 // namespace ns {
1888 // template <class> bool Param = false;
1889 // template <class T> struct N;
1890 // }
1891 //
1892 // template <class Param> struct ns::N { void foo(Param); };
1893 //
1894 // When we reference Param inside the function parameter list, our name lookup
1895 // chain for it should be like:
1896 // FunctionScope foo
1897 // -> RecordScope N
1898 // -> TemplateParamScope (where we will find Param)
1899 // -> NamespaceScope ns
1900 //
1901 // See also CppLookupName().
1902 if (S->isTemplateParamScope())
1903 EnterTemplatedContext(S, SemanticContext);
1904
1905 NamedDecl *PrevDecl = nullptr;
1906 if (Previous.begin() != Previous.end())
1907 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1908
1909 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1910 // Maybe we will complain about the shadowed template parameter.
1911 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1912 // Just pretend that we didn't see the previous declaration.
1913 PrevDecl = nullptr;
1914 }
1915
1916 // If there is a previous declaration with the same name, check
1917 // whether this is a valid redeclaration.
1918 ClassTemplateDecl *PrevClassTemplate =
1919 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1920
1921 // We may have found the injected-class-name of a class template,
1922 // class template partial specialization, or class template specialization.
1923 // In these cases, grab the template that is being defined or specialized.
1924 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1925 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1926 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1927 PrevClassTemplate
1928 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1929 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1930 PrevClassTemplate
1931 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1932 ->getSpecializedTemplate();
1933 }
1934 }
1935
1936 if (TUK == TagUseKind::Friend) {
1937 // C++ [namespace.memdef]p3:
1938 // [...] When looking for a prior declaration of a class or a function
1939 // declared as a friend, and when the name of the friend class or
1940 // function is neither a qualified name nor a template-id, scopes outside
1941 // the innermost enclosing namespace scope are not considered.
1942 if (!SS.isSet()) {
1943 DeclContext *OutermostContext = CurContext;
1944 while (!OutermostContext->isFileContext())
1945 OutermostContext = OutermostContext->getLookupParent();
1946
1947 if (PrevDecl &&
1948 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1949 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1950 SemanticContext = PrevDecl->getDeclContext();
1951 } else {
1952 // Declarations in outer scopes don't matter. However, the outermost
1953 // context we computed is the semantic context for our new
1954 // declaration.
1955 PrevDecl = PrevClassTemplate = nullptr;
1956 SemanticContext = OutermostContext;
1957
1958 // Check that the chosen semantic context doesn't already contain a
1959 // declaration of this name as a non-tag type.
1961 DeclContext *LookupContext = SemanticContext;
1962 while (LookupContext->isTransparentContext())
1963 LookupContext = LookupContext->getLookupParent();
1964 LookupQualifiedName(Previous, LookupContext);
1965
1966 if (Previous.isAmbiguous())
1967 return true;
1968
1969 if (Previous.begin() != Previous.end())
1970 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1971 }
1972 }
1973 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1974 SemanticContext, S, SS.isValid()))
1975 PrevDecl = PrevClassTemplate = nullptr;
1976
1977 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1978 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1979 if (SS.isEmpty() &&
1980 !(PrevClassTemplate &&
1981 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1982 SemanticContext->getRedeclContext()))) {
1983 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1984 Diag(Shadow->getTargetDecl()->getLocation(),
1985 diag::note_using_decl_target);
1986 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1987 // Recover by ignoring the old declaration.
1988 PrevDecl = PrevClassTemplate = nullptr;
1989 }
1990 }
1991
1992 if (PrevClassTemplate) {
1993 // Ensure that the template parameter lists are compatible. Skip this check
1994 // for a friend in a dependent context: the template parameter list itself
1995 // could be dependent.
1996 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1998 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1999 : CurContext,
2000 CurContext, KWLoc),
2001 TemplateParams, PrevClassTemplate,
2002 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2004 return true;
2005
2006 // C++ [temp.class]p4:
2007 // In a redeclaration, partial specialization, explicit
2008 // specialization or explicit instantiation of a class template,
2009 // the class-key shall agree in kind with the original class
2010 // template declaration (7.1.5.3).
2011 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2013 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2014 Diag(KWLoc, diag::err_use_with_wrong_tag)
2015 << Name
2016 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2017 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2018 Kind = PrevRecordDecl->getTagKind();
2019 }
2020
2021 // Check for redefinition of this class template.
2022 if (TUK == TagUseKind::Definition) {
2023 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2024 // If we have a prior definition that is not visible, treat this as
2025 // simply making that previous definition visible.
2026 NamedDecl *Hidden = nullptr;
2027 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2028 SkipBody->ShouldSkip = true;
2029 SkipBody->Previous = Def;
2030 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2031 assert(Tmpl && "original definition of a class template is not a "
2032 "class template?");
2035 } else {
2036 Diag(NameLoc, diag::err_redefinition) << Name;
2037 Diag(Def->getLocation(), diag::note_previous_definition);
2038 // FIXME: Would it make sense to try to "forget" the previous
2039 // definition, as part of error recovery?
2040 return true;
2041 }
2042 }
2043 }
2044 } else if (PrevDecl) {
2045 // C++ [temp]p5:
2046 // A class template shall not have the same name as any other
2047 // template, class, function, object, enumeration, enumerator,
2048 // namespace, or type in the same scope (3.3), except as specified
2049 // in (14.5.4).
2050 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2051 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2052 return true;
2053 }
2054
2055 // Check the template parameter list of this declaration, possibly
2056 // merging in the template parameter list from the previous class
2057 // template declaration. Skip this check for a friend in a dependent
2058 // context, because the template parameter list might be dependent.
2059 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2061 TemplateParams,
2062 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2063 : nullptr,
2064 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2065 SemanticContext->isDependentContext())
2069 SkipBody))
2070 Invalid = true;
2071
2072 if (SS.isSet()) {
2073 // If the name of the template was qualified, we must be defining the
2074 // template out-of-line.
2075 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2076 Diag(NameLoc, TUK == TagUseKind::Friend
2077 ? diag::err_friend_decl_does_not_match
2078 : diag::err_member_decl_does_not_match)
2079 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2080 Invalid = true;
2081 }
2082 }
2083
2084 // If this is a templated friend in a dependent context we should not put it
2085 // on the redecl chain. In some cases, the templated friend can be the most
2086 // recent declaration tricking the template instantiator to make substitutions
2087 // there.
2088 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2089 bool ShouldAddRedecl =
2091
2092 CXXRecordDecl *NewClass =
2093 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2094 PrevClassTemplate && ShouldAddRedecl ?
2095 PrevClassTemplate->getTemplatedDecl() : nullptr,
2096 /*DelayTypeCreation=*/true);
2097 SetNestedNameSpecifier(*this, NewClass, SS);
2098 if (NumOuterTemplateParamLists > 0)
2100 Context,
2101 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2102
2103 // Add alignment attributes if necessary; these attributes are checked when
2104 // the ASTContext lays out the structure.
2105 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2108 }
2109
2110 ClassTemplateDecl *NewTemplate
2111 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2112 DeclarationName(Name), TemplateParams,
2113 NewClass);
2114
2115 if (ShouldAddRedecl)
2116 NewTemplate->setPreviousDecl(PrevClassTemplate);
2117
2118 NewClass->setDescribedClassTemplate(NewTemplate);
2119
2120 if (ModulePrivateLoc.isValid())
2121 NewTemplate->setModulePrivate();
2122
2123 // Build the type for the class template declaration now.
2125 T = Context.getInjectedClassNameType(NewClass, T);
2126 assert(T->isDependentType() && "Class template type is not dependent?");
2127 (void)T;
2128
2129 // If we are providing an explicit specialization of a member that is a
2130 // class template, make a note of that.
2131 if (PrevClassTemplate &&
2132 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2133 PrevClassTemplate->setMemberSpecialization();
2134
2135 // Set the access specifier.
2136 if (!Invalid && TUK != TagUseKind::Friend &&
2137 NewTemplate->getDeclContext()->isRecord())
2138 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2139
2140 // Set the lexical context of these templates
2142 NewTemplate->setLexicalDeclContext(CurContext);
2143
2144 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2145 NewClass->startDefinition();
2146
2147 ProcessDeclAttributeList(S, NewClass, Attr);
2148 ProcessAPINotes(NewClass);
2149
2150 if (PrevClassTemplate)
2151 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2152
2156
2157 if (TUK != TagUseKind::Friend) {
2158 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2159 Scope *Outer = S;
2160 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2161 Outer = Outer->getParent();
2162 PushOnScopeChains(NewTemplate, Outer);
2163 } else {
2164 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2165 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2166 NewClass->setAccess(PrevClassTemplate->getAccess());
2167 }
2168
2169 NewTemplate->setObjectOfFriendDecl();
2170
2171 // Friend templates are visible in fairly strange ways.
2173 DeclContext *DC = SemanticContext->getRedeclContext();
2174 DC->makeDeclVisibleInContext(NewTemplate);
2175 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2176 PushOnScopeChains(NewTemplate, EnclosingScope,
2177 /* AddToContext = */ false);
2178 }
2179
2181 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2182 Friend->setAccess(AS_public);
2184 }
2185
2186 if (PrevClassTemplate)
2187 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2188
2189 if (Invalid) {
2190 NewTemplate->setInvalidDecl();
2191 NewClass->setInvalidDecl();
2192 }
2193
2194 ActOnDocumentableDecl(NewTemplate);
2195
2196 if (SkipBody && SkipBody->ShouldSkip)
2197 return SkipBody->Previous;
2198
2199 return NewTemplate;
2200}
2201
2202/// Diagnose the presence of a default template argument on a
2203/// template parameter, which is ill-formed in certain contexts.
2204///
2205/// \returns true if the default template argument should be dropped.
2208 SourceLocation ParamLoc,
2209 SourceRange DefArgRange) {
2210 switch (TPC) {
2214 return false;
2215
2218 // C++ [temp.param]p9:
2219 // A default template-argument shall not be specified in a
2220 // function template declaration or a function template
2221 // definition [...]
2222 // If a friend function template declaration specifies a default
2223 // template-argument, that declaration shall be a definition and shall be
2224 // the only declaration of the function template in the translation unit.
2225 // (C++98/03 doesn't have this wording; see DR226).
2226 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2227 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2228 : diag::ext_template_parameter_default_in_function_template)
2229 << DefArgRange;
2230 return false;
2231
2233 // C++0x [temp.param]p9:
2234 // A default template-argument shall not be specified in the
2235 // template-parameter-lists of the definition of a member of a
2236 // class template that appears outside of the member's class.
2237 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2238 << DefArgRange;
2239 return true;
2240
2243 // C++ [temp.param]p9:
2244 // A default template-argument shall not be specified in a
2245 // friend template declaration.
2246 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2247 << DefArgRange;
2248 return true;
2249
2250 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2251 // for friend function templates if there is only a single
2252 // declaration (and it is a definition). Strange!
2253 }
2254
2255 llvm_unreachable("Invalid TemplateParamListContext!");
2256}
2257
2258/// Check for unexpanded parameter packs within the template parameters
2259/// of a template template parameter, recursively.
2262 // A template template parameter which is a parameter pack is also a pack
2263 // expansion.
2264 if (TTP->isParameterPack())
2265 return false;
2266
2268 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2269 NamedDecl *P = Params->getParam(I);
2270 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2271 if (!TTP->isParameterPack())
2272 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2273 if (TC->hasExplicitTemplateArgs())
2274 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2277 return true;
2278 continue;
2279 }
2280
2281 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2282 if (!NTTP->isParameterPack() &&
2283 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2284 NTTP->getTypeSourceInfo(),
2286 return true;
2287
2288 continue;
2289 }
2290
2291 if (TemplateTemplateParmDecl *InnerTTP
2292 = dyn_cast<TemplateTemplateParmDecl>(P))
2293 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2294 return true;
2295 }
2296
2297 return false;
2298}
2299
2301 TemplateParameterList *OldParams,
2303 SkipBodyInfo *SkipBody) {
2304 bool Invalid = false;
2305
2306 // C++ [temp.param]p10:
2307 // The set of default template-arguments available for use with a
2308 // template declaration or definition is obtained by merging the
2309 // default arguments from the definition (if in scope) and all
2310 // declarations in scope in the same way default function
2311 // arguments are (8.3.6).
2312 bool SawDefaultArgument = false;
2313 SourceLocation PreviousDefaultArgLoc;
2314
2315 // Dummy initialization to avoid warnings.
2316 TemplateParameterList::iterator OldParam = NewParams->end();
2317 if (OldParams)
2318 OldParam = OldParams->begin();
2319
2320 bool RemoveDefaultArguments = false;
2321 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2322 NewParamEnd = NewParams->end();
2323 NewParam != NewParamEnd; ++NewParam) {
2324 // Whether we've seen a duplicate default argument in the same translation
2325 // unit.
2326 bool RedundantDefaultArg = false;
2327 // Whether we've found inconsis inconsitent default arguments in different
2328 // translation unit.
2329 bool InconsistentDefaultArg = false;
2330 // The name of the module which contains the inconsistent default argument.
2331 std::string PrevModuleName;
2332
2333 SourceLocation OldDefaultLoc;
2334 SourceLocation NewDefaultLoc;
2335
2336 // Variable used to diagnose missing default arguments
2337 bool MissingDefaultArg = false;
2338
2339 // Variable used to diagnose non-final parameter packs
2340 bool SawParameterPack = false;
2341
2342 if (TemplateTypeParmDecl *NewTypeParm
2343 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2344 // Check the presence of a default argument here.
2345 if (NewTypeParm->hasDefaultArgument() &&
2347 *this, TPC, NewTypeParm->getLocation(),
2348 NewTypeParm->getDefaultArgument().getSourceRange()))
2349 NewTypeParm->removeDefaultArgument();
2350
2351 // Merge default arguments for template type parameters.
2352 TemplateTypeParmDecl *OldTypeParm
2353 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2354 if (NewTypeParm->isParameterPack()) {
2355 assert(!NewTypeParm->hasDefaultArgument() &&
2356 "Parameter packs can't have a default argument!");
2357 SawParameterPack = true;
2358 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2359 NewTypeParm->hasDefaultArgument() &&
2360 (!SkipBody || !SkipBody->ShouldSkip)) {
2361 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2362 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2363 SawDefaultArgument = true;
2364
2365 if (!OldTypeParm->getOwningModule())
2366 RedundantDefaultArg = true;
2367 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2368 NewTypeParm)) {
2369 InconsistentDefaultArg = true;
2370 PrevModuleName =
2372 }
2373 PreviousDefaultArgLoc = NewDefaultLoc;
2374 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2375 // Merge the default argument from the old declaration to the
2376 // new declaration.
2377 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2378 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2379 } else if (NewTypeParm->hasDefaultArgument()) {
2380 SawDefaultArgument = true;
2381 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2382 } else if (SawDefaultArgument)
2383 MissingDefaultArg = true;
2384 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2385 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2386 // Check for unexpanded parameter packs.
2387 if (!NewNonTypeParm->isParameterPack() &&
2388 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2389 NewNonTypeParm->getTypeSourceInfo(),
2391 Invalid = true;
2392 continue;
2393 }
2394
2395 // Check the presence of a default argument here.
2396 if (NewNonTypeParm->hasDefaultArgument() &&
2398 *this, TPC, NewNonTypeParm->getLocation(),
2399 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2400 NewNonTypeParm->removeDefaultArgument();
2401 }
2402
2403 // Merge default arguments for non-type template parameters
2404 NonTypeTemplateParmDecl *OldNonTypeParm
2405 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2406 if (NewNonTypeParm->isParameterPack()) {
2407 assert(!NewNonTypeParm->hasDefaultArgument() &&
2408 "Parameter packs can't have a default argument!");
2409 if (!NewNonTypeParm->isPackExpansion())
2410 SawParameterPack = true;
2411 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2412 NewNonTypeParm->hasDefaultArgument() &&
2413 (!SkipBody || !SkipBody->ShouldSkip)) {
2414 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2415 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2416 SawDefaultArgument = true;
2417 if (!OldNonTypeParm->getOwningModule())
2418 RedundantDefaultArg = true;
2419 else if (!getASTContext().isSameDefaultTemplateArgument(
2420 OldNonTypeParm, NewNonTypeParm)) {
2421 InconsistentDefaultArg = true;
2422 PrevModuleName =
2423 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2424 }
2425 PreviousDefaultArgLoc = NewDefaultLoc;
2426 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2427 // Merge the default argument from the old declaration to the
2428 // new declaration.
2429 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2430 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2431 } else if (NewNonTypeParm->hasDefaultArgument()) {
2432 SawDefaultArgument = true;
2433 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2434 } else if (SawDefaultArgument)
2435 MissingDefaultArg = true;
2436 } else {
2437 TemplateTemplateParmDecl *NewTemplateParm
2438 = cast<TemplateTemplateParmDecl>(*NewParam);
2439
2440 // Check for unexpanded parameter packs, recursively.
2441 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2442 Invalid = true;
2443 continue;
2444 }
2445
2446 // Check the presence of a default argument here.
2447 if (NewTemplateParm->hasDefaultArgument() &&
2449 NewTemplateParm->getLocation(),
2450 NewTemplateParm->getDefaultArgument().getSourceRange()))
2451 NewTemplateParm->removeDefaultArgument();
2452
2453 // Merge default arguments for template template parameters
2454 TemplateTemplateParmDecl *OldTemplateParm
2455 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2456 if (NewTemplateParm->isParameterPack()) {
2457 assert(!NewTemplateParm->hasDefaultArgument() &&
2458 "Parameter packs can't have a default argument!");
2459 if (!NewTemplateParm->isPackExpansion())
2460 SawParameterPack = true;
2461 } else if (OldTemplateParm &&
2462 hasVisibleDefaultArgument(OldTemplateParm) &&
2463 NewTemplateParm->hasDefaultArgument() &&
2464 (!SkipBody || !SkipBody->ShouldSkip)) {
2465 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2466 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2467 SawDefaultArgument = true;
2468 if (!OldTemplateParm->getOwningModule())
2469 RedundantDefaultArg = true;
2470 else if (!getASTContext().isSameDefaultTemplateArgument(
2471 OldTemplateParm, NewTemplateParm)) {
2472 InconsistentDefaultArg = true;
2473 PrevModuleName =
2474 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2475 }
2476 PreviousDefaultArgLoc = NewDefaultLoc;
2477 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2478 // Merge the default argument from the old declaration to the
2479 // new declaration.
2480 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2481 PreviousDefaultArgLoc
2482 = OldTemplateParm->getDefaultArgument().getLocation();
2483 } else if (NewTemplateParm->hasDefaultArgument()) {
2484 SawDefaultArgument = true;
2485 PreviousDefaultArgLoc
2486 = NewTemplateParm->getDefaultArgument().getLocation();
2487 } else if (SawDefaultArgument)
2488 MissingDefaultArg = true;
2489 }
2490
2491 // C++11 [temp.param]p11:
2492 // If a template parameter of a primary class template or alias template
2493 // is a template parameter pack, it shall be the last template parameter.
2494 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2495 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2496 TPC == TPC_TypeAliasTemplate)) {
2497 Diag((*NewParam)->getLocation(),
2498 diag::err_template_param_pack_must_be_last_template_parameter);
2499 Invalid = true;
2500 }
2501
2502 // [basic.def.odr]/13:
2503 // There can be more than one definition of a
2504 // ...
2505 // default template argument
2506 // ...
2507 // in a program provided that each definition appears in a different
2508 // translation unit and the definitions satisfy the [same-meaning
2509 // criteria of the ODR].
2510 //
2511 // Simply, the design of modules allows the definition of template default
2512 // argument to be repeated across translation unit. Note that the ODR is
2513 // checked elsewhere. But it is still not allowed to repeat template default
2514 // argument in the same translation unit.
2515 if (RedundantDefaultArg) {
2516 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2517 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2518 Invalid = true;
2519 } else if (InconsistentDefaultArg) {
2520 // We could only diagnose about the case that the OldParam is imported.
2521 // The case NewParam is imported should be handled in ASTReader.
2522 Diag(NewDefaultLoc,
2523 diag::err_template_param_default_arg_inconsistent_redefinition);
2524 Diag(OldDefaultLoc,
2525 diag::note_template_param_prev_default_arg_in_other_module)
2526 << PrevModuleName;
2527 Invalid = true;
2528 } else if (MissingDefaultArg &&
2529 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2530 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2531 // C++ 23[temp.param]p14:
2532 // If a template-parameter of a class template, variable template, or
2533 // alias template has a default template argument, each subsequent
2534 // template-parameter shall either have a default template argument
2535 // supplied or be a template parameter pack.
2536 Diag((*NewParam)->getLocation(),
2537 diag::err_template_param_default_arg_missing);
2538 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2539 Invalid = true;
2540 RemoveDefaultArguments = true;
2541 }
2542
2543 // If we have an old template parameter list that we're merging
2544 // in, move on to the next parameter.
2545 if (OldParams)
2546 ++OldParam;
2547 }
2548
2549 // We were missing some default arguments at the end of the list, so remove
2550 // all of the default arguments.
2551 if (RemoveDefaultArguments) {
2552 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2553 NewParamEnd = NewParams->end();
2554 NewParam != NewParamEnd; ++NewParam) {
2555 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2556 TTP->removeDefaultArgument();
2557 else if (NonTypeTemplateParmDecl *NTTP
2558 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2559 NTTP->removeDefaultArgument();
2560 else
2561 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2562 }
2563 }
2564
2565 return Invalid;
2566}
2567
2568namespace {
2569
2570/// A class which looks for a use of a certain level of template
2571/// parameter.
2572struct DependencyChecker : DynamicRecursiveASTVisitor {
2573 unsigned Depth;
2574
2575 // Whether we're looking for a use of a template parameter that makes the
2576 // overall construct type-dependent / a dependent type. This is strictly
2577 // best-effort for now; we may fail to match at all for a dependent type
2578 // in some cases if this is set.
2579 bool IgnoreNonTypeDependent;
2580
2581 bool Match;
2582 SourceLocation MatchLoc;
2583
2584 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2585 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2586 Match(false) {}
2587
2588 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2589 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2590 NamedDecl *ND = Params->getParam(0);
2591 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2592 Depth = PD->getDepth();
2593 } else if (NonTypeTemplateParmDecl *PD =
2594 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2595 Depth = PD->getDepth();
2596 } else {
2597 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2598 }
2599 }
2600
2601 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2602 if (ParmDepth >= Depth) {
2603 Match = true;
2604 MatchLoc = Loc;
2605 return true;
2606 }
2607 return false;
2608 }
2609
2610 bool TraverseStmt(Stmt *S) override {
2611 // Prune out non-type-dependent expressions if requested. This can
2612 // sometimes result in us failing to find a template parameter reference
2613 // (if a value-dependent expression creates a dependent type), but this
2614 // mode is best-effort only.
2615 if (auto *E = dyn_cast_or_null<Expr>(S))
2616 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2617 return true;
2619 }
2620
2621 bool TraverseTypeLoc(TypeLoc TL) override {
2622 if (IgnoreNonTypeDependent && !TL.isNull() &&
2623 !TL.getType()->isDependentType())
2624 return true;
2626 }
2627
2628 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2629 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2630 }
2631
2632 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2633 // For a best-effort search, keep looking until we find a location.
2634 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2635 }
2636
2637 bool TraverseTemplateName(TemplateName N) override {
2638 if (TemplateTemplateParmDecl *PD =
2639 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2640 if (Matches(PD->getDepth()))
2641 return false;
2643 }
2644
2645 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2646 if (NonTypeTemplateParmDecl *PD =
2647 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2648 if (Matches(PD->getDepth(), E->getExprLoc()))
2649 return false;
2650 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2651 }
2652
2653 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2654 return TraverseType(T->getReplacementType());
2655 }
2656
2657 bool VisitSubstTemplateTypeParmPackType(
2658 SubstTemplateTypeParmPackType *T) override {
2659 return TraverseTemplateArgument(T->getArgumentPack());
2660 }
2661
2662 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2663 return TraverseType(T->getInjectedSpecializationType());
2664 }
2665};
2666} // end anonymous namespace
2667
2668/// Determines whether a given type depends on the given parameter
2669/// list.
2670static bool
2672 if (!Params->size())
2673 return false;
2674
2675 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2676 Checker.TraverseType(T);
2677 return Checker.Match;
2678}
2679
2680// Find the source range corresponding to the named type in the given
2681// nested-name-specifier, if any.
2683 QualType T,
2684 const CXXScopeSpec &SS) {
2686 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2687 if (const Type *CurType = NNS->getAsType()) {
2688 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2689 return NNSLoc.getTypeLoc().getSourceRange();
2690 } else
2691 break;
2692
2693 NNSLoc = NNSLoc.getPrefix();
2694 }
2695
2696 return SourceRange();
2697}
2698
2700 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2701 TemplateIdAnnotation *TemplateId,
2702 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2703 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2704 IsMemberSpecialization = false;
2705 Invalid = false;
2706
2707 // The sequence of nested types to which we will match up the template
2708 // parameter lists. We first build this list by starting with the type named
2709 // by the nested-name-specifier and walking out until we run out of types.
2710 SmallVector<QualType, 4> NestedTypes;
2711 QualType T;
2712 if (SS.getScopeRep()) {
2714 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2716 else
2717 T = QualType(SS.getScopeRep()->getAsType(), 0);
2718 }
2719
2720 // If we found an explicit specialization that prevents us from needing
2721 // 'template<>' headers, this will be set to the location of that
2722 // explicit specialization.
2723 SourceLocation ExplicitSpecLoc;
2724
2725 while (!T.isNull()) {
2726 NestedTypes.push_back(T);
2727
2728 // Retrieve the parent of a record type.
2730 // If this type is an explicit specialization, we're done.
2732 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2733 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2734 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2735 ExplicitSpecLoc = Spec->getLocation();
2736 break;
2737 }
2738 } else if (Record->getTemplateSpecializationKind()
2740 ExplicitSpecLoc = Record->getLocation();
2741 break;
2742 }
2743
2744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2746 else
2747 T = QualType();
2748 continue;
2749 }
2750
2751 if (const TemplateSpecializationType *TST
2753 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2754 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2756 else
2757 T = QualType();
2758 continue;
2759 }
2760 }
2761
2762 // Look one step prior in a dependent template specialization type.
2763 if (const DependentTemplateSpecializationType *DependentTST
2765 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2766 T = QualType(NNS->getAsType(), 0);
2767 else
2768 T = QualType();
2769 continue;
2770 }
2771
2772 // Look one step prior in a dependent name type.
2773 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2774 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2775 T = QualType(NNS->getAsType(), 0);
2776 else
2777 T = QualType();
2778 continue;
2779 }
2780
2781 // Retrieve the parent of an enumeration type.
2782 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2783 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2784 // check here.
2785 EnumDecl *Enum = EnumT->getDecl();
2786
2787 // Get to the parent type.
2788 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2790 else
2791 T = QualType();
2792 continue;
2793 }
2794
2795 T = QualType();
2796 }
2797 // Reverse the nested types list, since we want to traverse from the outermost
2798 // to the innermost while checking template-parameter-lists.
2799 std::reverse(NestedTypes.begin(), NestedTypes.end());
2800
2801 // C++0x [temp.expl.spec]p17:
2802 // A member or a member template may be nested within many
2803 // enclosing class templates. In an explicit specialization for
2804 // such a member, the member declaration shall be preceded by a
2805 // template<> for each enclosing class template that is
2806 // explicitly specialized.
2807 bool SawNonEmptyTemplateParameterList = false;
2808
2809 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2810 if (SawNonEmptyTemplateParameterList) {
2811 if (!SuppressDiagnostic)
2812 Diag(DeclLoc, diag::err_specialize_member_of_template)
2813 << !Recovery << Range;
2814 Invalid = true;
2815 IsMemberSpecialization = false;
2816 return true;
2817 }
2818
2819 return false;
2820 };
2821
2822 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2823 // Check that we can have an explicit specialization here.
2824 if (CheckExplicitSpecialization(Range, true))
2825 return true;
2826
2827 // We don't have a template header, but we should.
2828 SourceLocation ExpectedTemplateLoc;
2829 if (!ParamLists.empty())
2830 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2831 else
2832 ExpectedTemplateLoc = DeclStartLoc;
2833
2834 if (!SuppressDiagnostic)
2835 Diag(DeclLoc, diag::err_template_spec_needs_header)
2836 << Range
2837 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2838 return false;
2839 };
2840
2841 unsigned ParamIdx = 0;
2842 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2843 ++TypeIdx) {
2844 T = NestedTypes[TypeIdx];
2845
2846 // Whether we expect a 'template<>' header.
2847 bool NeedEmptyTemplateHeader = false;
2848
2849 // Whether we expect a template header with parameters.
2850 bool NeedNonemptyTemplateHeader = false;
2851
2852 // For a dependent type, the set of template parameters that we
2853 // expect to see.
2854 TemplateParameterList *ExpectedTemplateParams = nullptr;
2855
2856 // C++0x [temp.expl.spec]p15:
2857 // A member or a member template may be nested within many enclosing
2858 // class templates. In an explicit specialization for such a member, the
2859 // member declaration shall be preceded by a template<> for each
2860 // enclosing class template that is explicitly specialized.
2863 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2864 ExpectedTemplateParams = Partial->getTemplateParameters();
2865 NeedNonemptyTemplateHeader = true;
2866 } else if (Record->isDependentType()) {
2867 if (Record->getDescribedClassTemplate()) {
2868 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2869 ->getTemplateParameters();
2870 NeedNonemptyTemplateHeader = true;
2871 }
2872 } else if (ClassTemplateSpecializationDecl *Spec
2873 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2874 // C++0x [temp.expl.spec]p4:
2875 // Members of an explicitly specialized class template are defined
2876 // in the same manner as members of normal classes, and not using
2877 // the template<> syntax.
2878 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2879 NeedEmptyTemplateHeader = true;
2880 else
2881 continue;
2882 } else if (Record->getTemplateSpecializationKind()) {
2883 if (Record->getTemplateSpecializationKind()
2885 TypeIdx == NumTypes - 1)
2886 IsMemberSpecialization = true;
2887
2888 continue;
2889 }
2890 } else if (const TemplateSpecializationType *TST
2892 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2893 ExpectedTemplateParams = Template->getTemplateParameters();
2894 NeedNonemptyTemplateHeader = true;
2895 }
2897 // FIXME: We actually could/should check the template arguments here
2898 // against the corresponding template parameter list.
2899 NeedNonemptyTemplateHeader = false;
2900 }
2901
2902 // C++ [temp.expl.spec]p16:
2903 // In an explicit specialization declaration for a member of a class
2904 // template or a member template that appears in namespace scope, the
2905 // member template and some of its enclosing class templates may remain
2906 // unspecialized, except that the declaration shall not explicitly
2907 // specialize a class member template if its enclosing class templates
2908 // are not explicitly specialized as well.
2909 if (ParamIdx < ParamLists.size()) {
2910 if (ParamLists[ParamIdx]->size() == 0) {
2911 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2912 false))
2913 return nullptr;
2914 } else
2915 SawNonEmptyTemplateParameterList = true;
2916 }
2917
2918 if (NeedEmptyTemplateHeader) {
2919 // If we're on the last of the types, and we need a 'template<>' header
2920 // here, then it's a member specialization.
2921 if (TypeIdx == NumTypes - 1)
2922 IsMemberSpecialization = true;
2923
2924 if (ParamIdx < ParamLists.size()) {
2925 if (ParamLists[ParamIdx]->size() > 0) {
2926 // The header has template parameters when it shouldn't. Complain.
2927 if (!SuppressDiagnostic)
2928 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2929 diag::err_template_param_list_matches_nontemplate)
2930 << T
2931 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2932 ParamLists[ParamIdx]->getRAngleLoc())
2934 Invalid = true;
2935 return nullptr;
2936 }
2937
2938 // Consume this template header.
2939 ++ParamIdx;
2940 continue;
2941 }
2942
2943 if (!IsFriend)
2944 if (DiagnoseMissingExplicitSpecialization(
2946 return nullptr;
2947
2948 continue;
2949 }
2950
2951 if (NeedNonemptyTemplateHeader) {
2952 // In friend declarations we can have template-ids which don't
2953 // depend on the corresponding template parameter lists. But
2954 // assume that empty parameter lists are supposed to match this
2955 // template-id.
2956 if (IsFriend && T->isDependentType()) {
2957 if (ParamIdx < ParamLists.size() &&
2959 ExpectedTemplateParams = nullptr;
2960 else
2961 continue;
2962 }
2963
2964 if (ParamIdx < ParamLists.size()) {
2965 // Check the template parameter list, if we can.
2966 if (ExpectedTemplateParams &&
2968 ExpectedTemplateParams,
2969 !SuppressDiagnostic, TPL_TemplateMatch))
2970 Invalid = true;
2971
2972 if (!Invalid &&
2973 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2975 Invalid = true;
2976
2977 ++ParamIdx;
2978 continue;
2979 }
2980
2981 if (!SuppressDiagnostic)
2982 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2983 << T
2985 Invalid = true;
2986 continue;
2987 }
2988 }
2989
2990 // If there were at least as many template-ids as there were template
2991 // parameter lists, then there are no template parameter lists remaining for
2992 // the declaration itself.
2993 if (ParamIdx >= ParamLists.size()) {
2994 if (TemplateId && !IsFriend) {
2995 // We don't have a template header for the declaration itself, but we
2996 // should.
2997 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2998 TemplateId->RAngleLoc));
2999
3000 // Fabricate an empty template parameter list for the invented header.
3002 SourceLocation(), {},
3003 SourceLocation(), nullptr);
3004 }
3005
3006 return nullptr;
3007 }
3008
3009 // If there were too many template parameter lists, complain about that now.
3010 if (ParamIdx < ParamLists.size() - 1) {
3011 bool HasAnyExplicitSpecHeader = false;
3012 bool AllExplicitSpecHeaders = true;
3013 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3014 if (ParamLists[I]->size() == 0)
3015 HasAnyExplicitSpecHeader = true;
3016 else
3017 AllExplicitSpecHeaders = false;
3018 }
3019
3020 if (!SuppressDiagnostic)
3021 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3022 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3023 : diag::err_template_spec_extra_headers)
3024 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3025 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3026
3027 // If there was a specialization somewhere, such that 'template<>' is
3028 // not required, and there were any 'template<>' headers, note where the
3029 // specialization occurred.
3030 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3031 !SuppressDiagnostic)
3032 Diag(ExplicitSpecLoc,
3033 diag::note_explicit_template_spec_does_not_need_header)
3034 << NestedTypes.back();
3035
3036 // We have a template parameter list with no corresponding scope, which
3037 // means that the resulting template declaration can't be instantiated
3038 // properly (we'll end up with dependent nodes when we shouldn't).
3039 if (!AllExplicitSpecHeaders)
3040 Invalid = true;
3041 }
3042
3043 // C++ [temp.expl.spec]p16:
3044 // In an explicit specialization declaration for a member of a class
3045 // template or a member template that ap- pears in namespace scope, the
3046 // member template and some of its enclosing class templates may remain
3047 // unspecialized, except that the declaration shall not explicitly
3048 // specialize a class member template if its en- closing class templates
3049 // are not explicitly specialized as well.
3050 if (ParamLists.back()->size() == 0 &&
3051 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3052 false))
3053 return nullptr;
3054
3055 // Return the last template parameter list, which corresponds to the
3056 // entity being declared.
3057 return ParamLists.back();
3058}
3059
3061 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3062 Diag(Template->getLocation(), diag::note_template_declared_here)
3063 << (isa<FunctionTemplateDecl>(Template)
3064 ? 0
3065 : isa<ClassTemplateDecl>(Template)
3066 ? 1
3067 : isa<VarTemplateDecl>(Template)
3068 ? 2
3069 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3070 << Template->getDeclName();
3071 return;
3072 }
3073
3074 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3075 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3076 IEnd = OST->end();
3077 I != IEnd; ++I)
3078 Diag((*I)->getLocation(), diag::note_template_declared_here)
3079 << 0 << (*I)->getDeclName();
3080
3081 return;
3082 }
3083}
3084
3086 SourceLocation TemplateLoc,
3088 auto lookUpCommonType = [&](TemplateArgument T1,
3089 TemplateArgument T2) -> QualType {
3090 // Don't bother looking for other specializations if both types are
3091 // builtins - users aren't allowed to specialize for them
3092 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3093 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3094
3099 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3100
3101 EnterExpressionEvaluationContext UnevaluatedContext(
3103 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3105
3106 QualType BaseTemplateInst =
3107 S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3108
3109 if (SFINAE.hasErrorOccurred())
3110 return QualType();
3111
3112 return BaseTemplateInst;
3113 };
3114
3115 // Note A: For the common_type trait applied to a template parameter pack T of
3116 // types, the member type shall be either defined or not present as follows:
3117 switch (Ts.size()) {
3118
3119 // If sizeof...(T) is zero, there shall be no member type.
3120 case 0:
3121 return QualType();
3122
3123 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3124 // pack T. The member typedef-name type shall denote the same type, if any, as
3125 // common_type_t<T0, T0>; otherwise there shall be no member type.
3126 case 1:
3127 return lookUpCommonType(Ts[0], Ts[0]);
3128
3129 // If sizeof...(T) is two, let the first and second types constituting T be
3130 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3131 // as decay_t<T1> and decay_t<T2>, respectively.
3132 case 2: {
3133 QualType T1 = Ts[0].getAsType();
3134 QualType T2 = Ts[1].getAsType();
3135 QualType D1 = S.BuiltinDecay(T1, {});
3136 QualType D2 = S.BuiltinDecay(T2, {});
3137
3138 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3139 // the same type, if any, as common_type_t<D1, D2>.
3140 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3141 return lookUpCommonType(D1, D2);
3142
3143 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3144 // denotes a valid type, let C denote that type.
3145 {
3146 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3147 EnterExpressionEvaluationContext UnevaluatedContext(
3149 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3151
3152 // false
3154 VK_PRValue);
3155 ExprResult Cond = &CondExpr;
3156
3157 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3158 if (ConstRefQual) {
3159 D1.addConst();
3160 D2.addConst();
3161 }
3162
3163 // declval<D1>()
3164 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3165 ExprResult LHS = &LHSExpr;
3166
3167 // declval<D2>()
3168 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3169 ExprResult RHS = &RHSExpr;
3170
3173
3174 // decltype(false ? declval<D1>() : declval<D2>())
3176 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3177
3178 if (Result.isNull() || SFINAE.hasErrorOccurred())
3179 return QualType();
3180
3181 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3182 return S.BuiltinDecay(Result, TemplateLoc);
3183 };
3184
3185 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3186 return Res;
3187
3188 // Let:
3189 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3190 // COND-RES(X, Y) be
3191 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3192
3193 // C++20 only
3194 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3195 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3196 if (!S.Context.getLangOpts().CPlusPlus20)
3197 return QualType();
3198 return CheckConditionalOperands(true);
3199 }
3200 }
3201
3202 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3203 // denote the first, second, and (pack of) remaining types constituting T. Let
3204 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3205 // a type C, the member typedef-name type shall denote the same type, if any,
3206 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3207 default: {
3208 QualType Result = Ts.front().getAsType();
3209 for (auto T : llvm::drop_begin(Ts)) {
3210 Result = lookUpCommonType(Result, T.getAsType());
3211 if (Result.isNull())
3212 return QualType();
3213 }
3214 return Result;
3215 }
3216 }
3217}
3218
3219static QualType
3222 SourceLocation TemplateLoc,
3223 TemplateArgumentListInfo &TemplateArgs) {
3224 ASTContext &Context = SemaRef.getASTContext();
3225
3226 switch (BTD->getBuiltinTemplateKind()) {
3227 case BTK__make_integer_seq: {
3228 // Specializations of __make_integer_seq<S, T, N> are treated like
3229 // S<T, 0, ..., N-1>.
3230
3231 QualType OrigType = Converted[1].getAsType();
3232 // C++14 [inteseq.intseq]p1:
3233 // T shall be an integer type.
3234 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3235 SemaRef.Diag(TemplateArgs[1].getLocation(),
3236 diag::err_integer_sequence_integral_element_type);
3237 return QualType();
3238 }
3239
3240 TemplateArgument NumArgsArg = Converted[2];
3241 if (NumArgsArg.isDependent())
3243 Converted);
3244
3245 TemplateArgumentListInfo SyntheticTemplateArgs;
3246 // The type argument, wrapped in substitution sugar, gets reused as the
3247 // first template argument in the synthetic template argument list.
3248 SyntheticTemplateArgs.addArgument(
3251 OrigType, TemplateArgs[1].getLocation())));
3252
3253 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3254 // Expand N into 0 ... N-1.
3255 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3256 I < NumArgs; ++I) {
3257 TemplateArgument TA(Context, I, OrigType);
3258 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3259 TA, OrigType, TemplateArgs[2].getLocation()));
3260 }
3261 } else {
3262 // C++14 [inteseq.make]p1:
3263 // If N is negative the program is ill-formed.
3264 SemaRef.Diag(TemplateArgs[2].getLocation(),
3265 diag::err_integer_sequence_negative_length);
3266 return QualType();
3267 }
3268
3269 // The first template argument will be reused as the template decl that
3270 // our synthetic template arguments will be applied to.
3271 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3272 TemplateLoc, SyntheticTemplateArgs);
3273 }
3274
3276 // Specializations of
3277 // __type_pack_element<Index, T_1, ..., T_N>
3278 // are treated like T_Index.
3279 assert(Converted.size() == 2 &&
3280 "__type_pack_element should be given an index and a parameter pack");
3281
3282 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3283 if (IndexArg.isDependent() || Ts.isDependent())
3285 Converted);
3286
3287 llvm::APSInt Index = IndexArg.getAsIntegral();
3288 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3289 "type std::size_t, and hence be non-negative");
3290 // If the Index is out of bounds, the program is ill-formed.
3291 if (Index >= Ts.pack_size()) {
3292 SemaRef.Diag(TemplateArgs[0].getLocation(),
3293 diag::err_type_pack_element_out_of_bounds);
3294 return QualType();
3295 }
3296
3297 // We simply return the type at index `Index`.
3298 int64_t N = Index.getExtValue();
3299 return Ts.getPackAsArray()[N].getAsType();
3300 }
3301
3303 assert(Converted.size() == 4);
3304 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3306 Converted);
3307
3308 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3309 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3310 QualType HasNoTypeMember = Converted[2].getAsType();
3311 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3312 if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3313 !CT.isNull()) {
3317 CT, TemplateArgs[1].getLocation())));
3318
3319 return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3320 }
3321 return HasNoTypeMember;
3322 }
3323 }
3324 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3325}
3326
3327/// Determine whether this alias template is "enable_if_t".
3328/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3330 return AliasTemplate->getName() == "enable_if_t" ||
3331 AliasTemplate->getName() == "__enable_if_t";
3332}
3333
3334/// Collect all of the separable terms in the given condition, which
3335/// might be a conjunction.
3336///
3337/// FIXME: The right answer is to convert the logical expression into
3338/// disjunctive normal form, so we can find the first failed term
3339/// within each possible clause.
3340static void collectConjunctionTerms(Expr *Clause,
3341 SmallVectorImpl<Expr *> &Terms) {
3342 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3343 if (BinOp->getOpcode() == BO_LAnd) {
3344 collectConjunctionTerms(BinOp->getLHS(), Terms);
3345 collectConjunctionTerms(BinOp->getRHS(), Terms);
3346 return;
3347 }
3348 }
3349
3350 Terms.push_back(Clause);
3351}
3352
3353// The ranges-v3 library uses an odd pattern of a top-level "||" with
3354// a left-hand side that is value-dependent but never true. Identify
3355// the idiom and ignore that term.
3357 // Top-level '||'.
3358 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3359 if (!BinOp) return Cond;
3360
3361 if (BinOp->getOpcode() != BO_LOr) return Cond;
3362
3363 // With an inner '==' that has a literal on the right-hand side.
3364 Expr *LHS = BinOp->getLHS();
3365 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3366 if (!InnerBinOp) return Cond;
3367
3368 if (InnerBinOp->getOpcode() != BO_EQ ||
3369 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3370 return Cond;
3371
3372 // If the inner binary operation came from a macro expansion named
3373 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3374 // of the '||', which is the real, user-provided condition.
3375 SourceLocation Loc = InnerBinOp->getExprLoc();
3376 if (!Loc.isMacroID()) return Cond;
3377
3378 StringRef MacroName = PP.getImmediateMacroName(Loc);
3379 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3380 return BinOp->getRHS();
3381
3382 return Cond;
3383}
3384
3385namespace {
3386
3387// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3388// within failing boolean expression, such as substituting template parameters
3389// for actual types.
3390class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3391public:
3392 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3393 : Policy(P) {}
3394
3395 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3396 const auto *DR = dyn_cast<DeclRefExpr>(E);
3397 if (DR && DR->getQualifier()) {
3398 // If this is a qualified name, expand the template arguments in nested
3399 // qualifiers.
3400 DR->getQualifier()->print(OS, Policy, true);
3401 // Then print the decl itself.
3402 const ValueDecl *VD = DR->getDecl();
3403 OS << VD->getName();
3404 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3405 // This is a template variable, print the expanded template arguments.
3407 OS, IV->getTemplateArgs().asArray(), Policy,
3408 IV->getSpecializedTemplate()->getTemplateParameters());
3409 }
3410 return true;
3411 }
3412 return false;
3413 }
3414
3415private:
3416 const PrintingPolicy Policy;
3417};
3418
3419} // end anonymous namespace
3420
3421std::pair<Expr *, std::string>
3423 Cond = lookThroughRangesV3Condition(PP, Cond);
3424
3425 // Separate out all of the terms in a conjunction.
3427 collectConjunctionTerms(Cond, Terms);
3428
3429 // Determine which term failed.
3430 Expr *FailedCond = nullptr;
3431 for (Expr *Term : Terms) {
3432 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3433
3434 // Literals are uninteresting.
3435 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3436 isa<IntegerLiteral>(TermAsWritten))
3437 continue;
3438
3439 // The initialization of the parameter from the argument is
3440 // a constant-evaluated context.
3443
3444 bool Succeeded;
3445 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3446 !Succeeded) {
3447 FailedCond = TermAsWritten;
3448 break;
3449 }
3450 }
3451 if (!FailedCond)
3452 FailedCond = Cond->IgnoreParenImpCasts();
3453
3454 std::string Description;
3455 {
3456 llvm::raw_string_ostream Out(Description);
3458 Policy.PrintCanonicalTypes = true;
3459 FailedBooleanConditionPrinterHelper Helper(Policy);
3460 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3461 }
3462 return { FailedCond, Description };
3463}
3464
3466 SourceLocation TemplateLoc,
3467 TemplateArgumentListInfo &TemplateArgs) {
3469 Name.getUnderlying().getAsDependentTemplateName();
3470 if (DTN && DTN->isIdentifier())
3471 // When building a template-id where the template-name is dependent,
3472 // assume the template is a type template. Either our assumption is
3473 // correct, or the code is ill-formed and will be diagnosed when the
3474 // dependent name is substituted.
3477 TemplateArgs.arguments());
3478
3479 if (Name.getAsAssumedTemplateName() &&
3480 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3481 return QualType();
3482
3483 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3484
3485 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3486 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3487 // We might have a substituted template template parameter pack. If so,
3488 // build a template specialization type for it.
3489 if (Name.getAsSubstTemplateTemplateParmPack())
3491 TemplateArgs.arguments());
3492
3493 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3494 << Name;
3496 return QualType();
3497 }
3498
3499 // Check that the template argument list is well-formed for this
3500 // template.
3501 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3502 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3503 DefaultArgs, false, SugaredConverted,
3504 CanonicalConverted,
3505 /*UpdateArgsWithConversions=*/true))
3506 return QualType();
3507
3508 QualType CanonType;
3509
3511 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3512
3513 // Find the canonical type for this type alias template specialization.
3514 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3515 if (Pattern->isInvalidDecl())
3516 return QualType();
3517
3518 // Only substitute for the innermost template argument list. NOTE: Some
3519 // external resugarers rely on leaving a Subst* node here. Make the
3520 // substitution non-final in that case. Note that these external resugarers
3521 // will still miss some information in this representation, because we don't
3522 // provide enough context in the Subst* nodes in order to tell different
3523 // template type alias specializations apart.
3524 MultiLevelTemplateArgumentList TemplateArgLists;
3525 TemplateArgLists.addOuterTemplateArguments(
3526 Template, SugaredConverted,
3527 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3528 TemplateArgLists.addOuterRetainedLevels(
3529 AliasTemplate->getTemplateParameters()->getDepth());
3530
3533 *this, /*PointOfInstantiation=*/TemplateLoc,
3534 /*Entity=*/AliasTemplate,
3535 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3536
3537 // Diagnose uses of this alias.
3538 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3539
3540 if (Inst.isInvalid())
3541 return QualType();
3542
3543 std::optional<ContextRAII> SavedContext;
3544 if (!AliasTemplate->getDeclContext()->isFileContext())
3545 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3546
3547 CanonType =
3548 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3549 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3550 if (CanonType.isNull()) {
3551 // If this was enable_if and we failed to find the nested type
3552 // within enable_if in a SFINAE context, dig out the specific
3553 // enable_if condition that failed and present that instead.
3555 if (auto DeductionInfo = isSFINAEContext()) {
3556 if (*DeductionInfo &&
3557 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3558 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3559 diag::err_typename_nested_not_found_enable_if &&
3560 TemplateArgs[0].getArgument().getKind()
3562 Expr *FailedCond;
3563 std::string FailedDescription;
3564 std::tie(FailedCond, FailedDescription) =
3565 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3566
3567 // Remove the old SFINAE diagnostic.
3568 PartialDiagnosticAt OldDiag =
3570 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3571
3572 // Add a new SFINAE diagnostic specifying which condition
3573 // failed.
3574 (*DeductionInfo)->addSFINAEDiagnostic(
3575 OldDiag.first,
3576 PDiag(diag::err_typename_nested_not_found_requirement)
3577 << FailedDescription
3578 << FailedCond->getSourceRange());
3579 }
3580 }
3581 }
3582
3583 return QualType();
3584 }
3585 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3586 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3587 TemplateLoc, TemplateArgs);
3588 } else if (Name.isDependent() ||
3590 TemplateArgs, CanonicalConverted)) {
3591 // This class template specialization is a dependent
3592 // type. Therefore, its canonical type is another class template
3593 // specialization type that contains all of the converted
3594 // arguments in canonical form. This ensures that, e.g., A<T> and
3595 // A<T, T> have identical types when A is declared as:
3596 //
3597 // template<typename T, typename U = T> struct A;
3599 Name, CanonicalConverted);
3600
3601 // This might work out to be a current instantiation, in which
3602 // case the canonical type needs to be the InjectedClassNameType.
3603 //
3604 // TODO: in theory this could be a simple hashtable lookup; most
3605 // changes to CurContext don't change the set of current
3606 // instantiations.
3607 if (isa<ClassTemplateDecl>(Template)) {
3608 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3609 // If we get out to a namespace, we're done.
3610 if (Ctx->isFileContext()) break;
3611
3612 // If this isn't a record, keep looking.
3613 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3614 if (!Record) continue;
3615
3616 // Look for one of the two cases with InjectedClassNameTypes
3617 // and check whether it's the same template.
3618 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3619 !Record->getDescribedClassTemplate())
3620 continue;
3621
3622 // Fetch the injected class name type and check whether its
3623 // injected type is equal to the type we just built.
3625 QualType Injected = cast<InjectedClassNameType>(ICNT)
3626 ->getInjectedSpecializationType();
3627
3628 if (CanonType != Injected->getCanonicalTypeInternal())
3629 continue;
3630
3631 // If so, the canonical type of this TST is the injected
3632 // class name type of the record we just found.
3633 assert(ICNT.isCanonical());
3634 CanonType = ICNT;
3635 break;
3636 }
3637 }
3638 } else if (ClassTemplateDecl *ClassTemplate =
3639 dyn_cast<ClassTemplateDecl>(Template)) {
3640 // Find the class template specialization declaration that
3641 // corresponds to these arguments.
3642 void *InsertPos = nullptr;
3644 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3645 if (!Decl) {
3646 // This is the first time we have referenced this class template
3647 // specialization. Create the canonical declaration and add it to
3648 // the set of specializations.
3650 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3651 ClassTemplate->getDeclContext(),
3652 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3653 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3654 nullptr);
3655 ClassTemplate->AddSpecialization(Decl, InsertPos);
3656 if (ClassTemplate->isOutOfLine())
3657 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3658 }
3659
3660 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3661 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3662 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3663 if (!Inst.isInvalid()) {
3664 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3665 CanonicalConverted,
3666 /*Final=*/false);
3667 InstantiateAttrsForDecl(TemplateArgLists,
3668 ClassTemplate->getTemplatedDecl(), Decl);
3669 }
3670 }
3671
3672 // Diagnose uses of this specialization.
3673 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3674
3675 CanonType = Context.getTypeDeclType(Decl);
3676 assert(isa<RecordType>(CanonType) &&
3677 "type of non-dependent specialization is not a RecordType");
3678 } else {
3679 llvm_unreachable("Unhandled template kind");
3680 }
3681
3682 // Build the fully-sugared type for this class template
3683 // specialization, which refers back to the class template
3684 // specialization we created or found.
3685 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3686 CanonType);
3687}
3688
3690 TemplateNameKind &TNK,
3691 SourceLocation NameLoc,
3692 IdentifierInfo *&II) {
3693 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3694
3695 TemplateName Name = ParsedName.get();
3696 auto *ATN = Name.getAsAssumedTemplateName();
3697 assert(ATN && "not an assumed template name");
3698 II = ATN->getDeclName().getAsIdentifierInfo();
3699
3700 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3701 // Resolved to a type template name.
3702 ParsedName = TemplateTy::make(Name);
3703 TNK = TNK_Type_template;
3704 }
3705}
3706
3708 SourceLocation NameLoc,
3709 bool Diagnose) {
3710 // We assumed this undeclared identifier to be an (ADL-only) function
3711 // template name, but it was used in a context where a type was required.
3712 // Try to typo-correct it now.
3713 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3714 assert(ATN && "not an assumed template name");
3715
3716 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3717 struct CandidateCallback : CorrectionCandidateCallback {
3718 bool ValidateCandidate(const TypoCorrection &TC) override {
3719 return TC.getCorrectionDecl() &&
3721 }
3722 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3723 return std::make_unique<CandidateCallback>(*this);
3724 }
3725 } FilterCCC;
3726
3727 TypoCorrection Corrected =
3728 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3729 FilterCCC, CTK_ErrorRecovery);
3730 if (Corrected && Corrected.getFoundDecl()) {
3731 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3732 << ATN->getDeclName());
3734 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3736 return false;
3737 }
3738
3739 if (Diagnose)
3740 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3741 return true;
3742}
3743
3745 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3746 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3747 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3748 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3749 bool IsCtorOrDtorName, bool IsClassName,
3750 ImplicitTypenameContext AllowImplicitTypename) {
3751 if (SS.isInvalid())
3752 return true;
3753
3754 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3755 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3756
3757 // C++ [temp.res]p3:
3758 // A qualified-id that refers to a type and in which the
3759 // nested-name-specifier depends on a template-parameter (14.6.2)
3760 // shall be prefixed by the keyword typename to indicate that the
3761 // qualified-id denotes a type, forming an
3762 // elaborated-type-specifier (7.1.5.3).
3763 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3764 // C++2a relaxes some of those restrictions in [temp.res]p5.
3765 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3767 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3768 else
3769 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3770 << SS.getScopeRep() << TemplateII->getName()
3771 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3772 } else
3773 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3774 << SS.getScopeRep() << TemplateII->getName();
3775
3776 // FIXME: This is not quite correct recovery as we don't transform SS
3777 // into the corresponding dependent form (and we don't diagnose missing
3778 // 'template' keywords within SS as a result).
3779 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3780 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3781 TemplateArgsIn, RAngleLoc);
3782 }
3783
3784 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3785 // it's not actually allowed to be used as a type in most cases. Because
3786 // we annotate it before we know whether it's valid, we have to check for
3787 // this case here.
3788 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3789 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3790 Diag(TemplateIILoc,
3791 TemplateKWLoc.isInvalid()
3792 ? diag::err_out_of_line_qualified_id_type_names_constructor
3793 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3794 << TemplateII << 0 /*injected-class-name used as template name*/
3795 << 1 /*if any keyword was present, it was 'template'*/;
3796 }
3797 }
3798
3799 TemplateName Template = TemplateD.get();
3800 if (Template.getAsAssumedTemplateName() &&
3801 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3802 return true;
3803
3804 // Translate the parser's template argument list in our AST format.
3805 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3806 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3807
3808 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3809 assert(SS.getScopeRep() == DTN->getQualifier());
3811 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3812 TemplateArgs.arguments());
3813 // Build type-source information.
3814 TypeLocBuilder TLB;
3819 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3820 SpecTL.setTemplateNameLoc(TemplateIILoc);
3821 SpecTL.setLAngleLoc(LAngleLoc);
3822 SpecTL.setRAngleLoc(RAngleLoc);
3823 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3824 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3826 }
3827
3828 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3829 if (SpecTy.isNull())
3830 return true;
3831
3832 // Build type-source information.
3833 TypeLocBuilder TLB;
3836 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3837 SpecTL.setTemplateNameLoc(TemplateIILoc);
3838 SpecTL.setLAngleLoc(LAngleLoc);
3839 SpecTL.setRAngleLoc(RAngleLoc);
3840 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3841 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3842
3843 // Create an elaborated-type-specifier containing the nested-name-specifier.
3844 QualType ElTy =
3846 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3847 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3849 if (!ElabTL.isEmpty())
3851 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3852}
3853
3855 TypeSpecifierType TagSpec,
3856 SourceLocation TagLoc,
3857 CXXScopeSpec &SS,
3858 SourceLocation TemplateKWLoc,
3859 TemplateTy TemplateD,
3860 SourceLocation TemplateLoc,
3861 SourceLocation LAngleLoc,
3862 ASTTemplateArgsPtr TemplateArgsIn,
3863 SourceLocation RAngleLoc) {
3864 if (SS.isInvalid())
3865 return TypeResult(true);
3866
3867 TemplateName Template = TemplateD.get();
3868
3869 // Translate the parser's template argument list in our AST format.
3870 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3871 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3872
3873 // Determine the tag kind
3875 ElaboratedTypeKeyword Keyword
3877
3878 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3879 assert(SS.getScopeRep() == DTN->getQualifier());
3881 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3882 TemplateArgs.arguments());
3883
3884 // Build type-source information.
3885 TypeLocBuilder TLB;
3888 SpecTL.setElaboratedKeywordLoc(TagLoc);
3890 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3891 SpecTL.setTemplateNameLoc(TemplateLoc);
3892 SpecTL.setLAngleLoc(LAngleLoc);
3893 SpecTL.setRAngleLoc(RAngleLoc);
3894 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3895 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3897 }
3898
3899 if (TypeAliasTemplateDecl *TAT =
3900 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3901 // C++0x [dcl.type.elab]p2:
3902 // If the identifier resolves to a typedef-name or the simple-template-id
3903 // resolves to an alias template specialization, the
3904 // elaborated-type-specifier is ill-formed.
3905 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3906 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3907 Diag(TAT->getLocation(), diag::note_declared_at);
3908 }
3909
3910 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3911 if (Result.isNull())
3912 return TypeResult(true);
3913
3914 // Check the tag kind
3915 if (const RecordType *RT = Result->getAs<RecordType>()) {
3916 RecordDecl *D = RT->getDecl();
3917
3918 IdentifierInfo *Id = D->getIdentifier();
3919 assert(Id && "templated class must have an identifier");
3920
3922 TagLoc, Id)) {
3923 Diag(TagLoc, diag::err_use_with_wrong_tag)
3924 << Result
3925 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3926 Diag(D->getLocation(), diag::note_previous_use);
3927 }
3928 }
3929
3930 // Provide source-location information for the template specialization.
3931 TypeLocBuilder TLB;
3934 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3935 SpecTL.setTemplateNameLoc(TemplateLoc);
3936 SpecTL.setLAngleLoc(LAngleLoc);
3937 SpecTL.setRAngleLoc(RAngleLoc);
3938 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3939 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3940
3941 // Construct an elaborated type containing the nested-name-specifier (if any)
3942 // and tag keyword.
3945 ElabTL.setElaboratedKeywordLoc(TagLoc);
3948}
3949
3950static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3951 NamedDecl *PrevDecl,
3954
3956
3958 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3959 switch (Arg.getKind()) {
3967 return false;
3968
3970 QualType Type = Arg.getAsType();
3971 const TemplateTypeParmType *TPT =
3973 return TPT && !Type.hasQualifiers() &&
3974 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3975 }
3976
3978 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3979 if (!DRE || !DRE->getDecl())
3980 return false;
3981 const NonTypeTemplateParmDecl *NTTP =
3982 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3983 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3984 }
3985
3987 const TemplateTemplateParmDecl *TTP =
3988 dyn_cast_or_null<TemplateTemplateParmDecl>(
3990 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3991 }
3992 llvm_unreachable("unexpected kind of template argument");
3993}
3994
3997 if (Params->size() != Args.size())
3998 return false;
3999
4000 unsigned Depth = Params->getDepth();
4001
4002 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4003 TemplateArgument Arg = Args[I];
4004
4005 // If the parameter is a pack expansion, the argument must be a pack
4006 // whose only element is a pack expansion.
4007 if (Params->getParam(I)->isParameterPack()) {
4008 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4009 !Arg.pack_begin()->isPackExpansion())
4010 return false;
4011 Arg = Arg.pack_begin()->getPackExpansionPattern();
4012 }
4013
4014 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4015 return false;
4016 }
4017
4018 return true;
4019}
4020
4021template<typename PartialSpecDecl>
4022static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4023 if (Partial->getDeclContext()->isDependentContext())
4024 return;
4025
4026 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4027 // for non-substitution-failure issues?
4028 TemplateDeductionInfo Info(Partial->getLocation());
4029 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4030 return;
4031
4032 auto *Template = Partial->getSpecializedTemplate();
4033 S.Diag(Partial->getLocation(),
4034 diag::ext_partial_spec_not_more_specialized_than_primary)
4035 << isa<VarTemplateDecl>(Template);
4036
4037 if (Info.hasSFINAEDiagnostic()) {
4041 SmallString<128> SFINAEArgString;
4042 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4043 S.Diag(Diag.first,
4044 diag::note_partial_spec_not_more_specialized_than_primary)
4045 << SFINAEArgString;
4046 }
4047
4048 S.NoteTemplateLocation(*Template);
4049 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4050 Template->getAssociatedConstraints(TemplateAC);
4051 Partial->getAssociatedConstraints(PartialAC);
4052 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4053 TemplateAC);
4054}
4055
4056static void
4058 const llvm::SmallBitVector &DeducibleParams) {
4059 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4060 if (!DeducibleParams[I]) {
4061 NamedDecl *Param = TemplateParams->getParam(I);
4062 if (Param->getDeclName())
4063 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4064 << Param->getDeclName();
4065 else
4066 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4067 << "(anonymous)";
4068 }
4069 }
4070}
4071
4072
4073template<typename PartialSpecDecl>
4075 PartialSpecDecl *Partial) {
4076 // C++1z [temp.class.spec]p8: (DR1495)
4077 // - The specialization shall be more specialized than the primary
4078 // template (14.5.5.2).
4080
4081 // C++ [temp.class.spec]p8: (DR1315)
4082 // - Each template-parameter shall appear at least once in the
4083 // template-id outside a non-deduced context.
4084 // C++1z [temp.class.spec.match]p3 (P0127R2)
4085 // If the template arguments of a partial specialization cannot be
4086 // deduced because of the structure of its template-parameter-list
4087 // and the template-id, the program is ill-formed.
4088 auto *TemplateParams = Partial->getTemplateParameters();
4089 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4090 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4091 TemplateParams->getDepth(), DeducibleParams);
4092
4093 if (!DeducibleParams.all()) {
4094 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4095 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4096 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4097 << (NumNonDeducible > 1)
4098 << SourceRange(Partial->getLocation(),
4099 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4100 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4101 }
4102}
4103
4106 checkTemplatePartialSpecialization(*this, Partial);
4107}
4108
4111 checkTemplatePartialSpecialization(*this, Partial);
4112}
4113
4115 // C++1z [temp.param]p11:
4116 // A template parameter of a deduction guide template that does not have a
4117 // default-argument shall be deducible from the parameter-type-list of the
4118 // deduction guide template.
4119 auto *TemplateParams = TD->getTemplateParameters();
4120 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4121 MarkDeducedTemplateParameters(TD, DeducibleParams);
4122 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4123 // A parameter pack is deducible (to an empty pack).
4124 auto *Param = TemplateParams->getParam(I);
4125 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4126 DeducibleParams[I] = true;
4127 }
4128
4129 if (!DeducibleParams.all()) {
4130 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4131 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4132 << (NumNonDeducible > 1);
4133 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4134 }
4135}
4136
4139 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4141 // D must be variable template id.
4142 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4143 "Variable template specialization is declared with a template id.");
4144
4145 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4146 TemplateArgumentListInfo TemplateArgs =
4147 makeTemplateArgumentListInfo(*this, *TemplateId);
4148 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4149 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4150 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4151
4152 TemplateName Name = TemplateId->Template.get();
4153
4154 // The template-id must name a variable template.
4156 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4157 if (!VarTemplate) {
4158 NamedDecl *FnTemplate;
4159 if (auto *OTS = Name.getAsOverloadedTemplate())
4160 FnTemplate = *OTS->begin();
4161 else
4162 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4163 if (FnTemplate)
4164 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4165 << FnTemplate->getDeclName();
4166 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4168 }
4169
4170 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4171 auto Message = DSA->getMessage();
4172 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4173 << VarTemplate << !Message.empty() << Message;
4174 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4175 }
4176
4177 // Check for unexpanded parameter packs in any of the template arguments.
4178 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4179 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4183 return true;
4184
4185 // Check that the template argument list is well-formed for this
4186 // template.
4187 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4188 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4189 /*DefaultArgs=*/{}, false, SugaredConverted,
4190 CanonicalConverted,
4191 /*UpdateArgsWithConversions=*/true))
4192 return true;
4193
4194 // Find the variable template (partial) specialization declaration that
4195 // corresponds to these arguments.
4198 TemplateArgs.size(),
4199 CanonicalConverted))
4200 return true;
4201
4202 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4203 // also do them during instantiation.
4204 if (!Name.isDependent() &&
4206 TemplateArgs, CanonicalConverted)) {
4207 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4208 << VarTemplate->getDeclName();
4210 }
4211
4212 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4213 CanonicalConverted) &&
4214 (!Context.getLangOpts().CPlusPlus20 ||
4215 !TemplateParams->hasAssociatedConstraints())) {
4216 // C++ [temp.class.spec]p9b3:
4217 //
4218 // -- The argument list of the specialization shall not be identical
4219 // to the implicit argument list of the primary template.
4220 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4221 << /*variable template*/ 1
4222 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4223 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4224 // FIXME: Recover from this by treating the declaration as a redeclaration
4225 // of the primary template.
4226 return true;
4227 }
4228 }
4229
4230 void *InsertPos = nullptr;
4231 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4232
4234 PrevDecl = VarTemplate->findPartialSpecialization(
4235 CanonicalConverted, TemplateParams, InsertPos);
4236 else
4237 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4238
4240
4241 // Check whether we can declare a variable template specialization in
4242 // the current scope.
4243 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4244 TemplateNameLoc,
4246 return true;
4247
4248 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4249 // Since the only prior variable template specialization with these
4250 // arguments was referenced but not declared, reuse that
4251 // declaration node as our own, updating its source location and
4252 // the list of outer template parameters to reflect our new declaration.
4253 Specialization = PrevDecl;
4254 Specialization->setLocation(TemplateNameLoc);
4255 PrevDecl = nullptr;
4256 } else if (IsPartialSpecialization) {
4257 // Create a new class template partial specialization declaration node.
4259 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4262 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4263 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4264 CanonicalConverted);
4265 Partial->setTemplateArgsAsWritten(TemplateArgs);
4266
4267 if (!PrevPartial)
4268 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4269 Specialization = Partial;
4270
4271 // If we are providing an explicit specialization of a member variable
4272 // template specialization, make a note of that.
4273 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4274 PrevPartial->setMemberSpecialization();
4275
4277 } else {
4278 // Create a new class template specialization declaration node for
4279 // this explicit specialization or friend declaration.
4281 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4282 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4283 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4284
4285 if (!PrevDecl)
4286 VarTemplate->AddSpecialization(Specialization, InsertPos);
4287 }
4288
4289 // C++ [temp.expl.spec]p6:
4290 // If a template, a member template or the member of a class template is
4291 // explicitly specialized then that specialization shall be declared
4292 // before the first use of that specialization that would cause an implicit
4293 // instantiation to take place, in every translation unit in which such a
4294 // use occurs; no diagnostic is required.
4295 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4296 bool Okay = false;
4297 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4298 // Is there any previous explicit specialization declaration?
4300 Okay = true;
4301 break;
4302 }
4303 }
4304
4305 if (!Okay) {
4306 SourceRange Range(TemplateNameLoc, RAngleLoc);
4307 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4308 << Name << Range;
4309
4310 Diag(PrevDecl->getPointOfInstantiation(),
4311 diag::note_instantiation_required_here)
4312 << (PrevDecl->getTemplateSpecializationKind() !=
4314 return true;
4315 }
4316 }
4317
4318 Specialization->setLexicalDeclContext(CurContext);
4319
4320 // Add the specialization into its lexical context, so that it can
4321 // be seen when iterating through the list of declarations in that
4322 // context. However, specializations are not found by name lookup.
4324
4325 // Note that this is an explicit specialization.
4326 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4327
4328 Previous.clear();
4329 if (PrevDecl)
4330 Previous.addDecl(PrevDecl);
4331 else if (Specialization->isStaticDataMember() &&
4332 Specialization->isOutOfLine())
4333 Specialization->setAccess(VarTemplate->getAccess());
4334
4335 return Specialization;
4336}
4337
4338namespace {
4339/// A partial specialization whose template arguments have matched
4340/// a given template-id.
4341struct PartialSpecMatchResult {
4344};
4345} // end anonymous namespace
4346
4349 SourceLocation TemplateNameLoc,
4350 const TemplateArgumentListInfo &TemplateArgs) {
4351 assert(Template && "A variable template id without template?");
4352
4353 // Check that the template argument list is well-formed for this template.
4354 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4356 Template, TemplateNameLoc,
4357 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4358 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4359 /*UpdateArgsWithConversions=*/true))
4360 return true;
4361
4362 // Produce a placeholder value if the specialization is dependent.
4363 if (Template->getDeclContext()->isDependentContext() ||
4365 TemplateArgs, CanonicalConverted))
4366 return DeclResult();
4367
4368 // Find the variable template specialization declaration that
4369 // corresponds to these arguments.
4370 void *InsertPos = nullptr;
4372 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4373 checkSpecializationReachability(TemplateNameLoc, Spec);
4374 // If we already have a variable template specialization, return it.
4375 return Spec;
4376 }
4377
4378 // This is the first time we have referenced this variable template
4379 // specialization. Create the canonical declaration and add it to
4380 // the set of specializations, based on the closest partial specialization
4381 // that it represents. That is,
4382 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4383 const TemplateArgumentList *PartialSpecArgs = nullptr;
4384 bool AmbiguousPartialSpec = false;
4385 typedef PartialSpecMatchResult MatchResult;
4387 SourceLocation PointOfInstantiation = TemplateNameLoc;
4388 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4389 /*ForTakingAddress=*/false);
4390
4391 // 1. Attempt to find the closest partial specialization that this
4392 // specializes, if any.
4393 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4394 // Perhaps better after unification of DeduceTemplateArguments() and
4395 // getMoreSpecializedPartialSpecialization().
4397 Template->getPartialSpecializations(PartialSpecs);
4398
4399 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4400 // C++ [temp.spec.partial.member]p2:
4401 // If the primary member template is explicitly specialized for a given
4402 // (implicit) specialization of the enclosing class template, the partial
4403 // specializations of the member template are ignored for this
4404 // specialization of the enclosing class template. If a partial
4405 // specialization of the member template is explicitly specialized for a
4406 // given (implicit) specialization of the enclosing class template, the
4407 // primary member template and its other partial specializations are still
4408 // considered for this specialization of the enclosing class template.
4409 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4410 !Partial->getMostRecentDecl()->isMemberSpecialization())
4411 continue;
4412
4413 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4414
4416 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4418 // Store the failed-deduction information for use in diagnostics, later.
4419 // TODO: Actually use the failed-deduction info?
4420 FailedCandidates.addCandidate().set(
4421 DeclAccessPair::make(Template, AS_public), Partial,
4423 (void)Result;
4424 } else {
4425 Matched.push_back(PartialSpecMatchResult());
4426 Matched.back().Partial = Partial;
4427 Matched.back().Args = Info.takeSugared();
4428 }
4429 }
4430
4431 if (Matched.size() >= 1) {
4432 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4433 if (Matched.size() == 1) {
4434 // -- If exactly one matching specialization is found, the
4435 // instantiation is generated from that specialization.
4436 // We don't need to do anything for this.
4437 } else {
4438 // -- If more than one matching specialization is found, the
4439 // partial order rules (14.5.4.2) are used to determine
4440 // whether one of the specializations is more specialized
4441 // than the others. If none of the specializations is more
4442 // specialized than all of the other matching
4443 // specializations, then the use of the variable template is
4444 // ambiguous and the program is ill-formed.
4446 PEnd = Matched.end();
4447 P != PEnd; ++P) {
4448 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4449 PointOfInstantiation) ==
4450 P->Partial)
4451 Best = P;
4452 }
4453
4454 // Determine if the best partial specialization is more specialized than
4455 // the others.
4456 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4457 PEnd = Matched.end();
4458 P != PEnd; ++P) {
4460 P->Partial, Best->Partial,
4461 PointOfInstantiation) != Best->Partial) {
4462 AmbiguousPartialSpec = true;
4463 break;
4464 }
4465 }
4466 }
4467
4468 // Instantiate using the best variable template partial specialization.
4469 InstantiationPattern = Best->Partial;
4470 PartialSpecArgs = Best->Args;
4471 } else {
4472 // -- If no match is found, the instantiation is generated
4473 // from the primary template.
4474 // InstantiationPattern = Template->getTemplatedDecl();
4475 }
4476
4477 // 2. Create the canonical declaration.
4478 // Note that we do not instantiate a definition until we see an odr-use
4479 // in DoMarkVarDeclReferenced().
4480 // FIXME: LateAttrs et al.?
4482 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4483 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4484 if (!Decl)
4485 return true;
4486
4487 if (AmbiguousPartialSpec) {
4488 // Partial ordering did not produce a clear winner. Complain.
4490 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4491 << Decl;
4492
4493 // Print the matching partial specializations.
4494 for (MatchResult P : Matched)
4495 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4496 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4497 *P.Args);
4498 return true;
4499 }
4500
4502 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4503 Decl->setInstantiationOf(D, PartialSpecArgs);
4504
4505 checkSpecializationReachability(TemplateNameLoc, Decl);
4506
4507 assert(Decl && "No variable template specialization?");
4508 return Decl;
4509}
4510
4512 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4513 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4514 const TemplateArgumentListInfo *TemplateArgs) {
4515
4516 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4517 *TemplateArgs);
4518 if (Decl.isInvalid())
4519 return ExprError();
4520
4521 if (!Decl.get())
4522 return ExprResult();
4523
4524 VarDecl *Var = cast<VarDecl>(Decl.get());
4527 NameInfo.getLoc());
4528
4529 // Build an ordinary singleton decl ref.
4530 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4531}
4532
4535 Diag(Loc, diag::err_template_missing_args)
4536 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4537 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4538 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4539 }
4540}
4541
4543 bool TemplateKeyword,
4544 TemplateDecl *TD,
4547 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4549}
4550
4553 SourceLocation TemplateKWLoc,
4554 const DeclarationNameInfo &ConceptNameInfo,
4555 NamedDecl *FoundDecl,
4556 ConceptDecl *NamedConcept,
4557 const TemplateArgumentListInfo *TemplateArgs) {
4558 assert(NamedConcept && "A concept template id without a template?");
4559
4560 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4562 NamedConcept, ConceptNameInfo.getLoc(),
4563 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4564 /*DefaultArgs=*/{},
4565 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4566 /*UpdateArgsWithConversions=*/false))
4567 return ExprError();
4568
4569 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4570
4572 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4573 CanonicalConverted);
4574 ConstraintSatisfaction Satisfaction;
4575 bool AreArgsDependent =
4577 *TemplateArgs, CanonicalConverted);
4578 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4579 /*Final=*/false);
4581
4584
4585 if (!AreArgsDependent &&
4587 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4588 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4589 TemplateArgs->getRAngleLoc()),
4590 Satisfaction))
4591 return ExprError();
4592 auto *CL = ConceptReference::Create(
4593 Context,
4595 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4598 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4599}
4600
4602 SourceLocation TemplateKWLoc,
4603 LookupResult &R,
4604 bool RequiresADL,
4605 const TemplateArgumentListInfo *TemplateArgs) {
4606 // FIXME: Can we do any checking at this point? I guess we could check the
4607 // template arguments that we have against the template name, if the template
4608 // name refers to a single template. That's not a terribly common case,
4609 // though.
4610 // foo<int> could identify a single function unambiguously
4611 // This approach does NOT work, since f<int>(1);
4612 // gets resolved prior to resorting to overload resolution
4613 // i.e., template<class T> void f(double);
4614 // vs template<class T, class U> void f(U);
4615
4616 // These should be filtered out by our callers.
4617 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4618
4619 // Non-function templates require a template argument list.
4620 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4621 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4623 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4624 return ExprError();
4625 }
4626 }
4627 bool KnownDependent = false;
4628 // In C++1y, check variable template ids.
4629 if (R.getAsSingle<VarTemplateDecl>()) {
4632 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4633 if (Res.isInvalid() || Res.isUsable())
4634 return Res;
4635 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4636 KnownDependent = true;
4637 }
4638
4639 if (R.getAsSingle<ConceptDecl>()) {
4640 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4642 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4643 }
4644
4645 // We don't want lookup warnings at this point.
4647
4650 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4651 R.begin(), R.end(), KnownDependent,
4652 /*KnownInstantiationDependent=*/false);
4653
4654 // Model the templates with UnresolvedTemplateTy. The expression should then
4655 // either be transformed in an instantiation or be diagnosed in
4656 // CheckPlaceholderExpr.
4657 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4660
4661 return ULE;
4662}
4663
4665 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4666 const DeclarationNameInfo &NameInfo,
4667 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4668 assert(TemplateArgs || TemplateKWLoc.isValid());
4669
4670 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4671 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4672 /*EnteringContext=*/false, TemplateKWLoc))
4673 return ExprError();
4674
4675 if (R.isAmbiguous())
4676 return ExprError();
4677
4679 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4680
4681 if (R.empty()) {
4683 Diag(NameInfo.getLoc(), diag::err_no_member)
4684 << NameInfo.getName() << DC << SS.getRange();
4685 return ExprError();
4686 }
4687
4688 // If necessary, build an implicit class member access.
4689 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4690 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4691 /*S=*/nullptr);
4692
4693 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4694}
4695
4697 CXXScopeSpec &SS,
4698 SourceLocation TemplateKWLoc,
4699 const UnqualifiedId &Name,
4700 ParsedType ObjectType,
4701 bool EnteringContext,
4703 bool AllowInjectedClassName) {
4704 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4705 Diag(TemplateKWLoc,
4707 diag::warn_cxx98_compat_template_outside_of_template :
4708 diag::ext_template_outside_of_template)
4709 << FixItHint::CreateRemoval(TemplateKWLoc);
4710
4711 if (SS.isInvalid())
4712 return TNK_Non_template;
4713
4714 // Figure out where isTemplateName is going to look.
4715 DeclContext *LookupCtx = nullptr;
4716 if (SS.isNotEmpty())
4717 LookupCtx = computeDeclContext(SS, EnteringContext);
4718 else if (ObjectType)
4719 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4720
4721 // C++0x [temp.names]p5:
4722 // If a name prefixed by the keyword template is not the name of
4723 // a template, the program is ill-formed. [Note: the keyword
4724 // template may not be applied to non-template members of class
4725 // templates. -end note ] [ Note: as is the case with the
4726 // typename prefix, the template prefix is allowed in cases
4727 // where it is not strictly necessary; i.e., when the
4728 // nested-name-specifier or the expression on the left of the ->
4729 // or . is not dependent on a template-parameter, or the use
4730 // does not appear in the scope of a template. -end note]
4731 //
4732 // Note: C++03 was more strict here, because it banned the use of
4733 // the "template" keyword prior to a template-name that was not a
4734 // dependent name. C++ DR468 relaxed this requirement (the
4735 // "template" keyword is now permitted). We follow the C++0x
4736 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4737 bool MemberOfUnknownSpecialization;
4738 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4739 ObjectType, EnteringContext, Result,
4740 MemberOfUnknownSpecialization);
4741 if (TNK != TNK_Non_template) {
4742 // We resolved this to a (non-dependent) template name. Return it.
4743 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4744 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4745 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4746 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4747 // C++14 [class.qual]p2:
4748 // In a lookup in which function names are not ignored and the
4749 // nested-name-specifier nominates a class C, if the name specified
4750 // [...] is the injected-class-name of C, [...] the name is instead
4751 // considered to name the constructor
4752 //
4753 // We don't get here if naming the constructor would be valid, so we
4754 // just reject immediately and recover by treating the
4755 // injected-class-name as naming the template.
4756 Diag(Name.getBeginLoc(),
4757 diag::ext_out_of_line_qualified_id_type_names_constructor)
4758 << Name.Identifier
4759 << 0 /*injected-class-name used as template name*/
4760 << TemplateKWLoc.isValid();
4761 }
4762 return TNK;
4763 }
4764
4765 if (!MemberOfUnknownSpecialization) {
4766 // Didn't find a template name, and the lookup wasn't dependent.
4767 // Do the lookup again to determine if this is a "nothing found" case or
4768 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4769 // need to do this.
4771 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4773 // Tell LookupTemplateName that we require a template so that it diagnoses
4774 // cases where it finds a non-template.
4775 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4776 ? RequiredTemplateKind(TemplateKWLoc)
4778 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4779 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4780 !R.isAmbiguous()) {
4781 if (LookupCtx)
4782 Diag(Name.getBeginLoc(), diag::err_no_member)
4783 << DNI.getName() << LookupCtx << SS.getRange();
4784 else
4785 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4786 << DNI.getName() << SS.getRange();
4787 }
4788 return TNK_Non_template;
4789 }
4790
4791 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4792
4793 switch (Name.getKind()) {
4796 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4798
4801 Qualifier, Name.OperatorFunctionId.Operator));
4802 return TNK_Function_template;
4803
4805 // This is a kind of template name, but can never occur in a dependent
4806 // scope (literal operators can only be declared at namespace scope).
4807 break;
4808
4809 default:
4810 break;
4811 }
4812
4813 // This name cannot possibly name a dependent template. Diagnose this now
4814 // rather than building a dependent template name that can never be valid.
4815 Diag(Name.getBeginLoc(),
4816 diag::err_template_kw_refers_to_dependent_non_template)
4817 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4818 << TemplateKWLoc.isValid() << TemplateKWLoc;
4819 return TNK_Non_template;
4820}
4821
4824 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4825 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4826 const TemplateArgument &Arg = AL.getArgument();
4827 QualType ArgType;
4828 TypeSourceInfo *TSI = nullptr;
4829
4830 // Check template type parameter.
4831 switch(Arg.getKind()) {
4833 // C++ [temp.arg.type]p1:
4834 // A template-argument for a template-parameter which is a
4835 // type shall be a type-id.
4836 ArgType = Arg.getAsType();
4837 TSI = AL.getTypeSourceInfo();
4838 break;
4841 // We have a template type parameter but the template argument
4842 // is a template without any arguments.
4843 SourceRange SR = AL.getSourceRange();
4846 return true;
4847 }
4849 // We have a template type parameter but the template argument is an
4850 // expression; see if maybe it is missing the "typename" keyword.
4851 CXXScopeSpec SS;
4852 DeclarationNameInfo NameInfo;
4853
4854 if (DependentScopeDeclRefExpr *ArgExpr =
4855 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4856 SS.Adopt(ArgExpr->getQualifierLoc());
4857 NameInfo = ArgExpr->getNameInfo();
4858 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4859 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4860 if (ArgExpr->isImplicitAccess()) {
4861 SS.Adopt(ArgExpr->getQualifierLoc());
4862 NameInfo = ArgExpr->getMemberNameInfo();
4863 }
4864 }
4865
4866 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4867 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4868 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4869
4870 if (Result.getAsSingle<TypeDecl>() ||
4871 Result.wasNotFoundInCurrentInstantiation()) {
4872 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4873 // Suggest that the user add 'typename' before the NNS.
4875 Diag(Loc, getLangOpts().MSVCCompat
4876 ? diag::ext_ms_template_type_arg_missing_typename
4877 : diag::err_template_arg_must_be_type_suggest)
4878 << FixItHint::CreateInsertion(Loc, "typename ");
4880
4881 // Recover by synthesizing a type using the location information that we
4882 // already have.
4884 SS.getScopeRep(), II);
4885 TypeLocBuilder TLB;
4887 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4889 TL.setNameLoc(NameInfo.getLoc());
4890 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4891
4892 // Overwrite our input TemplateArgumentLoc so that we can recover
4893 // properly.
4896
4897 break;
4898 }
4899 }
4900 // fallthrough
4901 [[fallthrough]];
4902 }
4903 default: {
4904 // We allow instantiateing a template with template argument packs when
4905 // building deduction guides.
4906 if (Arg.getKind() == TemplateArgument::Pack &&
4907 CodeSynthesisContexts.back().Kind ==
4909 SugaredConverted.push_back(Arg);
4910 CanonicalConverted.push_back(Arg);
4911 return false;
4912 }
4913 // We have a template type parameter but the template argument
4914 // is not a type.
4915 SourceRange SR = AL.getSourceRange();
4916 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4918
4919 return true;
4920 }
4921 }
4922
4923 if (CheckTemplateArgument(TSI))
4924 return true;
4925
4926 // Objective-C ARC:
4927 // If an explicitly-specified template argument type is a lifetime type
4928 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4929 if (getLangOpts().ObjCAutoRefCount &&
4930 ArgType->isObjCLifetimeType() &&
4931 !ArgType.getObjCLifetime()) {
4932 Qualifiers Qs;
4934 ArgType = Context.getQualifiedType(ArgType, Qs);
4935 }
4936
4937 SugaredConverted.push_back(TemplateArgument(ArgType));
4938 CanonicalConverted.push_back(
4940 return false;
4941}
4942
4943/// Substitute template arguments into the default template argument for
4944/// the given template type parameter.
4945///
4946/// \param SemaRef the semantic analysis object for which we are performing
4947/// the substitution.
4948///
4949/// \param Template the template that we are synthesizing template arguments
4950/// for.
4951///
4952/// \param TemplateLoc the location of the template name that started the
4953/// template-id we are checking.
4954///
4955/// \param RAngleLoc the location of the right angle bracket ('>') that
4956/// terminates the template-id.
4957///
4958/// \param Param the template template parameter whose default we are
4959/// substituting into.
4960///
4961/// \param Converted the list of template arguments provided for template
4962/// parameters that precede \p Param in the template parameter list.
4963///
4964/// \param Output the resulting substituted template argument.
4965///
4966/// \returns true if an error occurred.
4968 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4969 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4970 ArrayRef<TemplateArgument> SugaredConverted,
4971 ArrayRef<TemplateArgument> CanonicalConverted,
4972 TemplateArgumentLoc &Output) {
4973 Output = Param->getDefaultArgument();
4974
4975 // If the argument type is dependent, instantiate it now based
4976 // on the previously-computed template arguments.
4977 if (Output.getArgument().isInstantiationDependent()) {
4978 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4979 SugaredConverted,
4980 SourceRange(TemplateLoc, RAngleLoc));
4981 if (Inst.isInvalid())
4982 return true;
4983
4984 // Only substitute for the innermost template argument list.
4985 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4986 /*Final=*/true);
4987 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4988 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4989
4990 bool ForLambdaCallOperator = false;
4991 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4992 ForLambdaCallOperator = Rec->isLambda();
4993 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4994 !ForLambdaCallOperator);
4995
4996 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4997 Param->getDefaultArgumentLoc(),
4998 Param->getDeclName()))
4999 return true;
5000 }
5001
5002 return false;
5003}
5004
5005/// Substitute template arguments into the default template argument for
5006/// the given non-type template parameter.
5007///
5008/// \param SemaRef the semantic analysis object for which we are performing
5009/// the substitution.
5010///
5011/// \param Template the template that we are synthesizing template arguments
5012/// for.
5013///
5014/// \param TemplateLoc the location of the template name that started the
5015/// template-id we are checking.
5016///
5017/// \param RAngleLoc the location of the right angle bracket ('>') that
5018/// terminates the template-id.
5019///
5020/// \param Param the non-type template parameter whose default we are
5021/// substituting into.
5022///
5023/// \param Converted the list of template arguments provided for template
5024/// parameters that precede \p Param in the template parameter list.
5025///
5026/// \returns the substituted template argument, or NULL if an error occurred.
5028 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5029 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5030 ArrayRef<TemplateArgument> SugaredConverted,
5031 ArrayRef<TemplateArgument> CanonicalConverted,
5032 TemplateArgumentLoc &Output) {
5033 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5034 SugaredConverted,
5035 SourceRange(TemplateLoc, RAngleLoc));
5036 if (Inst.isInvalid())
5037 return true;
5038
5039 // Only substitute for the innermost template argument list.
5040 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5041 /*Final=*/true);
5042 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5043 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5044
5045 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5046 EnterExpressionEvaluationContext ConstantEvaluated(
5048 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5049 TemplateArgLists, Output);
5050}
5051
5052/// Substitute template arguments into the default template argument for
5053/// the given template template parameter.
5054///
5055/// \param SemaRef the semantic analysis object for which we are performing
5056/// the substitution.
5057///
5058/// \param Template the template that we are synthesizing template arguments
5059/// for.
5060///
5061/// \param TemplateLoc the location of the template name that started the
5062/// template-id we are checking.
5063///
5064/// \param RAngleLoc the location of the right angle bracket ('>') that
5065/// terminates the template-id.
5066///
5067/// \param Param the template template parameter whose default we are
5068/// substituting into.
5069///
5070/// \param Converted the list of template arguments provided for template
5071/// parameters that precede \p Param in the template parameter list.
5072///
5073/// \param QualifierLoc Will be set to the nested-name-specifier (with
5074/// source-location information) that precedes the template name.
5075///
5076/// \returns the substituted template argument, or NULL if an error occurred.
5078 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5079 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5080 ArrayRef<TemplateArgument> SugaredConverted,
5081 ArrayRef<TemplateArgument> CanonicalConverted,
5082 NestedNameSpecifierLoc &QualifierLoc) {
5084 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5085 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5086 if (Inst.isInvalid())
5087 return TemplateName();
5088
5089 // Only substitute for the innermost template argument list.
5090 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5091 /*Final=*/true);
5092 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5093 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5094
5095 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5096 // Substitute into the nested-name-specifier first,
5097 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5098 if (QualifierLoc) {
5099 QualifierLoc =
5100 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5101 if (!QualifierLoc)
5102 return TemplateName();
5103 }
5104
5105 return SemaRef.SubstTemplateName(
5106 QualifierLoc,
5109 TemplateArgLists);
5110}
5111
5113 TemplateDecl *Template, SourceLocation TemplateLoc,
5114 SourceLocation RAngleLoc, Decl *Param,
5115 ArrayRef<TemplateArgument> SugaredConverted,
5116 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5117 HasDefaultArg = false;
5118
5119 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5120 if (!hasReachableDefaultArgument(TypeParm))
5121 return TemplateArgumentLoc();
5122
5123 HasDefaultArg = true;
5124 TemplateArgumentLoc Output;
5125 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5126 TypeParm, SugaredConverted,
5127 CanonicalConverted, Output))
5128 return TemplateArgumentLoc();
5129 return Output;
5130 }
5131
5132 if (NonTypeTemplateParmDecl *NonTypeParm
5133 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5134 if (!hasReachableDefaultArgument(NonTypeParm))
5135 return TemplateArgumentLoc();
5136
5137 HasDefaultArg = true;
5138 TemplateArgumentLoc Output;
5139 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5140 NonTypeParm, SugaredConverted,
5141 CanonicalConverted, Output))
5142 return TemplateArgumentLoc();
5143 return Output;
5144 }
5145
5146 TemplateTemplateParmDecl *TempTempParm
5147 = cast<TemplateTemplateParmDecl>(Param);
5148 if (!hasReachableDefaultArgument(TempTempParm))
5149 return TemplateArgumentLoc();
5150
5151 HasDefaultArg = true;
5152 NestedNameSpecifierLoc QualifierLoc;
5154 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5155 CanonicalConverted, QualifierLoc);
5156 if (TName.isNull())
5157 return TemplateArgumentLoc();
5158
5159 return TemplateArgumentLoc(
5160 Context, TemplateArgument(TName),
5162 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5163}
5164
5165/// Convert a template-argument that we parsed as a type into a template, if
5166/// possible. C++ permits injected-class-names to perform dual service as
5167/// template template arguments and as template type arguments.
5170 // Extract and step over any surrounding nested-name-specifier.
5171 NestedNameSpecifierLoc QualLoc;
5172 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5173 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5174 return TemplateArgumentLoc();
5175
5176 QualLoc = ETLoc.getQualifierLoc();
5177 TLoc = ETLoc.getNamedTypeLoc();
5178 }
5179 // If this type was written as an injected-class-name, it can be used as a
5180 // template template argument.
5181 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5182 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5183 QualLoc, InjLoc.getNameLoc());
5184
5185 // If this type was written as an injected-class-name, it may have been
5186 // converted to a RecordType during instantiation. If the RecordType is
5187 // *not* wrapped in a TemplateSpecializationType and denotes a class
5188 // template specialization, it must have come from an injected-class-name.
5189 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5190 if (auto *CTSD =
5191 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5192 return TemplateArgumentLoc(Context,
5193 TemplateName(CTSD->getSpecializedTemplate()),
5194 QualLoc, RecLoc.getNameLoc());
5195
5196 return TemplateArgumentLoc();
5197}
5198
5200 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5201 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5202 unsigned ArgumentPackIndex,
5203 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5204 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5206 // Check template type parameters.
5207 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5208 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5209 CanonicalConverted);
5210
5211 // Check non-type template parameters.
5212 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5213 // Do substitution on the type of the non-type template parameter
5214 // with the template arguments we've seen thus far. But if the
5215 // template has a dependent context then we cannot substitute yet.
5216 QualType NTTPType = NTTP->getType();
5217 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5218 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5219
5220 if (NTTPType->isInstantiationDependentType() &&
5221 !isa<TemplateTemplateParmDecl>(Template) &&
5222 !Template->getDeclContext()->isDependentContext()) {
5223 // Do substitution on the type of the non-type template parameter.
5224 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5225 SugaredConverted,
5226 SourceRange(TemplateLoc, RAngleLoc));
5227 if (Inst.isInvalid())
5228 return true;
5229
5230 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5231 /*Final=*/true);
5232 // If the parameter is a pack expansion, expand this slice of the pack.
5233 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5235 ArgumentPackIndex);
5236 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5237 NTTP->getDeclName());
5238 } else {
5239 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5240 NTTP->getDeclName());
5241 }
5242
5243 // If that worked, check the non-type template parameter type
5244 // for validity.
5245 if (!NTTPType.isNull())
5246 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5247 NTTP->getLocation());
5248 if (NTTPType.isNull())
5249 return true;
5250 }
5251
5252 switch (Arg.getArgument().getKind()) {
5254 llvm_unreachable("Should never see a NULL template argument here");
5255
5257 Expr *E = Arg.getArgument().getAsExpr();
5258 TemplateArgument SugaredResult, CanonicalResult;
5259 unsigned CurSFINAEErrors = NumSFINAEErrors;
5260 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5261 CanonicalResult, CTAK);
5262 if (Res.isInvalid())
5263 return true;
5264 // If the current template argument causes an error, give up now.
5265 if (CurSFINAEErrors < NumSFINAEErrors)
5266 return true;
5267
5268 // If the resulting expression is new, then use it in place of the
5269 // old expression in the template argument.
5270 if (Res.get() != E) {
5271 TemplateArgument TA(Res.get());
5272 Arg = TemplateArgumentLoc(TA, Res.get());
5273 }
5274
5275 SugaredConverted.push_back(SugaredResult);
5276 CanonicalConverted.push_back(CanonicalResult);
5277 break;
5278 }
5279
5284 // We've already checked this template argument, so just copy
5285 // it to the list of converted arguments.
5286 SugaredConverted.push_back(Arg.getArgument());
5287 CanonicalConverted.push_back(
5289 break;
5290
5293 // We were given a template template argument. It may not be ill-formed;
5294 // see below.
5295 if (DependentTemplateName *DTN
5298 // We have a template argument such as \c T::template X, which we
5299 // parsed as a template template argument. However, since we now
5300 // know that we need a non-type template argument, convert this
5301 // template name into an expression.
5302
5303 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5304 Arg.getTemplateNameLoc());
5305
5306 CXXScopeSpec SS;
5308 // FIXME: the template-template arg was a DependentTemplateName,
5309 // so it was provided with a template keyword. However, its source
5310 // location is not stored in the template argument structure.
5311 SourceLocation TemplateKWLoc;
5313 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5314 nullptr);
5315
5316 // If we parsed the template argument as a pack expansion, create a
5317 // pack expansion expression.
5320 if (E.isInvalid())
5321 return true;
5322 }
5323
5324 TemplateArgument SugaredResult, CanonicalResult;
5325 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5326 CanonicalResult, CTAK_Specified);
5327 if (E.isInvalid())
5328 return true;
5329
5330 SugaredConverted.push_back(SugaredResult);
5331 CanonicalConverted.push_back(CanonicalResult);
5332 break;
5333 }
5334
5335 // We have a template argument that actually does refer to a class
5336 // template, alias template, or template template parameter, and
5337 // therefore cannot be a non-type template argument.
5338 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5339 << Arg.getSourceRange();
5341
5342 return true;
5343
5345 // We have a non-type template parameter but the template
5346 // argument is a type.
5347
5348 // C++ [temp.arg]p2:
5349 // In a template-argument, an ambiguity between a type-id and
5350 // an expression is resolved to a type-id, regardless of the
5351 // form of the corresponding template-parameter.
5352 //
5353 // We warn specifically about this case, since it can be rather
5354 // confusing for users.
5355 QualType T = Arg.getArgument().getAsType();
5356 SourceRange SR = Arg.getSourceRange();
5357 if (T->isFunctionType())
5358 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5359 else
5360 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5362 return true;
5363 }
5364
5366 llvm_unreachable("Caller must expand template argument packs");
5367 }
5368
5369 return false;
5370 }
5371
5372
5373 // Check template template parameters.
5374 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5375
5376 TemplateParameterList *Params = TempParm->getTemplateParameters();
5377 if (TempParm->isExpandedParameterPack())
5378 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5379
5380 // Substitute into the template parameter list of the template
5381 // template parameter, since previously-supplied template arguments
5382 // may appear within the template template parameter.
5383 //
5384 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5385 {
5386 // Set up a template instantiation context.
5388 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5389 SugaredConverted,
5390 SourceRange(TemplateLoc, RAngleLoc));
5391 if (Inst.isInvalid())
5392 return true;
5393
5394 Params =
5397 Template, SugaredConverted, /*Final=*/true),
5398 /*EvaluateConstraints=*/false);
5399 if (!Params)
5400 return true;
5401 }
5402
5403 // C++1z [temp.local]p1: (DR1004)
5404 // When [the injected-class-name] is used [...] as a template-argument for
5405 // a template template-parameter [...] it refers to the class template
5406 // itself.
5410 if (!ConvertedArg.getArgument().isNull())
5411 Arg = ConvertedArg;
5412 }
5413
5414 switch (Arg.getArgument().getKind()) {
5416 llvm_unreachable("Should never see a NULL template argument here");
5417
5420 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5421 /*IsDeduced=*/CTAK != CTAK_Specified))
5422 return true;
5423
5424 SugaredConverted.push_back(Arg.getArgument());
5425 CanonicalConverted.push_back(
5427 break;
5428
5431 // We have a template template parameter but the template
5432 // argument does not refer to a template.
5433 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5434 << getLangOpts().CPlusPlus11;
5435 return true;
5436
5441 llvm_unreachable("non-type argument with template template parameter");
5442
5444 llvm_unreachable("Caller must expand template argument packs");
5445 }
5446
5447 return false;
5448}
5449
5450/// Diagnose a missing template argument.
5451template<typename TemplateParmDecl>
5453 TemplateDecl *TD,
5454 const TemplateParmDecl *D,
5456 // Dig out the most recent declaration of the template parameter; there may be
5457 // declarations of the template that are more recent than TD.
5458 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5459 ->getTemplateParameters()
5460 ->getParam(D->getIndex()));
5461
5462 // If there's a default argument that's not reachable, diagnose that we're
5463 // missing a module import.
5465 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5466 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5467 D->getDefaultArgumentLoc(), Modules,
5469 /*Recover*/true);
5470 return true;
5471 }
5472
5473 // FIXME: If there's a more recent default argument that *is* visible,
5474 // diagnose that it was declared too late.
5475
5477
5478 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5479 << /*not enough args*/0
5481 << TD;
5482 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5483 return true;
5484}
5485
5486/// Check that the given template argument list is well-formed
5487/// for specializing the given template.
5489 TemplateDecl *Template, SourceLocation TemplateLoc,
5490 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5491 bool PartialTemplateArgs,
5492 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5493 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5494 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5495 bool PartialOrderingTTP) {
5496
5498 *ConstraintsNotSatisfied = false;
5499
5500 // Make a copy of the template arguments for processing. Only make the
5501 // changes at the end when successful in matching the arguments to the
5502 // template.
5503 TemplateArgumentListInfo NewArgs = TemplateArgs;
5504
5506
5507 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5508
5509 // C++ [temp.arg]p1:
5510 // [...] The type and form of each template-argument specified in
5511 // a template-id shall match the type and form specified for the
5512 // corresponding parameter declared by the template in its
5513 // template-parameter-list.
5514 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5515 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5516 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5517 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5518 LocalInstantiationScope InstScope(*this, true);
5519 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5520 ParamEnd = Params->end(),
5521 Param = ParamBegin;
5522 Param != ParamEnd;
5523 /* increment in loop */) {
5524 if (size_t ParamIdx = Param - ParamBegin;
5525 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5526 // All written arguments should have been consumed by this point.
5527 assert(ArgIdx == NumArgs && "bad default argument deduction");
5528 // FIXME: Don't ignore parameter packs.
5529 if (ParamIdx == DefaultArgs.StartPos && !(*Param)->isParameterPack()) {
5530 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5531 // Default arguments from a DeducedTemplateName are already converted.
5532 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5533 SugaredConverted.push_back(DefArg);
5534 CanonicalConverted.push_back(
5536 ++Param;
5537 }
5538 continue;
5539 }
5540 }
5541
5542 // If we have an expanded parameter pack, make sure we don't have too
5543 // many arguments.
5544 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5545 if (*Expansions == SugaredArgumentPack.size()) {
5546 // We're done with this parameter pack. Pack up its arguments and add
5547 // them to the list.
5548 SugaredConverted.push_back(
5549 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5550 SugaredArgumentPack.clear();
5551
5552 CanonicalConverted.push_back(
5553 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5554 CanonicalArgumentPack.clear();
5555
5556 // This argument is assigned to the next parameter.
5557 ++Param;
5558 continue;
5559 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5560 // Not enough arguments for this parameter pack.
5561 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5562 << /*not enough args*/0
5564 << Template;
5565 NoteTemplateLocation(*Template, Params->getSourceRange());
5566 return true;
5567 }
5568 }
5569
5570 if (ArgIdx < NumArgs) {
5571 // Check the template argument we were given.
5572 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5573 RAngleLoc, SugaredArgumentPack.size(),
5574 SugaredConverted, CanonicalConverted,
5576 return true;
5577
5578 CanonicalConverted.back().setIsDefaulted(
5580 Context, NewArgs[ArgIdx].getArgument(), *Param,
5581 CanonicalConverted, Params->getDepth()));
5582
5583 bool PackExpansionIntoNonPack =
5584 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5585 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5586 // CWG1430: Don't diagnose this pack expansion when partial
5587 // ordering template template parameters. Some uses of the template could
5588 // be valid, and invalid uses will be diagnosed later during
5589 // instantiation.
5590 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5591 (isa<TypeAliasTemplateDecl>(Template) ||
5592 isa<ConceptDecl>(Template))) {
5593 // CWG1430: we have a pack expansion as an argument to an
5594 // alias template, and it's not part of a parameter pack. This
5595 // can't be canonicalized, so reject it now.
5596 // As for concepts - we cannot normalize constraints where this
5597 // situation exists.
5598 Diag(NewArgs[ArgIdx].getLocation(),
5599 diag::err_template_expansion_into_fixed_list)
5600 << (isa<ConceptDecl>(Template) ? 1 : 0)
5601 << NewArgs[ArgIdx].getSourceRange();
5603 return true;
5604 }
5605
5606 // We're now done with this argument.
5607 ++ArgIdx;
5608
5609 if ((*Param)->isTemplateParameterPack()) {
5610 // The template parameter was a template parameter pack, so take the
5611 // deduced argument and place it on the argument pack. Note that we
5612 // stay on the same template parameter so that we can deduce more
5613 // arguments.
5614 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5615 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5616 } else {
5617 // Move to the next template parameter.
5618 ++Param;
5619 }
5620
5621 // If we just saw a pack expansion into a non-pack, then directly convert
5622 // the remaining arguments, because we don't know what parameters they'll
5623 // match up with.
5624 if (PackExpansionIntoNonPack) {
5625 if (!SugaredArgumentPack.empty()) {
5626 // If we were part way through filling in an expanded parameter pack,
5627 // fall back to just producing individual arguments.
5628 SugaredConverted.insert(SugaredConverted.end(),
5629 SugaredArgumentPack.begin(),
5630 SugaredArgumentPack.end());
5631 SugaredArgumentPack.clear();
5632
5633 CanonicalConverted.insert(CanonicalConverted.end(),
5634 CanonicalArgumentPack.begin(),
5635 CanonicalArgumentPack.end());
5636 CanonicalArgumentPack.clear();
5637 }
5638
5639 while (ArgIdx < NumArgs) {
5640 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5641 SugaredConverted.push_back(Arg);
5642 CanonicalConverted.push_back(
5644 ++ArgIdx;
5645 }
5646
5647 return false;
5648 }
5649
5650 continue;
5651 }
5652
5653 // If we're checking a partial template argument list, we're done.
5654 if (PartialTemplateArgs) {
5655 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5656 SugaredConverted.push_back(
5657 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5658 CanonicalConverted.push_back(
5659 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5660 }
5661 return false;
5662 }
5663
5664 // If we have a template parameter pack with no more corresponding
5665 // arguments, just break out now and we'll fill in the argument pack below.
5666 if ((*Param)->isTemplateParameterPack()) {
5667 assert(!getExpandedPackSize(*Param) &&
5668 "Should have dealt with this already");
5669
5670 // A non-expanded parameter pack before the end of the parameter list
5671 // only occurs for an ill-formed template parameter list, unless we've
5672 // got a partial argument list for a function template, so just bail out.
5673 if (Param + 1 != ParamEnd) {
5674 assert(
5675 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5676 "Concept templates must have parameter packs at the end.");
5677 return true;
5678 }
5679
5680 SugaredConverted.push_back(
5681 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5682 SugaredArgumentPack.clear();
5683
5684 CanonicalConverted.push_back(
5685 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5686 CanonicalArgumentPack.clear();
5687
5688 ++Param;
5689 continue;
5690 }
5691
5692 // Check whether we have a default argument.
5693 bool HasDefaultArg;
5694
5695 // Retrieve the default template argument from the template
5696 // parameter. For each kind of template parameter, we substitute the
5697 // template arguments provided thus far and any "outer" template arguments
5698 // (when the template parameter was part of a nested template) into
5699 // the default argument.
5701 Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5702 CanonicalConverted, HasDefaultArg);
5703
5704 if (Arg.getArgument().isNull()) {
5705 if (!HasDefaultArg) {
5706 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5707 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5708 NewArgs);
5709 if (NonTypeTemplateParmDecl *NTTP =
5710 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5711 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5712 NewArgs);
5713 return diagnoseMissingArgument(*this, TemplateLoc, Template,
5714 cast<TemplateTemplateParmDecl>(*Param),
5715 NewArgs);
5716 }
5717 return true;
5718 }
5719
5720 // Introduce an instantiation record that describes where we are using
5721 // the default template argument. We're not actually instantiating a
5722 // template here, we just create this object to put a note into the
5723 // context stack.
5724 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5725 SugaredConverted,
5726 SourceRange(TemplateLoc, RAngleLoc));
5727 if (Inst.isInvalid())
5728 return true;
5729
5730 // Check the default template argument.
5731 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5732 SugaredConverted, CanonicalConverted,
5734 return true;
5735
5736 SugaredConverted.back().setIsDefaulted(true);
5737 CanonicalConverted.back().setIsDefaulted(true);
5738
5739 // Core issue 150 (assumed resolution): if this is a template template
5740 // parameter, keep track of the default template arguments from the
5741 // template definition.
5742 if (isTemplateTemplateParameter)
5743 NewArgs.addArgument(Arg);
5744
5745 // Move to the next template parameter and argument.
5746 ++Param;
5747 ++ArgIdx;
5748 }
5749
5750 // If we're performing a partial argument substitution, allow any trailing
5751 // pack expansions; they might be empty. This can happen even if
5752 // PartialTemplateArgs is false (the list of arguments is complete but
5753 // still dependent).
5754 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5756 while (ArgIdx < NumArgs &&
5757 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5758 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5759 SugaredConverted.push_back(Arg);
5760 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5761 }
5762 }
5763
5764 // If we have any leftover arguments, then there were too many arguments.
5765 // Complain and fail.
5766 if (ArgIdx < NumArgs) {
5767 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5768 << /*too many args*/1
5770 << Template
5771 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5772 NoteTemplateLocation(*Template, Params->getSourceRange());
5773 return true;
5774 }
5775
5776 // No problems found with the new argument list, propagate changes back
5777 // to caller.
5778 if (UpdateArgsWithConversions)
5779 TemplateArgs = std::move(NewArgs);
5780
5781 if (!PartialTemplateArgs) {
5782 // Setup the context/ThisScope for the case where we are needing to
5783 // re-instantiate constraints outside of normal instantiation.
5784 DeclContext *NewContext = Template->getDeclContext();
5785
5786 // If this template is in a template, make sure we extract the templated
5787 // decl.
5788 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5789 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5790 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5791
5792 Qualifiers ThisQuals;
5793 if (const auto *Method =
5794 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5795 ThisQuals = Method->getMethodQualifiers();
5796
5797 ContextRAII Context(*this, NewContext);
5798 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5799
5801 Template, NewContext, /*Final=*/false, CanonicalConverted,
5802 /*RelativeToPrimary=*/true,
5803 /*Pattern=*/nullptr,
5804 /*ForConceptInstantiation=*/true);
5806 Template, MLTAL,
5807 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5810 return true;
5811 }
5812 }
5813
5814 return false;
5815}
5816
5817namespace {
5818 class UnnamedLocalNoLinkageFinder
5819 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5820 {
5821 Sema &S;
5822 SourceRange SR;
5823
5825
5826 public:
5827 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5828
5829 bool Visit(QualType T) {
5830 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5831 }
5832
5833#define TYPE(Class, Parent) \
5834 bool Visit##Class##Type(const Class##Type *);
5835#define ABSTRACT_TYPE(Class, Parent) \
5836 bool Visit##Class##Type(const Class##Type *) { return false; }
5837#define NON_CANONICAL_TYPE(Class, Parent) \
5838 bool Visit##Class##Type(const Class##Type *) { return false; }
5839#include "clang/AST/TypeNodes.inc"
5840
5841 bool VisitTagDecl(const TagDecl *Tag);
5842 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5843 };
5844} // end anonymous namespace
5845
5846bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5847 return false;
5848}
5849
5850bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5851 return Visit(T->getElementType());
5852}
5853
5854bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5855 return Visit(T->getPointeeType());
5856}
5857
5858bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5859 const BlockPointerType* T) {
5860 return Visit(T->getPointeeType());
5861}
5862
5863bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5864 const LValueReferenceType* T) {
5865 return Visit(T->getPointeeType());
5866}
5867
5868bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5869 const RValueReferenceType* T) {
5870 return Visit(T->getPointeeType());
5871}
5872
5873bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5874 const MemberPointerType* T) {
5875 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5876}
5877
5878bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5879 const ConstantArrayType* T) {
5880 return Visit(T->getElementType());
5881}
5882
5883bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5884 const IncompleteArrayType* T) {
5885 return Visit(T->getElementType());
5886}
5887
5888bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5889 const VariableArrayType* T) {
5890 return Visit(T->getElementType());
5891}
5892
5893bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5894 const DependentSizedArrayType* T) {
5895 return Visit(T->getElementType());
5896}
5897
5898bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5900 return Visit(T->getElementType());
5901}
5902
5903bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5904 const DependentSizedMatrixType *T) {
5905 return Visit(T->getElementType());
5906}
5907
5908bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5910 return Visit(T->getPointeeType());
5911}
5912
5913bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5914 return Visit(T->getElementType());
5915}
5916
5917bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5918 const DependentVectorType *T) {
5919 return Visit(T->getElementType());
5920}
5921
5922bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5923 return Visit(T->getElementType());
5924}
5925
5926bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5927 const ConstantMatrixType *T) {
5928 return Visit(T->getElementType());
5929}
5930
5931bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5932 const FunctionProtoType* T) {
5933 for (const auto &A : T->param_types()) {
5934 if (Visit(A))
5935 return true;
5936 }
5937
5938 return Visit(T->getReturnType());
5939}
5940
5941bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5942 const FunctionNoProtoType* T) {
5943 return Visit(T->getReturnType());
5944}
5945
5946bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5947 const UnresolvedUsingType*) {
5948 return false;
5949}
5950
5951bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5952 return false;
5953}
5954
5955bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5956 return Visit(T->getUnmodifiedType());
5957}
5958
5959bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5960 return false;
5961}
5962
5963bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5964 const PackIndexingType *) {
5965 return false;
5966}
5967
5968bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5969 const UnaryTransformType*) {
5970 return false;
5971}
5972
5973bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5974 return Visit(T->getDeducedType());
5975}
5976
5977bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5979 return Visit(T->getDeducedType());
5980}
5981
5982bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5983 return VisitTagDecl(T->getDecl());
5984}
5985
5986bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5987 return VisitTagDecl(T->getDecl());
5988}
5989
5990bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5991 const TemplateTypeParmType*) {
5992 return false;
5993}
5994
5995bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5997 return false;
5998}
5999
6000bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6002 return false;
6003}
6004
6005bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6006 const InjectedClassNameType* T) {
6007 return VisitTagDecl(T->getDecl());
6008}
6009
6010bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6011 const DependentNameType* T) {
6012 return VisitNestedNameSpecifier(T->getQualifier());
6013}
6014
6015bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6017 if (auto *Q = T->getQualifier())
6018 return VisitNestedNameSpecifier(Q);
6019 return false;
6020}
6021
6022bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6023 const PackExpansionType* T) {
6024 return Visit(T->getPattern());
6025}
6026
6027bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6028 return false;
6029}
6030
6031bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6032 const ObjCInterfaceType *) {
6033 return false;
6034}
6035
6036bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6037 const ObjCObjectPointerType *) {
6038 return false;
6039}
6040
6041bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6042 return Visit(T->getValueType());
6043}
6044
6045bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6046 return false;
6047}
6048
6049bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6050 return false;
6051}
6052
6053bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6054 const ArrayParameterType *T) {
6055 return VisitConstantArrayType(T);
6056}
6057
6058bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6059 const DependentBitIntType *T) {
6060 return false;
6061}
6062
6063bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6064 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6065 S.Diag(SR.getBegin(),
6066 S.getLangOpts().CPlusPlus11 ?
6067 diag::warn_cxx98_compat_template_arg_local_type :
6068 diag::ext_template_arg_local_type)
6069 << S.Context.getTypeDeclType(Tag) << SR;
6070 return true;
6071 }
6072
6073 if (!Tag->hasNameForLinkage()) {
6074 S.Diag(SR.getBegin(),
6075 S.getLangOpts().CPlusPlus11 ?
6076 diag::warn_cxx98_compat_template_arg_unnamed_type :
6077 diag::ext_template_arg_unnamed_type) << SR;
6078 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6079 return true;
6080 }
6081
6082 return false;
6083}
6084
6085bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6086 NestedNameSpecifier *NNS) {
6087 assert(NNS);
6088 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6089 return true;
6090
6091 switch (NNS->getKind()) {
6097 return false;
6098
6101 return Visit(QualType(NNS->getAsType(), 0));
6102 }
6103 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6104}
6105
6106bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6108 if (T->hasContainedType() && Visit(T->getContainedType()))
6109 return true;
6110 return Visit(T->getWrappedType());
6111}
6112
6114 assert(ArgInfo && "invalid TypeSourceInfo");
6115 QualType Arg = ArgInfo->getType();
6116 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6117 QualType CanonArg = Context.getCanonicalType(Arg);
6118
6119 if (CanonArg->isVariablyModifiedType()) {
6120 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6122 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6123 }
6124
6125 // C++03 [temp.arg.type]p2:
6126 // A local type, a type with no linkage, an unnamed type or a type
6127 // compounded from any of these types shall not be used as a
6128 // template-argument for a template type-parameter.
6129 //
6130 // C++11 allows these, and even in C++03 we allow them as an extension with
6131 // a warning.
6132 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6133 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6134 (void)Finder.Visit(CanonArg);
6135 }
6136
6137 return false;
6138}
6139
6143 NPV_Error
6145
6146/// Determine whether the given template argument is a null pointer
6147/// value of the appropriate type.
6150 QualType ParamType, Expr *Arg,
6151 Decl *Entity = nullptr) {
6152 if (Arg->isValueDependent() || Arg->isTypeDependent())
6153 return NPV_NotNullPointer;
6154
6155 // dllimport'd entities aren't constant but are available inside of template
6156 // arguments.
6157 if (Entity && Entity->hasAttr<DLLImportAttr>())
6158 return NPV_NotNullPointer;
6159
6160 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6161 llvm_unreachable(
6162 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6163
6164 if (!S.getLangOpts().CPlusPlus11)
6165 return NPV_NotNullPointer;
6166
6167 // Determine whether we have a constant expression.
6169 if (ArgRV.isInvalid())
6170 return NPV_Error;
6171 Arg = ArgRV.get();
6172
6173 Expr::EvalResult EvalResult;
6175 EvalResult.Diag = &Notes;
6176 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6177 EvalResult.HasSideEffects) {
6178 SourceLocation DiagLoc = Arg->getExprLoc();
6179
6180 // If our only note is the usual "invalid subexpression" note, just point
6181 // the caret at its location rather than producing an essentially
6182 // redundant note.
6183 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6184 diag::note_invalid_subexpr_in_const_expr) {
6185 DiagLoc = Notes[0].first;
6186 Notes.clear();
6187 }
6188
6189 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6190 << Arg->getType() << Arg->getSourceRange();
6191 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6192 S.Diag(Notes[I].first, Notes[I].second);
6193
6195 return NPV_Error;
6196 }
6197
6198 // C++11 [temp.arg.nontype]p1:
6199 // - an address constant expression of type std::nullptr_t
6200 if (Arg->getType()->isNullPtrType())
6201 return NPV_NullPointer;
6202
6203 // - a constant expression that evaluates to a null pointer value (4.10); or
6204 // - a constant expression that evaluates to a null member pointer value
6205 // (4.11); or
6206 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6207 (EvalResult.Val.isMemberPointer() &&
6208 !EvalResult.Val.getMemberPointerDecl())) {
6209 // If our expression has an appropriate type, we've succeeded.
6210 bool ObjCLifetimeConversion;
6211 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6212 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6213 ObjCLifetimeConversion))
6214 return NPV_NullPointer;
6215
6216 // The types didn't match, but we know we got a null pointer; complain,
6217 // then recover as if the types were correct.
6218 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6219 << Arg->getType() << ParamType << Arg->getSourceRange();
6221 return NPV_NullPointer;
6222 }
6223
6224 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6225 // We found a pointer that isn't null, but doesn't refer to an object.
6226 // We could just return NPV_NotNullPointer, but we can print a better
6227 // message with the information we have here.
6228 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6229 << EvalResult.Val.getAsString(S.Context, ParamType);
6231 return NPV_Error;
6232 }
6233
6234 // If we don't have a null pointer value, but we do have a NULL pointer
6235 // constant, suggest a cast to the appropriate type.
6237 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6238 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6239 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6241 ")");
6243 return NPV_NullPointer;
6244 }
6245
6246 // FIXME: If we ever want to support general, address-constant expressions
6247 // as non-type template arguments, we should return the ExprResult here to
6248 // be interpreted by the caller.
6249 return NPV_NotNullPointer;
6250}
6251
6252/// Checks whether the given template argument is compatible with its
6253/// template parameter.
6255 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6256 Expr *Arg, QualType ArgType) {
6257 bool ObjCLifetimeConversion;
6258 if (ParamType->isPointerType() &&
6259 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6260 S.IsQualificationConversion(ArgType, ParamType, false,
6261 ObjCLifetimeConversion)) {
6262 // For pointer-to-object types, qualification conversions are
6263 // permitted.
6264 } else {
6265 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6266 if (!ParamRef->getPointeeType()->isFunctionType()) {
6267 // C++ [temp.arg.nontype]p5b3:
6268 // For a non-type template-parameter of type reference to
6269 // object, no conversions apply. The type referred to by the
6270 // reference may be more cv-qualified than the (otherwise
6271 // identical) type of the template- argument. The
6272 // template-parameter is bound directly to the
6273 // template-argument, which shall be an lvalue.
6274
6275 // FIXME: Other qualifiers?
6276 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6277 unsigned ArgQuals = ArgType.getCVRQualifiers();
6278
6279 if ((ParamQuals | ArgQuals) != ParamQuals) {
6280 S.Diag(Arg->getBeginLoc(),
6281 diag::err_template_arg_ref_bind_ignores_quals)
6282 << ParamType << Arg->getType() << Arg->getSourceRange();
6284 return true;
6285 }
6286 }
6287 }
6288
6289 // At this point, the template argument refers to an object or
6290 // function with external linkage. We now need to check whether the
6291 // argument and parameter types are compatible.
6292 if (!S.Context.hasSameUnqualifiedType(ArgType,
6293 ParamType.getNonReferenceType())) {
6294 // We can't perform this conversion or binding.
6295 if (ParamType->isReferenceType())
6296 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6297 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6298 else
6299 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6300 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6302 return true;
6303 }
6304 }
6305
6306 return false;
6307}
6308
6309/// Checks whether the given template argument is the address
6310/// of an object or function according to C++ [temp.arg.nontype]p1.
6312 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6313 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6314 bool Invalid = false;
6315 Expr *Arg = ArgIn;
6316 QualType ArgType = Arg->getType();
6317
6318 bool AddressTaken = false;
6319 SourceLocation AddrOpLoc;
6320 if (S.getLangOpts().MicrosoftExt) {
6321 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6322 // dereference and address-of operators.
6323 Arg = Arg->IgnoreParenCasts();
6324
6325 bool ExtWarnMSTemplateArg = false;
6326 UnaryOperatorKind FirstOpKind;
6327 SourceLocation FirstOpLoc;
6328 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6329 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6330 if (UnOpKind == UO_Deref)
6331 ExtWarnMSTemplateArg = true;
6332 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6333 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6334 if (!AddrOpLoc.isValid()) {
6335 FirstOpKind = UnOpKind;
6336 FirstOpLoc = UnOp->getOperatorLoc();
6337 }
6338 } else
6339 break;
6340 }
6341 if (FirstOpLoc.isValid()) {
6342 if (ExtWarnMSTemplateArg)
6343 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6344 << ArgIn->getSourceRange();
6345
6346 if (FirstOpKind == UO_AddrOf)
6347 AddressTaken = true;
6348 else if (Arg->getType()->isPointerType()) {
6349 // We cannot let pointers get dereferenced here, that is obviously not a
6350 // constant expression.
6351 assert(FirstOpKind == UO_Deref);
6352 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6353 << Arg->getSourceRange();
6354 }
6355 }
6356 } else {
6357 // See through any implicit casts we added to fix the type.
6358 Arg = Arg->IgnoreImpCasts();
6359
6360 // C++ [temp.arg.nontype]p1:
6361 //
6362 // A template-argument for a non-type, non-template
6363 // template-parameter shall be one of: [...]
6364 //
6365 // -- the address of an object or function with external
6366 // linkage, including function templates and function
6367 // template-ids but excluding non-static class members,
6368 // expressed as & id-expression where the & is optional if
6369 // the name refers to a function or array, or if the
6370 // corresponding template-parameter is a reference; or
6371
6372 // In C++98/03 mode, give an extension warning on any extra parentheses.
6373 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6374 bool ExtraParens = false;
6375 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6376 if (!Invalid && !ExtraParens) {
6377 S.Diag(Arg->getBeginLoc(),
6378 S.getLangOpts().CPlusPlus11
6379 ? diag::warn_cxx98_compat_template_arg_extra_parens
6380 : diag::ext_template_arg_extra_parens)
6381 << Arg->getSourceRange();
6382 ExtraParens = true;
6383 }
6384
6385 Arg = Parens->getSubExpr();
6386 }
6387
6388 while (SubstNonTypeTemplateParmExpr *subst =
6389 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6390 Arg = subst->getReplacement()->IgnoreImpCasts();
6391
6392 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6393 if (UnOp->getOpcode() == UO_AddrOf) {
6394 Arg = UnOp->getSubExpr();
6395 AddressTaken = true;
6396 AddrOpLoc = UnOp->getOperatorLoc();
6397 }
6398 }
6399
6400 while (SubstNonTypeTemplateParmExpr *subst =
6401 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6402 Arg = subst->getReplacement()->IgnoreImpCasts();
6403 }
6404
6405 ValueDecl *Entity = nullptr;
6406 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6407 Entity = DRE->getDecl();
6408 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6409 Entity = CUE->getGuidDecl();
6410
6411 // If our parameter has pointer type, check for a null template value.
6412 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6413 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6414 Entity)) {
6415 case NPV_NullPointer:
6416 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6417 SugaredConverted = TemplateArgument(ParamType,
6418 /*isNullPtr=*/true);
6419 CanonicalConverted =
6421 /*isNullPtr=*/true);
6422 return false;
6423
6424 case NPV_Error:
6425 return true;
6426
6427 case NPV_NotNullPointer:
6428 break;
6429 }
6430 }
6431
6432 // Stop checking the precise nature of the argument if it is value dependent,
6433 // it should be checked when instantiated.
6434 if (Arg->isValueDependent()) {
6435 SugaredConverted = TemplateArgument(ArgIn);
6436 CanonicalConverted =
6437 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6438 return false;
6439 }
6440
6441 if (!Entity) {
6442 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6443 << Arg->getSourceRange();
6445 return true;
6446 }
6447
6448 // Cannot refer to non-static data members
6449 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6450 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6451 << Entity << Arg->getSourceRange();
6453 return true;
6454 }
6455
6456 // Cannot refer to non-static member functions
6457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6458 if (!Method->isStatic()) {
6459 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6460 << Method << Arg->getSourceRange();
6462 return true;
6463 }
6464 }
6465
6466 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6467 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6468 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6469
6470 // A non-type template argument must refer to an object or function.
6471 if (!Func && !Var && !Guid) {
6472 // We found something, but we don't know specifically what it is.
6473 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6474 << Arg->getSourceRange();
6475 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6476 return true;
6477 }
6478
6479 // Address / reference template args must have external linkage in C++98.
6480 if (Entity->getFormalLinkage() == Linkage::Internal) {
6481 S.Diag(Arg->getBeginLoc(),
6482 S.getLangOpts().CPlusPlus11
6483 ? diag::warn_cxx98_compat_template_arg_object_internal
6484 : diag::ext_template_arg_object_internal)
6485 << !Func << Entity << Arg->getSourceRange();
6486 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6487 << !Func;
6488 } else if (!Entity->hasLinkage()) {
6489 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6490 << !Func << Entity << Arg->getSourceRange();
6491 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6492 << !Func;
6493 return true;
6494 }
6495
6496 if (Var) {
6497 // A value of reference type is not an object.
6498 if (Var->getType()->isReferenceType()) {
6499 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6500 << Var->getType() << Arg->getSourceRange();
6502 return true;
6503 }
6504
6505 // A template argument must have static storage duration.
6506 if (Var->getTLSKind()) {
6507 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6508 << Arg->getSourceRange();
6509 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6510 return true;
6511 }
6512 }
6513
6514 if (AddressTaken && ParamType->isReferenceType()) {
6515 // If we originally had an address-of operator, but the
6516 // parameter has reference type, complain and (if things look
6517 // like they will work) drop the address-of operator.
6518 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6519 ParamType.getNonReferenceType())) {
6520 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6521 << ParamType;
6523 return true;
6524 }
6525
6526 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6527 << ParamType
6528 << FixItHint::CreateRemoval(AddrOpLoc);
6530
6531 ArgType = Entity->getType();
6532 }
6533
6534 // If the template parameter has pointer type, either we must have taken the
6535 // address or the argument must decay to a pointer.
6536 if (!AddressTaken && ParamType->isPointerType()) {
6537 if (Func) {
6538 // Function-to-pointer decay.
6539 ArgType = S.Context.getPointerType(Func->getType());
6540 } else if (Entity->getType()->isArrayType()) {
6541 // Array-to-pointer decay.
6542 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6543 } else {
6544 // If the template parameter has pointer type but the address of
6545 // this object was not taken, complain and (possibly) recover by
6546 // taking the address of the entity.
6547 ArgType = S.Context.getPointerType(Entity->getType());
6548 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6549 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6550 << ParamType;
6552 return true;
6553 }
6554
6555 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6556 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6557
6559 }
6560 }
6561
6562 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6563 Arg, ArgType))
6564 return true;
6565
6566 // Create the template argument.
6567 SugaredConverted = TemplateArgument(Entity, ParamType);
6568 CanonicalConverted =
6569 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6570 S.Context.getCanonicalType(ParamType));
6571 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6572 return false;
6573}
6574
6575/// Checks whether the given template argument is a pointer to
6576/// member constant according to C++ [temp.arg.nontype]p1.
6577static bool
6579 QualType ParamType, Expr *&ResultArg,
6580 TemplateArgument &SugaredConverted,
6581 TemplateArgument &CanonicalConverted) {
6582 bool Invalid = false;
6583
6584 Expr *Arg = ResultArg;
6585 bool ObjCLifetimeConversion;
6586
6587 // C++ [temp.arg.nontype]p1:
6588 //
6589 // A template-argument for a non-type, non-template
6590 // template-parameter shall be one of: [...]
6591 //
6592 // -- a pointer to member expressed as described in 5.3.1.
6593 DeclRefExpr *DRE = nullptr;
6594
6595 // In C++98/03 mode, give an extension warning on any extra parentheses.
6596 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6597 bool ExtraParens = false;
6598 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6599 if (!Invalid && !ExtraParens) {
6600 S.Diag(Arg->getBeginLoc(),
6601 S.getLangOpts().CPlusPlus11
6602 ? diag::warn_cxx98_compat_template_arg_extra_parens
6603 : diag::ext_template_arg_extra_parens)
6604 << Arg->getSourceRange();
6605 ExtraParens = true;
6606 }
6607
6608 Arg = Parens->getSubExpr();
6609 }
6610
6611 while (SubstNonTypeTemplateParmExpr *subst =
6612 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6613 Arg = subst->getReplacement()->IgnoreImpCasts();
6614
6615 // A pointer-to-member constant written &Class::member.
6616 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6617 if (UnOp->getOpcode() == UO_AddrOf) {
6618 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6619 if (DRE && !DRE->getQualifier())
6620 DRE = nullptr;
6621 }
6622 }
6623 // A constant of pointer-to-member type.
6624 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6625 ValueDecl *VD = DRE->getDecl();
6626 if (VD->getType()->isMemberPointerType()) {
6627 if (isa<NonTypeTemplateParmDecl>(VD)) {
6628 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6629 SugaredConverted = TemplateArgument(Arg);
6630 CanonicalConverted =
6631 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6632 } else {
6633 SugaredConverted = TemplateArgument(VD, ParamType);
6634 CanonicalConverted =
6635 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6636 S.Context.getCanonicalType(ParamType));
6637 }
6638 return Invalid;
6639 }
6640 }
6641
6642 DRE = nullptr;
6643 }
6644
6645 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6646
6647 // Check for a null pointer value.
6648 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6649 Entity)) {
6650 case NPV_Error:
6651 return true;
6652 case NPV_NullPointer:
6653 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6654 SugaredConverted = TemplateArgument(ParamType,
6655 /*isNullPtr*/ true);
6656 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6657 /*isNullPtr*/ true);
6658 return false;
6659 case NPV_NotNullPointer:
6660 break;
6661 }
6662
6663 if (S.IsQualificationConversion(ResultArg->getType(),
6664 ParamType.getNonReferenceType(), false,
6665 ObjCLifetimeConversion)) {
6666 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6667 ResultArg->getValueKind())
6668 .get();
6669 } else if (!S.Context.hasSameUnqualifiedType(
6670 ResultArg->getType(), ParamType.getNonReferenceType())) {
6671 // We can't perform this conversion.
6672 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6673 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6675 return true;
6676 }
6677
6678 if (!DRE)
6679 return S.Diag(Arg->getBeginLoc(),
6680 diag::err_template_arg_not_pointer_to_member_form)
6681 << Arg->getSourceRange();
6682
6683 if (isa<FieldDecl>(DRE->getDecl()) ||
6684 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6685 isa<CXXMethodDecl>(DRE->getDecl())) {
6686 assert((isa<FieldDecl>(DRE->getDecl()) ||
6687 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6688 cast<CXXMethodDecl>(DRE->getDecl())
6689 ->isImplicitObjectMemberFunction()) &&
6690 "Only non-static member pointers can make it here");
6691
6692 // Okay: this is the address of a non-static member, and therefore
6693 // a member pointer constant.
6694 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6695 SugaredConverted = TemplateArgument(Arg);
6696 CanonicalConverted =
6697 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6698 } else {
6699 ValueDecl *D = DRE->getDecl();
6700 SugaredConverted = TemplateArgument(D, ParamType);
6701 CanonicalConverted =
6702 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6703 S.Context.getCanonicalType(ParamType));
6704 }
6705 return Invalid;
6706 }
6707
6708 // We found something else, but we don't know specifically what it is.
6709 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6710 << Arg->getSourceRange();
6711 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6712 return true;
6713}
6714
6716 QualType ParamType, Expr *Arg,
6717 TemplateArgument &SugaredConverted,
6718 TemplateArgument &CanonicalConverted,
6720 SourceLocation StartLoc = Arg->getBeginLoc();
6721
6722 // If the parameter type somehow involves auto, deduce the type now.
6723 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6724 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6725 // During template argument deduction, we allow 'decltype(auto)' to
6726 // match an arbitrary dependent argument.
6727 // FIXME: The language rules don't say what happens in this case.
6728 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6729 // expression is merely instantiation-dependent; is this enough?
6730 if (Arg->isTypeDependent()) {
6731 auto *AT = dyn_cast<AutoType>(DeducedT);
6732 if (AT && AT->isDecltypeAuto()) {
6733 SugaredConverted = TemplateArgument(Arg);
6734 CanonicalConverted = TemplateArgument(
6735 Context.getCanonicalTemplateArgument(SugaredConverted));
6736 return Arg;
6737 }
6738 }
6739
6740 // When checking a deduced template argument, deduce from its type even if
6741 // the type is dependent, in order to check the types of non-type template
6742 // arguments line up properly in partial ordering.
6743 Expr *DeductionArg = Arg;
6744 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6745 DeductionArg = PE->getPattern();
6746 TypeSourceInfo *TSI =
6747 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6748 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6749 InitializedEntity Entity =
6752 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6753 Expr *Inits[1] = {DeductionArg};
6754 ParamType =
6755 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6756 if (ParamType.isNull())
6757 return ExprError();
6758 } else {
6759 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6760 Param->getDepth() + 1);
6761 ParamType = QualType();
6763 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6764 /*DependentDeduction=*/true,
6765 // We do not check constraints right now because the
6766 // immediately-declared constraint of the auto type is
6767 // also an associated constraint, and will be checked
6768 // along with the other associated constraints after
6769 // checking the template argument list.
6770 /*IgnoreConstraints=*/true);
6772 if (ParamType.isNull())
6773 return ExprError();
6775 Diag(Arg->getExprLoc(),
6776 diag::err_non_type_template_parm_type_deduction_failure)
6777 << Param->getDeclName() << Param->getType() << Arg->getType()
6778 << Arg->getSourceRange();
6780 return ExprError();
6781 }
6782 }
6783 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6784 // an error. The error message normally references the parameter
6785 // declaration, but here we'll pass the argument location because that's
6786 // where the parameter type is deduced.
6787 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6788 if (ParamType.isNull()) {
6790 return ExprError();
6791 }
6792 }
6793
6794 // We should have already dropped all cv-qualifiers by now.
6795 assert(!ParamType.hasQualifiers() &&
6796 "non-type template parameter type cannot be qualified");
6797
6798 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6799 if (CTAK == CTAK_Deduced &&
6800 (ParamType->isReferenceType()
6802 Arg->getType())
6803 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6804 // FIXME: If either type is dependent, we skip the check. This isn't
6805 // correct, since during deduction we're supposed to have replaced each
6806 // template parameter with some unique (non-dependent) placeholder.
6807 // FIXME: If the argument type contains 'auto', we carry on and fail the
6808 // type check in order to force specific types to be more specialized than
6809 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6810 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6811 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6812 !Arg->getType()->getContainedDeducedType()) {
6813 SugaredConverted = TemplateArgument(Arg);
6814 CanonicalConverted = TemplateArgument(
6815 Context.getCanonicalTemplateArgument(SugaredConverted));
6816 return Arg;
6817 }
6818 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6819 // we should actually be checking the type of the template argument in P,
6820 // not the type of the template argument deduced from A, against the
6821 // template parameter type.
6822 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6823 << Arg->getType()
6824 << ParamType.getUnqualifiedType();
6826 return ExprError();
6827 }
6828
6829 // If either the parameter has a dependent type or the argument is
6830 // type-dependent, there's nothing we can check now.
6831 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6832 // Force the argument to the type of the parameter to maintain invariants.
6833 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6834 if (PE)
6835 Arg = PE->getPattern();
6837 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6838 ParamType->isLValueReferenceType() ? VK_LValue
6839 : ParamType->isRValueReferenceType() ? VK_XValue
6840 : VK_PRValue);
6841 if (E.isInvalid())
6842 return ExprError();
6843 if (PE) {
6844 // Recreate a pack expansion if we unwrapped one.
6845 E = new (Context)
6846 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6847 PE->getNumExpansions());
6848 }
6849 SugaredConverted = TemplateArgument(E.get());
6850 CanonicalConverted = TemplateArgument(
6851 Context.getCanonicalTemplateArgument(SugaredConverted));
6852 return E;
6853 }
6854
6855 QualType CanonParamType = Context.getCanonicalType(ParamType);
6856 // Avoid making a copy when initializing a template parameter of class type
6857 // from a template parameter object of the same type. This is going beyond
6858 // the standard, but is required for soundness: in
6859 // template<A a> struct X { X *p; X<a> *q; };
6860 // ... we need p and q to have the same type.
6861 //
6862 // Similarly, don't inject a call to a copy constructor when initializing
6863 // from a template parameter of the same type.
6864 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6865 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6866 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6867 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6868 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6869
6870 SugaredConverted = TemplateArgument(TPO, ParamType);
6871 CanonicalConverted =
6872 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6873 return Arg;
6874 }
6875 if (isa<NonTypeTemplateParmDecl>(ND)) {
6876 SugaredConverted = TemplateArgument(Arg);
6877 CanonicalConverted =
6878 Context.getCanonicalTemplateArgument(SugaredConverted);
6879 return Arg;
6880 }
6881 }
6882
6883 // The initialization of the parameter from the argument is
6884 // a constant-evaluated context.
6887
6888 bool IsConvertedConstantExpression = true;
6889 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6891 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6892 Expr *Inits[1] = {Arg};
6893 InitializedEntity Entity =
6895 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6896 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6897 if (Result.isInvalid() || !Result.get())
6898 return ExprError();
6900 if (Result.isInvalid() || !Result.get())
6901 return ExprError();
6902 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6903 /*DiscardedValue=*/false,
6904 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6905 .get();
6906 IsConvertedConstantExpression = false;
6907 }
6908
6909 if (getLangOpts().CPlusPlus17) {
6910 // C++17 [temp.arg.nontype]p1:
6911 // A template-argument for a non-type template parameter shall be
6912 // a converted constant expression of the type of the template-parameter.
6913 APValue Value;
6914 ExprResult ArgResult;
6915 if (IsConvertedConstantExpression) {
6916 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6917 CCEK_TemplateArg, Param);
6918 if (ArgResult.isInvalid())
6919 return ExprError();
6920 } else {
6921 ArgResult = Arg;
6922 }
6923
6924 // For a value-dependent argument, CheckConvertedConstantExpression is
6925 // permitted (and expected) to be unable to determine a value.
6926 if (ArgResult.get()->isValueDependent()) {
6927 SugaredConverted = TemplateArgument(ArgResult.get());
6928 CanonicalConverted =
6929 Context.getCanonicalTemplateArgument(SugaredConverted);
6930 return ArgResult;
6931 }
6932
6933 APValue PreNarrowingValue;
6935 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6936 false, PreNarrowingValue);
6937 if (ArgResult.isInvalid())
6938 return ExprError();
6939
6940 if (Value.isLValue()) {
6941 APValue::LValueBase Base = Value.getLValueBase();
6942 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6943 // For a non-type template-parameter of pointer or reference type,
6944 // the value of the constant expression shall not refer to
6945 assert(ParamType->isPointerOrReferenceType() ||
6946 ParamType->isNullPtrType());
6947 // -- a temporary object
6948 // -- a string literal
6949 // -- the result of a typeid expression, or
6950 // -- a predefined __func__ variable
6951 if (Base &&
6952 (!VD ||
6953 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6954 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6955 << Arg->getSourceRange();
6956 return ExprError();
6957 }
6958
6959 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6960 VD->getType()->isArrayType() &&
6961 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6962 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6963 SugaredConverted = TemplateArgument(VD, ParamType);
6964 CanonicalConverted = TemplateArgument(
6965 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6966 return ArgResult.get();
6967 }
6968
6969 // -- a subobject [until C++20]
6970 if (!getLangOpts().CPlusPlus20) {
6971 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6972 Value.isLValueOnePastTheEnd()) {
6973 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6974 << Value.getAsString(Context, ParamType);
6975 return ExprError();
6976 }
6977 assert((VD || !ParamType->isReferenceType()) &&
6978 "null reference should not be a constant expression");
6979 assert((!VD || !ParamType->isNullPtrType()) &&
6980 "non-null value of type nullptr_t?");
6981 }
6982 }
6983
6984 if (Value.isAddrLabelDiff())
6985 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6986
6987 SugaredConverted = TemplateArgument(Context, ParamType, Value);
6988 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6989 return ArgResult.get();
6990 }
6991
6992 // C++ [temp.arg.nontype]p5:
6993 // The following conversions are performed on each expression used
6994 // as a non-type template-argument. If a non-type
6995 // template-argument cannot be converted to the type of the
6996 // corresponding template-parameter then the program is
6997 // ill-formed.
6998 if (ParamType->isIntegralOrEnumerationType()) {
6999 // C++11:
7000 // -- for a non-type template-parameter of integral or
7001 // enumeration type, conversions permitted in a converted
7002 // constant expression are applied.
7003 //
7004 // C++98:
7005 // -- for a non-type template-parameter of integral or
7006 // enumeration type, integral promotions (4.5) and integral
7007 // conversions (4.7) are applied.
7008
7009 if (getLangOpts().CPlusPlus11) {
7010 // C++ [temp.arg.nontype]p1:
7011 // A template-argument for a non-type, non-template template-parameter
7012 // shall be one of:
7013 //
7014 // -- for a non-type template-parameter of integral or enumeration
7015 // type, a converted constant expression of the type of the
7016 // template-parameter; or
7017 llvm::APSInt Value;
7018 ExprResult ArgResult =
7021 if (ArgResult.isInvalid())
7022 return ExprError();
7023
7024 // We can't check arbitrary value-dependent arguments.
7025 if (ArgResult.get()->isValueDependent()) {
7026 SugaredConverted = TemplateArgument(ArgResult.get());
7027 CanonicalConverted =
7028 Context.getCanonicalTemplateArgument(SugaredConverted);
7029 return ArgResult;
7030 }
7031
7032 // Widen the argument value to sizeof(parameter type). This is almost
7033 // always a no-op, except when the parameter type is bool. In
7034 // that case, this may extend the argument from 1 bit to 8 bits.
7035 QualType IntegerType = ParamType;
7036 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7037 IntegerType = Enum->getDecl()->getIntegerType();
7038 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7039 ? Context.getIntWidth(IntegerType)
7040 : Context.getTypeSize(IntegerType));
7041
7042 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7043 CanonicalConverted =
7045 return ArgResult;
7046 }
7047
7048 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7049 if (ArgResult.isInvalid())
7050 return ExprError();
7051 Arg = ArgResult.get();
7052
7053 QualType ArgType = Arg->getType();
7054
7055 // C++ [temp.arg.nontype]p1:
7056 // A template-argument for a non-type, non-template
7057 // template-parameter shall be one of:
7058 //
7059 // -- an integral constant-expression of integral or enumeration
7060 // type; or
7061 // -- the name of a non-type template-parameter; or
7062 llvm::APSInt Value;
7063 if (!ArgType->isIntegralOrEnumerationType()) {
7064 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7065 << ArgType << Arg->getSourceRange();
7067 return ExprError();
7068 } else if (!Arg->isValueDependent()) {
7069 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7070 QualType T;
7071
7072 public:
7073 TmplArgICEDiagnoser(QualType T) : T(T) { }
7074
7075 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7076 SourceLocation Loc) override {
7077 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7078 }
7079 } Diagnoser(ArgType);
7080
7081 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7082 if (!Arg)
7083 return ExprError();
7084 }
7085
7086 // From here on out, all we care about is the unqualified form
7087 // of the argument type.
7088 ArgType = ArgType.getUnqualifiedType();
7089
7090 // Try to convert the argument to the parameter's type.
7091 if (Context.hasSameType(ParamType, ArgType)) {
7092 // Okay: no conversion necessary
7093 } else if (ParamType->isBooleanType()) {
7094 // This is an integral-to-boolean conversion.
7095 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7096 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7097 !ParamType->isEnumeralType()) {
7098 // This is an integral promotion or conversion.
7099 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7100 } else {
7101 // We can't perform this conversion.
7102 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7103 << Arg->getType() << ParamType << Arg->getSourceRange();
7105 return ExprError();
7106 }
7107
7108 // Add the value of this argument to the list of converted
7109 // arguments. We use the bitwidth and signedness of the template
7110 // parameter.
7111 if (Arg->isValueDependent()) {
7112 // The argument is value-dependent. Create a new
7113 // TemplateArgument with the converted expression.
7114 SugaredConverted = TemplateArgument(Arg);
7115 CanonicalConverted =
7116 Context.getCanonicalTemplateArgument(SugaredConverted);
7117 return Arg;
7118 }
7119
7120 QualType IntegerType = ParamType;
7121 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7122 IntegerType = Enum->getDecl()->getIntegerType();
7123 }
7124
7125 if (ParamType->isBooleanType()) {
7126 // Value must be zero or one.
7127 Value = Value != 0;
7128 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7129 if (Value.getBitWidth() != AllowedBits)
7130 Value = Value.extOrTrunc(AllowedBits);
7131 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7132 } else {
7133 llvm::APSInt OldValue = Value;
7134
7135 // Coerce the template argument's value to the value it will have
7136 // based on the template parameter's type.
7137 unsigned AllowedBits = IntegerType->isBitIntType()
7138 ? Context.getIntWidth(IntegerType)
7139 : Context.getTypeSize(IntegerType);
7140 if (Value.getBitWidth() != AllowedBits)
7141 Value = Value.extOrTrunc(AllowedBits);
7142 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7143
7144 // Complain if an unsigned parameter received a negative value.
7145 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7146 (OldValue.isSigned() && OldValue.isNegative())) {
7147 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7148 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7149 << Arg->getSourceRange();
7151 }
7152
7153 // Complain if we overflowed the template parameter's type.
7154 unsigned RequiredBits;
7155 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7156 RequiredBits = OldValue.getActiveBits();
7157 else if (OldValue.isUnsigned())
7158 RequiredBits = OldValue.getActiveBits() + 1;
7159 else
7160 RequiredBits = OldValue.getSignificantBits();
7161 if (RequiredBits > AllowedBits) {
7162 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7163 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7164 << Arg->getSourceRange();
7166 }
7167 }
7168
7169 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7170 SugaredConverted = TemplateArgument(Context, Value, T);
7171 CanonicalConverted =
7173 return Arg;
7174 }
7175
7176 QualType ArgType = Arg->getType();
7177 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7178
7179 // Handle pointer-to-function, reference-to-function, and
7180 // pointer-to-member-function all in (roughly) the same way.
7181 if (// -- For a non-type template-parameter of type pointer to
7182 // function, only the function-to-pointer conversion (4.3) is
7183 // applied. If the template-argument represents a set of
7184 // overloaded functions (or a pointer to such), the matching
7185 // function is selected from the set (13.4).
7186 (ParamType->isPointerType() &&
7187 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7188 // -- For a non-type template-parameter of type reference to
7189 // function, no conversions apply. If the template-argument
7190 // represents a set of overloaded functions, the matching
7191 // function is selected from the set (13.4).
7192 (ParamType->isReferenceType() &&
7193 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7194 // -- For a non-type template-parameter of type pointer to
7195 // member function, no conversions apply. If the
7196 // template-argument represents a set of overloaded member
7197 // functions, the matching member function is selected from
7198 // the set (13.4).
7199 (ParamType->isMemberPointerType() &&
7200 ParamType->castAs<MemberPointerType>()->getPointeeType()
7201 ->isFunctionType())) {
7202
7203 if (Arg->getType() == Context.OverloadTy) {
7204 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7205 true,
7206 FoundResult)) {
7207 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7208 return ExprError();
7209
7210 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7211 if (Res.isInvalid())
7212 return ExprError();
7213 Arg = Res.get();
7214 ArgType = Arg->getType();
7215 } else
7216 return ExprError();
7217 }
7218
7219 if (!ParamType->isMemberPointerType()) {
7221 *this, Param, ParamType, Arg, SugaredConverted,
7222 CanonicalConverted))
7223 return ExprError();
7224 return Arg;
7225 }
7226
7228 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7229 return ExprError();
7230 return Arg;
7231 }
7232
7233 if (ParamType->isPointerType()) {
7234 // -- for a non-type template-parameter of type pointer to
7235 // object, qualification conversions (4.4) and the
7236 // array-to-pointer conversion (4.2) are applied.
7237 // C++0x also allows a value of std::nullptr_t.
7238 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7239 "Only object pointers allowed here");
7240
7242 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7243 return ExprError();
7244 return Arg;
7245 }
7246
7247 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7248 // -- For a non-type template-parameter of type reference to
7249 // object, no conversions apply. The type referred to by the
7250 // reference may be more cv-qualified than the (otherwise
7251 // identical) type of the template-argument. The
7252 // template-parameter is bound directly to the
7253 // template-argument, which must be an lvalue.
7254 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7255 "Only object references allowed here");
7256
7257 if (Arg->getType() == Context.OverloadTy) {
7259 ParamRefType->getPointeeType(),
7260 true,
7261 FoundResult)) {
7262 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7263 return ExprError();
7264 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7265 if (Res.isInvalid())
7266 return ExprError();
7267 Arg = Res.get();
7268 ArgType = Arg->getType();
7269 } else
7270 return ExprError();
7271 }
7272
7274 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7275 return ExprError();
7276 return Arg;
7277 }
7278
7279 // Deal with parameters of type std::nullptr_t.
7280 if (ParamType->isNullPtrType()) {
7281 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7282 SugaredConverted = TemplateArgument(Arg);
7283 CanonicalConverted =
7284 Context.getCanonicalTemplateArgument(SugaredConverted);
7285 return Arg;
7286 }
7287
7288 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7289 case NPV_NotNullPointer:
7290 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7291 << Arg->getType() << ParamType;
7293 return ExprError();
7294
7295 case NPV_Error:
7296 return ExprError();
7297
7298 case NPV_NullPointer:
7299 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7300 SugaredConverted = TemplateArgument(ParamType,
7301 /*isNullPtr=*/true);
7302 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7303 /*isNullPtr=*/true);
7304 return Arg;
7305 }
7306 }
7307
7308 // -- For a non-type template-parameter of type pointer to data
7309 // member, qualification conversions (4.4) are applied.
7310 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7311
7313 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7314 return ExprError();
7315 return Arg;
7316}
7317
7321
7323 TemplateParameterList *Params,
7325 bool IsDeduced) {
7327 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7328 if (!Template) {
7329 // Any dependent template name is fine.
7330 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7331 return false;
7332 }
7333
7334 if (Template->isInvalidDecl())
7335 return true;
7336
7337 // C++0x [temp.arg.template]p1:
7338 // A template-argument for a template template-parameter shall be
7339 // the name of a class template or an alias template, expressed as an
7340 // id-expression. When the template-argument names a class template, only
7341 // primary class templates are considered when matching the
7342 // template template argument with the corresponding parameter;
7343 // partial specializations are not considered even if their
7344 // parameter lists match that of the template template parameter.
7345 //
7346 // Note that we also allow template template parameters here, which
7347 // will happen when we are dealing with, e.g., class template
7348 // partial specializations.
7349 if (!isa<ClassTemplateDecl>(Template) &&
7350 !isa<TemplateTemplateParmDecl>(Template) &&
7351 !isa<TypeAliasTemplateDecl>(Template) &&
7352 !isa<BuiltinTemplateDecl>(Template)) {
7353 assert(isa<FunctionTemplateDecl>(Template) &&
7354 "Only function templates are possible here");
7355 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7356 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7357 << Template;
7358 }
7359
7360 // C++1z [temp.arg.template]p3: (DR 150)
7361 // A template-argument matches a template template-parameter P when P
7362 // is at least as specialized as the template-argument A.
7363 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7364 // Quick check for the common case:
7365 // If P contains a parameter pack, then A [...] matches P if each of A's
7366 // template parameters matches the corresponding template parameter in
7367 // the template-parameter-list of P.
7369 Template->getTemplateParameters(), Params, false,
7371 // If the argument has no associated constraints, then the parameter is
7372 // definitely at least as specialized as the argument.
7373 // Otherwise - we need a more thorough check.
7374 !Template->hasAssociatedConstraints())
7375 return false;
7376
7378 Params, Template, DefaultArgs, Arg.getLocation(), IsDeduced)) {
7379 // P2113
7380 // C++20[temp.func.order]p2
7381 // [...] If both deductions succeed, the partial ordering selects the
7382 // more constrained template (if one exists) as determined below.
7383 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7384 Params->getAssociatedConstraints(ParamsAC);
7385 // C++2a[temp.arg.template]p3
7386 // [...] In this comparison, if P is unconstrained, the constraints on A
7387 // are not considered.
7388 if (ParamsAC.empty())
7389 return false;
7390
7391 Template->getAssociatedConstraints(TemplateAC);
7392
7393 bool IsParamAtLeastAsConstrained;
7394 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7395 IsParamAtLeastAsConstrained))
7396 return true;
7397 if (!IsParamAtLeastAsConstrained) {
7398 Diag(Arg.getLocation(),
7399 diag::err_template_template_parameter_not_at_least_as_constrained)
7400 << Template << Param << Arg.getSourceRange();
7401 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7402 Diag(Template->getLocation(), diag::note_entity_declared_at)
7403 << Template;
7404 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7405 TemplateAC);
7406 return true;
7407 }
7408 return false;
7409 }
7410 // FIXME: Produce better diagnostics for deduction failures.
7411 }
7412
7413 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7414 Params,
7415 true,
7417 Arg.getLocation());
7418}
7419
7421 unsigned HereDiagID,
7422 unsigned ExternalDiagID) {
7423 if (Decl.getLocation().isValid())
7424 return S.Diag(Decl.getLocation(), HereDiagID);
7425
7426 SmallString<128> Str;
7427 llvm::raw_svector_ostream Out(Str);
7429 PP.TerseOutput = 1;
7430 Decl.print(Out, PP);
7431 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7432}
7433
7435 std::optional<SourceRange> ParamRange) {
7437 noteLocation(*this, Decl, diag::note_template_decl_here,
7438 diag::note_template_decl_external);
7439 if (ParamRange && ParamRange->isValid()) {
7440 assert(Decl.getLocation().isValid() &&
7441 "Parameter range has location when Decl does not");
7442 DB << *ParamRange;
7443 }
7444}
7445
7447 noteLocation(*this, Decl, diag::note_template_param_here,
7448 diag::note_template_param_external);
7449}
7450
7452 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7454 // C++ [temp.param]p8:
7455 //
7456 // A non-type template-parameter of type "array of T" or
7457 // "function returning T" is adjusted to be of type "pointer to
7458 // T" or "pointer to function returning T", respectively.
7459 if (ParamType->isArrayType())
7460 ParamType = Context.getArrayDecayedType(ParamType);
7461 else if (ParamType->isFunctionType())
7462 ParamType = Context.getPointerType(ParamType);
7463
7464 // For a NULL non-type template argument, return nullptr casted to the
7465 // parameter's type.
7466 if (Arg.getKind() == TemplateArgument::NullPtr) {
7467 return ImpCastExprToType(
7469 ParamType,
7470 ParamType->getAs<MemberPointerType>()
7471 ? CK_NullToMemberPointer
7472 : CK_NullToPointer);
7473 }
7474 assert(Arg.getKind() == TemplateArgument::Declaration &&
7475 "Only declaration template arguments permitted here");
7476
7477 ValueDecl *VD = Arg.getAsDecl();
7478
7479 CXXScopeSpec SS;
7480 if (ParamType->isMemberPointerType()) {
7481 // If this is a pointer to member, we need to use a qualified name to
7482 // form a suitable pointer-to-member constant.
7483 assert(VD->getDeclContext()->isRecord() &&
7484 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7485 isa<IndirectFieldDecl>(VD)));
7486 QualType ClassType
7487 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7488 NestedNameSpecifier *Qualifier
7489 = NestedNameSpecifier::Create(Context, nullptr, false,
7490 ClassType.getTypePtr());
7491 SS.MakeTrivial(Context, Qualifier, Loc);
7492 }
7493
7495 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7496 if (RefExpr.isInvalid())
7497 return ExprError();
7498
7499 // For a pointer, the argument declaration is the pointee. Take its address.
7500 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7501 if (ParamType->isPointerType() && !ElemT.isNull() &&
7502 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7503 // Decay an array argument if we want a pointer to its first element.
7504 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7505 if (RefExpr.isInvalid())
7506 return ExprError();
7507 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7508 // For any other pointer, take the address (or form a pointer-to-member).
7509 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7510 if (RefExpr.isInvalid())
7511 return ExprError();
7512 } else if (ParamType->isRecordType()) {
7513 assert(isa<TemplateParamObjectDecl>(VD) &&
7514 "arg for class template param not a template parameter object");
7515 // No conversions apply in this case.
7516 return RefExpr;
7517 } else {
7518 assert(ParamType->isReferenceType() &&
7519 "unexpected type for decl template argument");
7520 if (NonTypeTemplateParmDecl *NTTP =
7521 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7522 QualType TemplateParamType = NTTP->getType();
7523 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7524 if (AT && AT->isDecltypeAuto()) {
7526 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7527 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7528 /*PackIndex=*/std::nullopt,
7529 /*RefParam=*/true);
7530 }
7531 }
7532 }
7533
7534 // At this point we should have the right value category.
7535 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7536 "value kind mismatch for non-type template argument");
7537
7538 // The type of the template parameter can differ from the type of the
7539 // argument in various ways; convert it now if necessary.
7540 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7541 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7542 CastKind CK;
7543 QualType Ignored;
7544 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7545 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7546 CK = CK_NoOp;
7547 } else if (ParamType->isVoidPointerType() &&
7548 RefExpr.get()->getType()->isPointerType()) {
7549 CK = CK_BitCast;
7550 } else {
7551 // FIXME: Pointers to members can need conversion derived-to-base or
7552 // base-to-derived conversions. We currently don't retain enough
7553 // information to convert properly (we need to track a cast path or
7554 // subobject number in the template argument).
7555 llvm_unreachable(
7556 "unexpected conversion required for non-type template argument");
7557 }
7558 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7559 RefExpr.get()->getValueKind());
7560 }
7561
7562 return RefExpr;
7563}
7564
7565/// Construct a new expression that refers to the given
7566/// integral template argument with the given source-location
7567/// information.
7568///
7569/// This routine takes care of the mapping from an integral template
7570/// argument (which may have any integral type) to the appropriate
7571/// literal value.
7573 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7574 assert(OrigT->isIntegralOrEnumerationType());
7575
7576 // If this is an enum type that we're instantiating, we need to use an integer
7577 // type the same size as the enumerator. We don't want to build an
7578 // IntegerLiteral with enum type. The integer type of an enum type can be of
7579 // any integral type with C++11 enum classes, make sure we create the right
7580 // type of literal for it.
7581 QualType T = OrigT;
7582 if (const EnumType *ET = OrigT->getAs<EnumType>())
7583 T = ET->getDecl()->getIntegerType();
7584
7585 Expr *E;
7586 if (T->isAnyCharacterType()) {
7588 if (T->isWideCharType())
7590 else if (T->isChar8Type() && S.getLangOpts().Char8)
7592 else if (T->isChar16Type())
7594 else if (T->isChar32Type())
7596 else
7598
7599 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7600 } else if (T->isBooleanType()) {
7601 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7602 } else {
7603 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7604 }
7605
7606 if (OrigT->isEnumeralType()) {
7607 // FIXME: This is a hack. We need a better way to handle substituted
7608 // non-type template parameters.
7609 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7610 nullptr, S.CurFPFeatureOverrides(),
7612 Loc, Loc);
7613 }
7614
7615 return E;
7616}
7617
7619 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7620 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7621 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7622 ILE->setType(T);
7623 return ILE;
7624 };
7625
7626 switch (Val.getKind()) {
7628 // This cannot occur in a template argument at all.
7629 case APValue::Array:
7630 case APValue::Struct:
7631 case APValue::Union:
7632 // These can only occur within a template parameter object, which is
7633 // represented as a TemplateArgument::Declaration.
7634 llvm_unreachable("unexpected template argument value");
7635
7636 case APValue::Int:
7638 Loc);
7639
7640 case APValue::Float:
7641 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7642 T, Loc);
7643
7646 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7647 Val.getFixedPoint().getScale());
7648
7649 case APValue::ComplexInt: {
7650 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7652 S, ElemT, Val.getComplexIntReal(), Loc),
7654 S, ElemT, Val.getComplexIntImag(), Loc)});
7655 }
7656
7657 case APValue::ComplexFloat: {
7658 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7659 return MakeInitList(
7661 ElemT, Loc),
7663 ElemT, Loc)});
7664 }
7665
7666 case APValue::Vector: {
7667 QualType ElemT = T->castAs<VectorType>()->getElementType();
7669 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7671 S, ElemT, Val.getVectorElt(I), Loc));
7672 return MakeInitList(Elts);
7673 }
7674
7675 case APValue::None:
7677 llvm_unreachable("Unexpected APValue kind.");
7678 case APValue::LValue:
7680 // There isn't necessarily a valid equivalent source-level syntax for
7681 // these; in particular, a naive lowering might violate access control.
7682 // So for now we lower to a ConstantExpr holding the value, wrapped around
7683 // an OpaqueValueExpr.
7684 // FIXME: We should have a better representation for this.
7686 if (T->isReferenceType()) {
7687 T = T->getPointeeType();
7688 VK = VK_LValue;
7689 }
7690 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7691 return ConstantExpr::Create(S.Context, OVE, Val);
7692 }
7693 llvm_unreachable("Unhandled APValue::ValueKind enum");
7694}
7695
7699 switch (Arg.getKind()) {
7705 llvm_unreachable("not a non-type template argument");
7706
7708 return Arg.getAsExpr();
7709
7714
7717 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7718
7721 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7722 }
7723 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7724}
7725
7726/// Match two template parameters within template parameter lists.
7728 Sema &S, NamedDecl *New,
7729 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7730 const NamedDecl *OldInstFrom, bool Complain,
7732 // Check the actual kind (type, non-type, template).
7733 if (Old->getKind() != New->getKind()) {
7734 if (Complain) {
7735 unsigned NextDiag = diag::err_template_param_different_kind;
7736 if (TemplateArgLoc.isValid()) {
7737 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7738 NextDiag = diag::note_template_param_different_kind;
7739 }
7740 S.Diag(New->getLocation(), NextDiag)
7741 << (Kind != Sema::TPL_TemplateMatch);
7742 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7743 << (Kind != Sema::TPL_TemplateMatch);
7744 }
7745
7746 return false;
7747 }
7748
7749 // Check that both are parameter packs or neither are parameter packs.
7750 // However, if we are matching a template template argument to a
7751 // template template parameter, the template template parameter can have
7752 // a parameter pack where the template template argument does not.
7753 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7755 Old->isTemplateParameterPack())) {
7756 if (Complain) {
7757 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7758 if (TemplateArgLoc.isValid()) {
7759 S.Diag(TemplateArgLoc,
7760 diag::err_template_arg_template_params_mismatch);
7761 NextDiag = diag::note_template_parameter_pack_non_pack;
7762 }
7763
7764 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7765 : isa<NonTypeTemplateParmDecl>(New)? 1
7766 : 2;
7767 S.Diag(New->getLocation(), NextDiag)
7768 << ParamKind << New->isParameterPack();
7769 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7770 << ParamKind << Old->isParameterPack();
7771 }
7772
7773 return false;
7774 }
7775
7776 // For non-type template parameters, check the type of the parameter.
7777 if (NonTypeTemplateParmDecl *OldNTTP
7778 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7779 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7780
7781 // If we are matching a template template argument to a template
7782 // template parameter and one of the non-type template parameter types
7783 // is dependent, then we must wait until template instantiation time
7784 // to actually compare the arguments.
7786 (!OldNTTP->getType()->isDependentType() &&
7787 !NewNTTP->getType()->isDependentType())) {
7788 // C++20 [temp.over.link]p6:
7789 // Two [non-type] template-parameters are equivalent [if] they have
7790 // equivalent types ignoring the use of type-constraints for
7791 // placeholder types
7792 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7793 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7794 if (!S.Context.hasSameType(OldType, NewType)) {
7795 if (Complain) {
7796 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7797 if (TemplateArgLoc.isValid()) {
7798 S.Diag(TemplateArgLoc,
7799 diag::err_template_arg_template_params_mismatch);
7800 NextDiag = diag::note_template_nontype_parm_different_type;
7801 }
7802 S.Diag(NewNTTP->getLocation(), NextDiag)
7803 << NewNTTP->getType()
7804 << (Kind != Sema::TPL_TemplateMatch);
7805 S.Diag(OldNTTP->getLocation(),
7806 diag::note_template_nontype_parm_prev_declaration)
7807 << OldNTTP->getType();
7808 }
7809
7810 return false;
7811 }
7812 }
7813 }
7814 // For template template parameters, check the template parameter types.
7815 // The template parameter lists of template template
7816 // parameters must agree.
7817 else if (TemplateTemplateParmDecl *OldTTP =
7818 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7819 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7821 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7822 OldTTP->getTemplateParameters(), Complain,
7825 : Kind),
7826 TemplateArgLoc))
7827 return false;
7828 }
7829
7832 !isa<TemplateTemplateParmDecl>(Old)) {
7833 const Expr *NewC = nullptr, *OldC = nullptr;
7834
7835 if (isa<TemplateTypeParmDecl>(New)) {
7836 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7837 NewC = TC->getImmediatelyDeclaredConstraint();
7838 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7839 OldC = TC->getImmediatelyDeclaredConstraint();
7840 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7841 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7842 ->getPlaceholderTypeConstraint())
7843 NewC = E;
7844 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7845 ->getPlaceholderTypeConstraint())
7846 OldC = E;
7847 } else
7848 llvm_unreachable("unexpected template parameter type");
7849
7850 auto Diagnose = [&] {
7851 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7852 diag::err_template_different_type_constraint);
7853 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7854 diag::note_template_prev_declaration) << /*declaration*/0;
7855 };
7856
7857 if (!NewC != !OldC) {
7858 if (Complain)
7859 Diagnose();
7860 return false;
7861 }
7862
7863 if (NewC) {
7864 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7865 NewC)) {
7866 if (Complain)
7867 Diagnose();
7868 return false;
7869 }
7870 }
7871 }
7872
7873 return true;
7874}
7875
7876/// Diagnose a known arity mismatch when comparing template argument
7877/// lists.
7878static
7883 SourceLocation TemplateArgLoc) {
7884 unsigned NextDiag = diag::err_template_param_list_different_arity;
7885 if (TemplateArgLoc.isValid()) {
7886 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7887 NextDiag = diag::note_template_param_list_different_arity;
7888 }
7889 S.Diag(New->getTemplateLoc(), NextDiag)
7890 << (New->size() > Old->size())
7891 << (Kind != Sema::TPL_TemplateMatch)
7892 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7893 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7894 << (Kind != Sema::TPL_TemplateMatch)
7895 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7896}
7897
7899 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7900 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7901 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7902 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7903 if (Complain)
7904 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7905 TemplateArgLoc);
7906
7907 return false;
7908 }
7909
7910 // C++0x [temp.arg.template]p3:
7911 // A template-argument matches a template template-parameter (call it P)
7912 // when each of the template parameters in the template-parameter-list of
7913 // the template-argument's corresponding class template or alias template
7914 // (call it A) matches the corresponding template parameter in the
7915 // template-parameter-list of P. [...]
7916 TemplateParameterList::iterator NewParm = New->begin();
7917 TemplateParameterList::iterator NewParmEnd = New->end();
7918 for (TemplateParameterList::iterator OldParm = Old->begin(),
7919 OldParmEnd = Old->end();
7920 OldParm != OldParmEnd; ++OldParm) {
7922 !(*OldParm)->isTemplateParameterPack()) {
7923 if (NewParm == NewParmEnd) {
7924 if (Complain)
7925 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7926 TemplateArgLoc);
7927
7928 return false;
7929 }
7930
7931 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7932 OldInstFrom, Complain, Kind,
7933 TemplateArgLoc))
7934 return false;
7935
7936 ++NewParm;
7937 continue;
7938 }
7939
7940 // C++0x [temp.arg.template]p3:
7941 // [...] When P's template- parameter-list contains a template parameter
7942 // pack (14.5.3), the template parameter pack will match zero or more
7943 // template parameters or template parameter packs in the
7944 // template-parameter-list of A with the same type and form as the
7945 // template parameter pack in P (ignoring whether those template
7946 // parameters are template parameter packs).
7947 for (; NewParm != NewParmEnd; ++NewParm) {
7948 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7949 OldInstFrom, Complain, Kind,
7950 TemplateArgLoc))
7951 return false;
7952 }
7953 }
7954
7955 // Make sure we exhausted all of the arguments.
7956 if (NewParm != NewParmEnd) {
7957 if (Complain)
7958 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7959 TemplateArgLoc);
7960
7961 return false;
7962 }
7963
7966 const Expr *NewRC = New->getRequiresClause();
7967 const Expr *OldRC = Old->getRequiresClause();
7968
7969 auto Diagnose = [&] {
7970 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7971 diag::err_template_different_requires_clause);
7972 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7973 diag::note_template_prev_declaration) << /*declaration*/0;
7974 };
7975
7976 if (!NewRC != !OldRC) {
7977 if (Complain)
7978 Diagnose();
7979 return false;
7980 }
7981
7982 if (NewRC) {
7983 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7984 NewRC)) {
7985 if (Complain)
7986 Diagnose();
7987 return false;
7988 }
7989 }
7990 }
7991
7992 return true;
7993}
7994
7995bool
7997 if (!S)
7998 return false;
7999
8000 // Find the nearest enclosing declaration scope.
8001 S = S->getDeclParent();
8002
8003 // C++ [temp.pre]p6: [P2096]
8004 // A template, explicit specialization, or partial specialization shall not
8005 // have C linkage.
8006 DeclContext *Ctx = S->getEntity();
8007 if (Ctx && Ctx->isExternCContext()) {
8008 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8009 << TemplateParams->getSourceRange();
8010 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8011 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8012 return true;
8013 }
8014 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8015
8016 // C++ [temp]p2:
8017 // A template-declaration can appear only as a namespace scope or
8018 // class scope declaration.
8019 // C++ [temp.expl.spec]p3:
8020 // An explicit specialization may be declared in any scope in which the
8021 // corresponding primary template may be defined.
8022 // C++ [temp.class.spec]p6: [P2096]
8023 // A partial specialization may be declared in any scope in which the
8024 // corresponding primary template may be defined.
8025 if (Ctx) {
8026 if (Ctx->isFileContext())
8027 return false;
8028 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8029 // C++ [temp.mem]p2:
8030 // A local class shall not have member templates.
8031 if (RD->isLocalClass())
8032 return Diag(TemplateParams->getTemplateLoc(),
8033 diag::err_template_inside_local_class)
8034 << TemplateParams->getSourceRange();
8035 else
8036 return false;
8037 }
8038 }
8039
8040 return Diag(TemplateParams->getTemplateLoc(),
8041 diag::err_template_outside_namespace_or_class_scope)
8042 << TemplateParams->getSourceRange();
8043}
8044
8045/// Determine what kind of template specialization the given declaration
8046/// is.
8048 if (!D)
8049 return TSK_Undeclared;
8050
8051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8052 return Record->getTemplateSpecializationKind();
8053 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8054 return Function->getTemplateSpecializationKind();
8055 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8056 return Var->getTemplateSpecializationKind();
8057
8058 return TSK_Undeclared;
8059}
8060
8061/// Check whether a specialization is well-formed in the current
8062/// context.
8063///
8064/// This routine determines whether a template specialization can be declared
8065/// in the current context (C++ [temp.expl.spec]p2).
8066///
8067/// \param S the semantic analysis object for which this check is being
8068/// performed.
8069///
8070/// \param Specialized the entity being specialized or instantiated, which
8071/// may be a kind of template (class template, function template, etc.) or
8072/// a member of a class template (member function, static data member,
8073/// member class).
8074///
8075/// \param PrevDecl the previous declaration of this entity, if any.
8076///
8077/// \param Loc the location of the explicit specialization or instantiation of
8078/// this entity.
8079///
8080/// \param IsPartialSpecialization whether this is a partial specialization of
8081/// a class template.
8082///
8083/// \returns true if there was an error that we cannot recover from, false
8084/// otherwise.
8086 NamedDecl *Specialized,
8087 NamedDecl *PrevDecl,
8090 // Keep these "kind" numbers in sync with the %select statements in the
8091 // various diagnostics emitted by this routine.
8092 int EntityKind = 0;
8093 if (isa<ClassTemplateDecl>(Specialized))
8094 EntityKind = IsPartialSpecialization? 1 : 0;
8095 else if (isa<VarTemplateDecl>(Specialized))
8096 EntityKind = IsPartialSpecialization ? 3 : 2;
8097 else if (isa<FunctionTemplateDecl>(Specialized))
8098 EntityKind = 4;
8099 else if (isa<CXXMethodDecl>(Specialized))
8100 EntityKind = 5;
8101 else if (isa<VarDecl>(Specialized))
8102 EntityKind = 6;
8103 else if (isa<RecordDecl>(Specialized))
8104 EntityKind = 7;
8105 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8106 EntityKind = 8;
8107 else {
8108 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8109 << S.getLangOpts().CPlusPlus11;
8110 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8111 return true;
8112 }
8113
8114 // C++ [temp.expl.spec]p2:
8115 // An explicit specialization may be declared in any scope in which
8116 // the corresponding primary template may be defined.
8118 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8119 << Specialized;
8120 return true;
8121 }
8122
8123 // C++ [temp.class.spec]p6:
8124 // A class template partial specialization may be declared in any
8125 // scope in which the primary template may be defined.
8126 DeclContext *SpecializedContext =
8127 Specialized->getDeclContext()->getRedeclContext();
8129
8130 // Make sure that this redeclaration (or definition) occurs in the same
8131 // scope or an enclosing namespace.
8132 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8133 : DC->Equals(SpecializedContext))) {
8134 if (isa<TranslationUnitDecl>(SpecializedContext))
8135 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8136 << EntityKind << Specialized;
8137 else {
8138 auto *ND = cast<NamedDecl>(SpecializedContext);
8139 int Diag = diag::err_template_spec_redecl_out_of_scope;
8140 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8141 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8142 S.Diag(Loc, Diag) << EntityKind << Specialized
8143 << ND << isa<CXXRecordDecl>(ND);
8144 }
8145
8146 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8147
8148 // Don't allow specializing in the wrong class during error recovery.
8149 // Otherwise, things can go horribly wrong.
8150 if (DC->isRecord())
8151 return true;
8152 }
8153
8154 return false;
8155}
8156
8158 if (!E->isTypeDependent())
8159 return SourceLocation();
8160 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8161 Checker.TraverseStmt(E);
8162 if (Checker.MatchLoc.isInvalid())
8163 return E->getSourceRange();
8164 return Checker.MatchLoc;
8165}
8166
8167static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8168 if (!TL.getType()->isDependentType())
8169 return SourceLocation();
8170 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8171 Checker.TraverseTypeLoc(TL);
8172 if (Checker.MatchLoc.isInvalid())
8173 return TL.getSourceRange();
8174 return Checker.MatchLoc;
8175}
8176
8177/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8178/// that checks non-type template partial specialization arguments.
8180 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8181 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8182 for (unsigned I = 0; I != NumArgs; ++I) {
8183 if (Args[I].getKind() == TemplateArgument::Pack) {
8185 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8186 Args[I].pack_size(), IsDefaultArgument))
8187 return true;
8188
8189 continue;
8190 }
8191
8192 if (Args[I].getKind() != TemplateArgument::Expression)
8193 continue;
8194
8195 Expr *ArgExpr = Args[I].getAsExpr();
8196
8197 // We can have a pack expansion of any of the bullets below.
8198 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8199 ArgExpr = Expansion->getPattern();
8200
8201 // Strip off any implicit casts we added as part of type checking.
8202 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8203 ArgExpr = ICE->getSubExpr();
8204
8205 // C++ [temp.class.spec]p8:
8206 // A non-type argument is non-specialized if it is the name of a
8207 // non-type parameter. All other non-type arguments are
8208 // specialized.
8209 //
8210 // Below, we check the two conditions that only apply to
8211 // specialized non-type arguments, so skip any non-specialized
8212 // arguments.
8213 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8214 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8215 continue;
8216
8217 // C++ [temp.class.spec]p9:
8218 // Within the argument list of a class template partial
8219 // specialization, the following restrictions apply:
8220 // -- A partially specialized non-type argument expression
8221 // shall not involve a template parameter of the partial
8222 // specialization except when the argument expression is a
8223 // simple identifier.
8224 // -- The type of a template parameter corresponding to a
8225 // specialized non-type argument shall not be dependent on a
8226 // parameter of the specialization.
8227 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8228 // We implement a compromise between the original rules and DR1315:
8229 // -- A specialized non-type template argument shall not be
8230 // type-dependent and the corresponding template parameter
8231 // shall have a non-dependent type.
8232 SourceRange ParamUseRange =
8233 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8234 if (ParamUseRange.isValid()) {
8235 if (IsDefaultArgument) {
8236 S.Diag(TemplateNameLoc,
8237 diag::err_dependent_non_type_arg_in_partial_spec);
8238 S.Diag(ParamUseRange.getBegin(),
8239 diag::note_dependent_non_type_default_arg_in_partial_spec)
8240 << ParamUseRange;
8241 } else {
8242 S.Diag(ParamUseRange.getBegin(),
8243 diag::err_dependent_non_type_arg_in_partial_spec)
8244 << ParamUseRange;
8245 }
8246 return true;
8247 }
8248
8249 ParamUseRange = findTemplateParameter(
8250 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8251 if (ParamUseRange.isValid()) {
8252 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8253 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8254 << Param->getType();
8256 return true;
8257 }
8258 }
8259
8260 return false;
8261}
8262
8264 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8265 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8266 // We have to be conservative when checking a template in a dependent
8267 // context.
8268 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8269 return false;
8270
8271 TemplateParameterList *TemplateParams =
8272 PrimaryTemplate->getTemplateParameters();
8273 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8275 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8276 if (!Param)
8277 continue;
8278
8279 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8280 Param, &TemplateArgs[I],
8281 1, I >= NumExplicit))
8282 return true;
8283 }
8284
8285 return false;
8286}
8287
8289 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8290 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8292 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8293 assert(TUK != TagUseKind::Reference && "References are not specializations");
8294
8295 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8296 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8297 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8298
8299 // Find the class template we're specializing
8300 TemplateName Name = TemplateId.Template.get();
8302 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8303
8304 if (!ClassTemplate) {
8305 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8306 << (Name.getAsTemplateDecl() &&
8307 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8308 return true;
8309 }
8310
8311 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8312 auto Message = DSA->getMessage();
8313 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8314 << ClassTemplate << !Message.empty() << Message;
8315 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8316 }
8317
8318 if (S->isTemplateParamScope())
8319 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8320
8321 DeclContext *DC = ClassTemplate->getDeclContext();
8322
8323 bool isMemberSpecialization = false;
8324 bool isPartialSpecialization = false;
8325
8326 if (SS.isSet()) {
8327 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8328 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8329 TemplateNameLoc, &TemplateId,
8330 /*IsMemberSpecialization=*/false))
8331 return true;
8332 }
8333
8334 // Check the validity of the template headers that introduce this
8335 // template.
8336 // FIXME: We probably shouldn't complain about these headers for
8337 // friend declarations.
8338 bool Invalid = false;
8339 TemplateParameterList *TemplateParams =
8341 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8342 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8343 if (Invalid)
8344 return true;
8345
8346 // Check that we can declare a template specialization here.
8347 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8348 return true;
8349
8350 if (TemplateParams && DC->isDependentContext()) {
8351 ContextRAII SavedContext(*this, DC);
8353 return true;
8354 }
8355
8356 if (TemplateParams && TemplateParams->size() > 0) {
8357 isPartialSpecialization = true;
8358
8359 if (TUK == TagUseKind::Friend) {
8360 Diag(KWLoc, diag::err_partial_specialization_friend)
8361 << SourceRange(LAngleLoc, RAngleLoc);
8362 return true;
8363 }
8364
8365 // C++ [temp.class.spec]p10:
8366 // The template parameter list of a specialization shall not
8367 // contain default template argument values.
8368 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8369 Decl *Param = TemplateParams->getParam(I);
8370 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8371 if (TTP->hasDefaultArgument()) {
8372 Diag(TTP->getDefaultArgumentLoc(),
8373 diag::err_default_arg_in_partial_spec);
8374 TTP->removeDefaultArgument();
8375 }
8376 } else if (NonTypeTemplateParmDecl *NTTP
8377 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8378 if (NTTP->hasDefaultArgument()) {
8379 Diag(NTTP->getDefaultArgumentLoc(),
8380 diag::err_default_arg_in_partial_spec)
8381 << NTTP->getDefaultArgument().getSourceRange();
8382 NTTP->removeDefaultArgument();
8383 }
8384 } else {
8385 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8386 if (TTP->hasDefaultArgument()) {
8388 diag::err_default_arg_in_partial_spec)
8390 TTP->removeDefaultArgument();
8391 }
8392 }
8393 }
8394 } else if (TemplateParams) {
8395 if (TUK == TagUseKind::Friend)
8396 Diag(KWLoc, diag::err_template_spec_friend)
8398 SourceRange(TemplateParams->getTemplateLoc(),
8399 TemplateParams->getRAngleLoc()))
8400 << SourceRange(LAngleLoc, RAngleLoc);
8401 } else {
8402 assert(TUK == TagUseKind::Friend &&
8403 "should have a 'template<>' for this decl");
8404 }
8405
8406 // Check that the specialization uses the same tag kind as the
8407 // original template.
8409 assert(Kind != TagTypeKind::Enum &&
8410 "Invalid enum tag in class template spec!");
8411 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8412 TUK == TagUseKind::Definition, KWLoc,
8413 ClassTemplate->getIdentifier())) {
8414 Diag(KWLoc, diag::err_use_with_wrong_tag)
8415 << ClassTemplate
8417 ClassTemplate->getTemplatedDecl()->getKindName());
8418 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8419 diag::note_previous_use);
8420 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8421 }
8422
8423 // Translate the parser's template argument list in our AST format.
8424 TemplateArgumentListInfo TemplateArgs =
8425 makeTemplateArgumentListInfo(*this, TemplateId);
8426
8427 // Check for unexpanded parameter packs in any of the template arguments.
8428 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8429 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8430 isPartialSpecialization
8433 return true;
8434
8435 // Check that the template argument list is well-formed for this
8436 // template.
8437 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8438 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8439 /*DefaultArgs=*/{},
8440 /*PartialTemplateArgs=*/false, SugaredConverted,
8441 CanonicalConverted,
8442 /*UpdateArgsWithConversions=*/true))
8443 return true;
8444
8445 // Find the class template (partial) specialization declaration that
8446 // corresponds to these arguments.
8447 if (isPartialSpecialization) {
8449 TemplateArgs.size(),
8450 CanonicalConverted))
8451 return true;
8452
8453 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8454 // also do it during instantiation.
8455 if (!Name.isDependent() &&
8457 TemplateArgs, CanonicalConverted)) {
8458 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8459 << ClassTemplate->getDeclName();
8460 isPartialSpecialization = false;
8461 Invalid = true;
8462 }
8463 }
8464
8465 void *InsertPos = nullptr;
8466 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8467
8468 if (isPartialSpecialization)
8469 PrevDecl = ClassTemplate->findPartialSpecialization(
8470 CanonicalConverted, TemplateParams, InsertPos);
8471 else
8472 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8473
8475
8476 // Check whether we can declare a class template specialization in
8477 // the current scope.
8478 if (TUK != TagUseKind::Friend &&
8480 TemplateNameLoc,
8481 isPartialSpecialization))
8482 return true;
8483
8484 // The canonical type
8485 QualType CanonType;
8486 if (isPartialSpecialization) {
8487 // Build the canonical type that describes the converted template
8488 // arguments of the class template partial specialization.
8489 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8490 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8491 CanonicalConverted);
8492
8493 if (Context.hasSameType(CanonType,
8494 ClassTemplate->getInjectedClassNameSpecialization()) &&
8495 (!Context.getLangOpts().CPlusPlus20 ||
8496 !TemplateParams->hasAssociatedConstraints())) {
8497 // C++ [temp.class.spec]p9b3:
8498 //
8499 // -- The argument list of the specialization shall not be identical
8500 // to the implicit argument list of the primary template.
8501 //
8502 // This rule has since been removed, because it's redundant given DR1495,
8503 // but we keep it because it produces better diagnostics and recovery.
8504 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8505 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8506 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8507 return CheckClassTemplate(
8508 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8509 TemplateNameLoc, Attr, TemplateParams, AS_none,
8510 /*ModulePrivateLoc=*/SourceLocation(),
8511 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8512 TemplateParameterLists.data());
8513 }
8514
8515 // Create a new class template partial specialization declaration node.
8517 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8520 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8521 ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8522 Partial->setTemplateArgsAsWritten(TemplateArgs);
8523 SetNestedNameSpecifier(*this, Partial, SS);
8524 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8526 Context, TemplateParameterLists.drop_back(1));
8527 }
8528
8529 if (!PrevPartial)
8530 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8531 Specialization = Partial;
8532
8533 // If we are providing an explicit specialization of a member class
8534 // template specialization, make a note of that.
8535 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8536 PrevPartial->setMemberSpecialization();
8537
8539 } else {
8540 // Create a new class template specialization declaration node for
8541 // this explicit specialization or friend declaration.
8543 Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8544 CanonicalConverted, PrevDecl);
8545 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8547 if (TemplateParameterLists.size() > 0) {
8548 Specialization->setTemplateParameterListsInfo(Context,
8549 TemplateParameterLists);
8550 }
8551
8552 if (!PrevDecl)
8553 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8554
8556 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8557 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8558 CanonicalConverted);
8559 } else {
8561 }
8562 }
8563
8564 // C++ [temp.expl.spec]p6:
8565 // If a template, a member template or the member of a class template is
8566 // explicitly specialized then that specialization shall be declared
8567 // before the first use of that specialization that would cause an implicit
8568 // instantiation to take place, in every translation unit in which such a
8569 // use occurs; no diagnostic is required.
8570 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8571 bool Okay = false;
8572 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8573 // Is there any previous explicit specialization declaration?
8575 Okay = true;
8576 break;
8577 }
8578 }
8579
8580 if (!Okay) {
8581 SourceRange Range(TemplateNameLoc, RAngleLoc);
8582 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8584
8585 Diag(PrevDecl->getPointOfInstantiation(),
8586 diag::note_instantiation_required_here)
8587 << (PrevDecl->getTemplateSpecializationKind()
8589 return true;
8590 }
8591 }
8592
8593 // If this is not a friend, note that this is an explicit specialization.
8594 if (TUK != TagUseKind::Friend)
8595 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8596
8597 // Check that this isn't a redefinition of this specialization.
8598 if (TUK == TagUseKind::Definition) {
8599 RecordDecl *Def = Specialization->getDefinition();
8600 NamedDecl *Hidden = nullptr;
8601 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8602 SkipBody->ShouldSkip = true;
8603 SkipBody->Previous = Def;
8605 } else if (Def) {
8606 SourceRange Range(TemplateNameLoc, RAngleLoc);
8607 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8608 Diag(Def->getLocation(), diag::note_previous_definition);
8609 Specialization->setInvalidDecl();
8610 return true;
8611 }
8612 }
8613
8616
8617 // Add alignment attributes if necessary; these attributes are checked when
8618 // the ASTContext lays out the structure.
8619 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8622 }
8623
8624 if (ModulePrivateLoc.isValid())
8625 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8626 << (isPartialSpecialization? 1 : 0)
8627 << FixItHint::CreateRemoval(ModulePrivateLoc);
8628
8629 // C++ [temp.expl.spec]p9:
8630 // A template explicit specialization is in the scope of the
8631 // namespace in which the template was defined.
8632 //
8633 // We actually implement this paragraph where we set the semantic
8634 // context (in the creation of the ClassTemplateSpecializationDecl),
8635 // but we also maintain the lexical context where the actual
8636 // definition occurs.
8637 Specialization->setLexicalDeclContext(CurContext);
8638
8639 // We may be starting the definition of this specialization.
8640 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8641 Specialization->startDefinition();
8642
8643 if (TUK == TagUseKind::Friend) {
8644 // Build the fully-sugared type for this class template
8645 // specialization as the user wrote in the specialization
8646 // itself. This means that we'll pretty-print the type retrieved
8647 // from the specialization's declaration the way that the user
8648 // actually wrote the specialization, rather than formatting the
8649 // name based on the "canonical" representation used to store the
8650 // template arguments in the specialization.
8652 Name, TemplateNameLoc, TemplateArgs, CanonType);
8654 TemplateNameLoc,
8655 WrittenTy,
8656 /*FIXME:*/KWLoc);
8657 Friend->setAccess(AS_public);
8659 } else {
8660 // Add the specialization into its lexical context, so that it can
8661 // be seen when iterating through the list of declarations in that
8662 // context. However, specializations are not found by name lookup.
8664 }
8665
8666 if (SkipBody && SkipBody->ShouldSkip)
8667 return SkipBody->Previous;
8668
8669 Specialization->setInvalidDecl(Invalid);
8671 return Specialization;
8672}
8673
8675 MultiTemplateParamsArg TemplateParameterLists,
8676 Declarator &D) {
8677 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8678 ActOnDocumentableDecl(NewDecl);
8679 return NewDecl;
8680}
8681
8683 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8684 const IdentifierInfo *Name, SourceLocation NameLoc) {
8685 DeclContext *DC = CurContext;
8686
8687 if (!DC->getRedeclContext()->isFileContext()) {
8688 Diag(NameLoc,
8689 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8690 return nullptr;
8691 }
8692
8693 if (TemplateParameterLists.size() > 1) {
8694 Diag(NameLoc, diag::err_concept_extra_headers);
8695 return nullptr;
8696 }
8697
8698 TemplateParameterList *Params = TemplateParameterLists.front();
8699
8700 if (Params->size() == 0) {
8701 Diag(NameLoc, diag::err_concept_no_parameters);
8702 return nullptr;
8703 }
8704
8705 // Ensure that the parameter pack, if present, is the last parameter in the
8706 // template.
8707 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8708 ParamEnd = Params->end();
8709 ParamIt != ParamEnd; ++ParamIt) {
8710 Decl const *Param = *ParamIt;
8711 if (Param->isParameterPack()) {
8712 if (++ParamIt == ParamEnd)
8713 break;
8714 Diag(Param->getLocation(),
8715 diag::err_template_param_pack_must_be_last_template_parameter);
8716 return nullptr;
8717 }
8718 }
8719
8720 ConceptDecl *NewDecl =
8721 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8722
8723 if (NewDecl->hasAssociatedConstraints()) {
8724 // C++2a [temp.concept]p4:
8725 // A concept shall not have associated constraints.
8726 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8727 NewDecl->setInvalidDecl();
8728 }
8729
8730 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8731 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8733 LookupName(Previous, S);
8734 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8735 /*AllowInlineNamespace*/ false);
8736
8737 // We cannot properly handle redeclarations until we parse the constraint
8738 // expression, so only inject the name if we are sure we are not redeclaring a
8739 // symbol
8740 if (Previous.empty())
8741 PushOnScopeChains(NewDecl, S, true);
8742
8743 return NewDecl;
8744}
8745
8747 bool Found = false;
8749 while (F.hasNext()) {
8750 NamedDecl *D = F.next();
8751 if (D == C) {
8752 F.erase();
8753 Found = true;
8754 break;
8755 }
8756 }
8757 F.done();
8758 return Found;
8759}
8760
8763 Expr *ConstraintExpr,
8764 const ParsedAttributesView &Attrs) {
8765 assert(!C->hasDefinition() && "Concept already defined");
8766 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8767 return nullptr;
8768 C->setDefinition(ConstraintExpr);
8769 ProcessDeclAttributeList(S, C, Attrs);
8770
8771 // Check for conflicting previous declaration.
8772 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8773 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8775 LookupName(Previous, S);
8776 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8777 /*AllowInlineNamespace*/ false);
8778 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8779 bool AddToScope = true;
8780 CheckConceptRedefinition(C, Previous, AddToScope);
8781
8783 if (!WasAlreadyAdded && AddToScope)
8784 PushOnScopeChains(C, S);
8785
8786 return C;
8787}
8788
8790 LookupResult &Previous, bool &AddToScope) {
8791 AddToScope = true;
8792
8793 if (Previous.empty())
8794 return;
8795
8796 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8797 if (!OldConcept) {
8798 auto *Old = Previous.getRepresentativeDecl();
8799 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8800 << NewDecl->getDeclName();
8801 notePreviousDefinition(Old, NewDecl->getLocation());
8802 AddToScope = false;
8803 return;
8804 }
8805 // Check if we can merge with a concept declaration.
8806 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8807 if (!IsSame) {
8808 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8809 << NewDecl->getDeclName();
8810 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8811 AddToScope = false;
8812 return;
8813 }
8814 if (hasReachableDefinition(OldConcept) &&
8815 IsRedefinitionInModule(NewDecl, OldConcept)) {
8816 Diag(NewDecl->getLocation(), diag::err_redefinition)
8817 << NewDecl->getDeclName();
8818 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8819 AddToScope = false;
8820 return;
8821 }
8822 if (!Previous.isSingleResult()) {
8823 // FIXME: we should produce an error in case of ambig and failed lookups.
8824 // Other decls (e.g. namespaces) also have this shortcoming.
8825 return;
8826 }
8827 // We unwrap canonical decl late to check for module visibility.
8828 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8829}
8830
8833 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8834 Diag(Loc, diag::err_recursive_concept) << Concept;
8835 Diag(Concept->getLocation(), diag::note_declared_at);
8836 return true;
8837 }
8838 return false;
8839}
8840
8841/// \brief Strips various properties off an implicit instantiation
8842/// that has just been explicitly specialized.
8843static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8844 if (MinGW || (isa<FunctionDecl>(D) &&
8845 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8846 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8847
8848 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8849 FD->setInlineSpecified(false);
8850}
8851
8852/// Compute the diagnostic location for an explicit instantiation
8853// declaration or definition.
8855 NamedDecl* D, SourceLocation PointOfInstantiation) {
8856 // Explicit instantiations following a specialization have no effect and
8857 // hence no PointOfInstantiation. In that case, walk decl backwards
8858 // until a valid name loc is found.
8859 SourceLocation PrevDiagLoc = PointOfInstantiation;
8860 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8861 Prev = Prev->getPreviousDecl()) {
8862 PrevDiagLoc = Prev->getLocation();
8863 }
8864 assert(PrevDiagLoc.isValid() &&
8865 "Explicit instantiation without point of instantiation?");
8866 return PrevDiagLoc;
8867}
8868
8869bool
8872 NamedDecl *PrevDecl,
8874 SourceLocation PrevPointOfInstantiation,
8875 bool &HasNoEffect) {
8876 HasNoEffect = false;
8877
8878 switch (NewTSK) {
8879 case TSK_Undeclared:
8881 assert(
8882 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8883 "previous declaration must be implicit!");
8884 return false;
8885
8887 switch (PrevTSK) {
8888 case TSK_Undeclared:
8890 // Okay, we're just specializing something that is either already
8891 // explicitly specialized or has merely been mentioned without any
8892 // instantiation.
8893 return false;
8894
8896 if (PrevPointOfInstantiation.isInvalid()) {
8897 // The declaration itself has not actually been instantiated, so it is
8898 // still okay to specialize it.
8900 PrevDecl,
8901 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8902 return false;
8903 }
8904 // Fall through
8905 [[fallthrough]];
8906
8909 assert((PrevTSK == TSK_ImplicitInstantiation ||
8910 PrevPointOfInstantiation.isValid()) &&
8911 "Explicit instantiation without point of instantiation?");
8912
8913 // C++ [temp.expl.spec]p6:
8914 // If a template, a member template or the member of a class template
8915 // is explicitly specialized then that specialization shall be declared
8916 // before the first use of that specialization that would cause an
8917 // implicit instantiation to take place, in every translation unit in
8918 // which such a use occurs; no diagnostic is required.
8919 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8920 // Is there any previous explicit specialization declaration?
8922 return false;
8923 }
8924
8925 Diag(NewLoc, diag::err_specialization_after_instantiation)
8926 << PrevDecl;
8927 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8928 << (PrevTSK != TSK_ImplicitInstantiation);
8929
8930 return true;
8931 }
8932 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8933
8935 switch (PrevTSK) {
8937 // This explicit instantiation declaration is redundant (that's okay).
8938 HasNoEffect = true;
8939 return false;
8940
8941 case TSK_Undeclared:
8943 // We're explicitly instantiating something that may have already been
8944 // implicitly instantiated; that's fine.
8945 return false;
8946
8948 // C++0x [temp.explicit]p4:
8949 // For a given set of template parameters, if an explicit instantiation
8950 // of a template appears after a declaration of an explicit
8951 // specialization for that template, the explicit instantiation has no
8952 // effect.
8953 HasNoEffect = true;
8954 return false;
8955
8957 // C++0x [temp.explicit]p10:
8958 // If an entity is the subject of both an explicit instantiation
8959 // declaration and an explicit instantiation definition in the same
8960 // translation unit, the definition shall follow the declaration.
8961 Diag(NewLoc,
8962 diag::err_explicit_instantiation_declaration_after_definition);
8963
8964 // Explicit instantiations following a specialization have no effect and
8965 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8966 // until a valid name loc is found.
8967 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8968 diag::note_explicit_instantiation_definition_here);
8969 HasNoEffect = true;
8970 return false;
8971 }
8972 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8973
8975 switch (PrevTSK) {
8976 case TSK_Undeclared:
8978 // We're explicitly instantiating something that may have already been
8979 // implicitly instantiated; that's fine.
8980 return false;
8981
8983 // C++ DR 259, C++0x [temp.explicit]p4:
8984 // For a given set of template parameters, if an explicit
8985 // instantiation of a template appears after a declaration of
8986 // an explicit specialization for that template, the explicit
8987 // instantiation has no effect.
8988 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8989 << PrevDecl;
8990 Diag(PrevDecl->getLocation(),
8991 diag::note_previous_template_specialization);
8992 HasNoEffect = true;
8993 return false;
8994
8996 // We're explicitly instantiating a definition for something for which we
8997 // were previously asked to suppress instantiations. That's fine.
8998
8999 // C++0x [temp.explicit]p4:
9000 // For a given set of template parameters, if an explicit instantiation
9001 // of a template appears after a declaration of an explicit
9002 // specialization for that template, the explicit instantiation has no
9003 // effect.
9004 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9005 // Is there any previous explicit specialization declaration?
9007 HasNoEffect = true;
9008 break;
9009 }
9010 }
9011
9012 return false;
9013
9015 // C++0x [temp.spec]p5:
9016 // For a given template and a given set of template-arguments,
9017 // - an explicit instantiation definition shall appear at most once
9018 // in a program,
9019
9020 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9021 Diag(NewLoc, (getLangOpts().MSVCCompat)
9022 ? diag::ext_explicit_instantiation_duplicate
9023 : diag::err_explicit_instantiation_duplicate)
9024 << PrevDecl;
9025 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9026 diag::note_previous_explicit_instantiation);
9027 HasNoEffect = true;
9028 return false;
9029 }
9030 }
9031
9032 llvm_unreachable("Missing specialization/instantiation case?");
9033}
9034
9036 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9038 // Remove anything from Previous that isn't a function template in
9039 // the correct context.
9040 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9041 LookupResult::Filter F = Previous.makeFilter();
9042 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9043 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9044 while (F.hasNext()) {
9046 if (!isa<FunctionTemplateDecl>(D)) {
9047 F.erase();
9048 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9049 continue;
9050 }
9051
9052 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9054 F.erase();
9055 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9056 continue;
9057 }
9058 }
9059 F.done();
9060
9061 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9062 if (Previous.empty()) {
9063 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9064 << IsFriend;
9065 for (auto &P : DiscardedCandidates)
9066 Diag(P.second->getLocation(),
9067 diag::note_dependent_function_template_spec_discard_reason)
9068 << P.first << IsFriend;
9069 return true;
9070 }
9071
9073 ExplicitTemplateArgs);
9074 return false;
9075}
9076
9078 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9079 LookupResult &Previous, bool QualifiedFriend) {
9080 // The set of function template specializations that could match this
9081 // explicit function template specialization.
9082 UnresolvedSet<8> Candidates;
9083 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9084 /*ForTakingAddress=*/false);
9085
9086 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9087 ConvertedTemplateArgs;
9088
9089 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9090 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9091 I != E; ++I) {
9092 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9093 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9094 // Only consider templates found within the same semantic lookup scope as
9095 // FD.
9096 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9098 continue;
9099
9100 QualType FT = FD->getType();
9101 // C++11 [dcl.constexpr]p8:
9102 // A constexpr specifier for a non-static member function that is not
9103 // a constructor declares that member function to be const.
9104 //
9105 // When matching a constexpr member function template specialization
9106 // against the primary template, we don't yet know whether the
9107 // specialization has an implicit 'const' (because we don't know whether
9108 // it will be a static member function until we know which template it
9109 // specializes). This rule was removed in C++14.
9110 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9111 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9112 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9113 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9114 if (OldMD && OldMD->isConst()) {
9115 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9117 EPI.TypeQuals.addConst();
9119 FPT->getParamTypes(), EPI);
9120 }
9121 }
9122
9124 if (ExplicitTemplateArgs)
9125 Args = *ExplicitTemplateArgs;
9126
9127 // C++ [temp.expl.spec]p11:
9128 // A trailing template-argument can be left unspecified in the
9129 // template-id naming an explicit function template specialization
9130 // provided it can be deduced from the function argument type.
9131 // Perform template argument deduction to determine whether we may be
9132 // specializing this template.
9133 // FIXME: It is somewhat wasteful to build
9134 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9135 FunctionDecl *Specialization = nullptr;
9137 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9138 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9140 // Template argument deduction failed; record why it failed, so
9141 // that we can provide nifty diagnostics.
9142 FailedCandidates.addCandidate().set(
9143 I.getPair(), FunTmpl->getTemplatedDecl(),
9144 MakeDeductionFailureInfo(Context, TDK, Info));
9145 (void)TDK;
9146 continue;
9147 }
9148
9149 // Target attributes are part of the cuda function signature, so
9150 // the deduced template's cuda target must match that of the
9151 // specialization. Given that C++ template deduction does not
9152 // take target attributes into account, we reject candidates
9153 // here that have a different target.
9154 if (LangOpts.CUDA &&
9156 /* IgnoreImplicitHDAttr = */ true) !=
9157 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9158 FailedCandidates.addCandidate().set(
9159 I.getPair(), FunTmpl->getTemplatedDecl(),
9162 continue;
9163 }
9164
9165 // Record this candidate.
9166 if (ExplicitTemplateArgs)
9167 ConvertedTemplateArgs[Specialization] = std::move(Args);
9168 Candidates.addDecl(Specialization, I.getAccess());
9169 }
9170 }
9171
9172 // For a qualified friend declaration (with no explicit marker to indicate
9173 // that a template specialization was intended), note all (template and
9174 // non-template) candidates.
9175 if (QualifiedFriend && Candidates.empty()) {
9176 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9177 << FD->getDeclName() << FDLookupContext;
9178 // FIXME: We should form a single candidate list and diagnose all
9179 // candidates at once, to get proper sorting and limiting.
9180 for (auto *OldND : Previous) {
9181 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9182 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9183 }
9184 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9185 return true;
9186 }
9187
9188 // Find the most specialized function template.
9190 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9191 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9192 PDiag(diag::err_function_template_spec_ambiguous)
9193 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9194 PDiag(diag::note_function_template_spec_matched));
9195
9196 if (Result == Candidates.end())
9197 return true;
9198
9199 // Ignore access information; it doesn't figure into redeclaration checking.
9200 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9201
9202 if (const auto *PT = Specialization->getPrimaryTemplate();
9203 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9204 auto Message = DSA->getMessage();
9205 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9206 << PT << !Message.empty() << Message;
9207 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9208 }
9209
9210 // C++23 [except.spec]p13:
9211 // An exception specification is considered to be needed when:
9212 // - [...]
9213 // - the exception specification is compared to that of another declaration
9214 // (e.g., an explicit specialization or an overriding virtual function);
9215 // - [...]
9216 //
9217 // The exception specification of a defaulted function is evaluated as
9218 // described above only when needed; similarly, the noexcept-specifier of a
9219 // specialization of a function template or member function of a class
9220 // template is instantiated only when needed.
9221 //
9222 // The standard doesn't specify what the "comparison with another declaration"
9223 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9224 // not state which properties of an explicit specialization must match the
9225 // primary template.
9226 //
9227 // We assume that an explicit specialization must correspond with (per
9228 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9229 // the declaration produced by substitution into the function template.
9230 //
9231 // Since the determination whether two function declarations correspond does
9232 // not consider exception specification, we only need to instantiate it once
9233 // we determine the primary template when comparing types per
9234 // [basic.link]p11.1.
9235 auto *SpecializationFPT =
9236 Specialization->getType()->castAs<FunctionProtoType>();
9237 // If the function has a dependent exception specification, resolve it after
9238 // we have selected the primary template so we can check whether it matches.
9239 if (getLangOpts().CPlusPlus17 &&
9240 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9241 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9242 return true;
9243
9245 = Specialization->getTemplateSpecializationInfo();
9246 assert(SpecInfo && "Function template specialization info missing?");
9247
9248 // Note: do not overwrite location info if previous template
9249 // specialization kind was explicit.
9251 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9252 Specialization->setLocation(FD->getLocation());
9253 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9254 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9255 // function can differ from the template declaration with respect to
9256 // the constexpr specifier.
9257 // FIXME: We need an update record for this AST mutation.
9258 // FIXME: What if there are multiple such prior declarations (for instance,
9259 // from different modules)?
9260 Specialization->setConstexprKind(FD->getConstexprKind());
9261 }
9262
9263 // FIXME: Check if the prior specialization has a point of instantiation.
9264 // If so, we have run afoul of .
9265
9266 // If this is a friend declaration, then we're not really declaring
9267 // an explicit specialization.
9268 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9269
9270 // Check the scope of this explicit specialization.
9271 if (!isFriend &&
9273 Specialization->getPrimaryTemplate(),
9275 false))
9276 return true;
9277
9278 // C++ [temp.expl.spec]p6:
9279 // If a template, a member template or the member of a class template is
9280 // explicitly specialized then that specialization shall be declared
9281 // before the first use of that specialization that would cause an implicit
9282 // instantiation to take place, in every translation unit in which such a
9283 // use occurs; no diagnostic is required.
9284 bool HasNoEffect = false;
9285 if (!isFriend &&
9290 SpecInfo->getPointOfInstantiation(),
9291 HasNoEffect))
9292 return true;
9293
9294 // Mark the prior declaration as an explicit specialization, so that later
9295 // clients know that this is an explicit specialization.
9296 if (!isFriend) {
9297 // Since explicit specializations do not inherit '=delete' from their
9298 // primary function template - check if the 'specialization' that was
9299 // implicitly generated (during template argument deduction for partial
9300 // ordering) from the most specialized of all the function templates that
9301 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9302 // first check that it was implicitly generated during template argument
9303 // deduction by making sure it wasn't referenced, and then reset the deleted
9304 // flag to not-deleted, so that we can inherit that information from 'FD'.
9305 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9306 !Specialization->getCanonicalDecl()->isReferenced()) {
9307 // FIXME: This assert will not hold in the presence of modules.
9308 assert(
9309 Specialization->getCanonicalDecl() == Specialization &&
9310 "This must be the only existing declaration of this specialization");
9311 // FIXME: We need an update record for this AST mutation.
9312 Specialization->setDeletedAsWritten(false);
9313 }
9314 // FIXME: We need an update record for this AST mutation.
9317 }
9318
9319 // Turn the given function declaration into a function template
9320 // specialization, with the template arguments from the previous
9321 // specialization.
9322 // Take copies of (semantic and syntactic) template argument lists.
9324 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9325 FD->setFunctionTemplateSpecialization(
9326 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9328 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9329
9330 // A function template specialization inherits the target attributes
9331 // of its template. (We require the attributes explicitly in the
9332 // code to match, but a template may have implicit attributes by
9333 // virtue e.g. of being constexpr, and it passes these implicit
9334 // attributes on to its specializations.)
9335 if (LangOpts.CUDA)
9336 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9337
9338 // The "previous declaration" for this function template specialization is
9339 // the prior function template specialization.
9340 Previous.clear();
9341 Previous.addDecl(Specialization);
9342 return false;
9343}
9344
9345bool
9347 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9348 "Only for non-template members");
9349
9350 // Try to find the member we are instantiating.
9351 NamedDecl *FoundInstantiation = nullptr;
9352 NamedDecl *Instantiation = nullptr;
9353 NamedDecl *InstantiatedFrom = nullptr;
9354 MemberSpecializationInfo *MSInfo = nullptr;
9355
9356 if (Previous.empty()) {
9357 // Nowhere to look anyway.
9358 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9359 UnresolvedSet<8> Candidates;
9360 for (NamedDecl *Candidate : Previous) {
9361 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9362 // Ignore any candidates that aren't member functions.
9363 if (!Method)
9364 continue;
9365
9366 QualType Adjusted = Function->getType();
9367 if (!hasExplicitCallingConv(Adjusted))
9368 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9369 // Ignore any candidates with the wrong type.
9370 // This doesn't handle deduced return types, but both function
9371 // declarations should be undeduced at this point.
9372 // FIXME: The exception specification should probably be ignored when
9373 // comparing the types.
9374 if (!Context.hasSameType(Adjusted, Method->getType()))
9375 continue;
9376
9377 // Ignore any candidates with unsatisfied constraints.
9378 if (ConstraintSatisfaction Satisfaction;
9379 Method->getTrailingRequiresClause() &&
9380 (CheckFunctionConstraints(Method, Satisfaction,
9381 /*UsageLoc=*/Member->getLocation(),
9382 /*ForOverloadResolution=*/true) ||
9383 !Satisfaction.IsSatisfied))
9384 continue;
9385
9386 Candidates.addDecl(Candidate);
9387 }
9388
9389 // If we have no viable candidates left after filtering, we are done.
9390 if (Candidates.empty())
9391 return false;
9392
9393 // Find the function that is more constrained than every other function it
9394 // has been compared to.
9395 UnresolvedSetIterator Best = Candidates.begin();
9396 CXXMethodDecl *BestMethod = nullptr;
9397 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9398 I != E; ++I) {
9399 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9400 if (I == Best ||
9401 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9402 Best = I;
9403 BestMethod = Method;
9404 }
9405 }
9406
9407 FoundInstantiation = *Best;
9408 Instantiation = BestMethod;
9409 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9410 MSInfo = BestMethod->getMemberSpecializationInfo();
9411
9412 // Make sure the best candidate is more constrained than all of the others.
9413 bool Ambiguous = false;
9414 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9415 I != E; ++I) {
9416 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9417 if (I != Best &&
9418 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9419 Ambiguous = true;
9420 break;
9421 }
9422 }
9423
9424 if (Ambiguous) {
9425 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9426 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9427 for (NamedDecl *Candidate : Candidates) {
9428 Candidate = Candidate->getUnderlyingDecl();
9429 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9430 << Candidate;
9431 }
9432 return true;
9433 }
9434 } else if (isa<VarDecl>(Member)) {
9435 VarDecl *PrevVar;
9436 if (Previous.isSingleResult() &&
9437 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9438 if (PrevVar->isStaticDataMember()) {
9439 FoundInstantiation = Previous.getRepresentativeDecl();
9440 Instantiation = PrevVar;
9441 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9442 MSInfo = PrevVar->getMemberSpecializationInfo();
9443 }
9444 } else if (isa<RecordDecl>(Member)) {
9445 CXXRecordDecl *PrevRecord;
9446 if (Previous.isSingleResult() &&
9447 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9448 FoundInstantiation = Previous.getRepresentativeDecl();
9449 Instantiation = PrevRecord;
9450 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9451 MSInfo = PrevRecord->getMemberSpecializationInfo();
9452 }
9453 } else if (isa<EnumDecl>(Member)) {
9454 EnumDecl *PrevEnum;
9455 if (Previous.isSingleResult() &&
9456 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9457 FoundInstantiation = Previous.getRepresentativeDecl();
9458 Instantiation = PrevEnum;
9459 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9460 MSInfo = PrevEnum->getMemberSpecializationInfo();
9461 }
9462 }
9463
9464 if (!Instantiation) {
9465 // There is no previous declaration that matches. Since member
9466 // specializations are always out-of-line, the caller will complain about
9467 // this mismatch later.
9468 return false;
9469 }
9470
9471 // A member specialization in a friend declaration isn't really declaring
9472 // an explicit specialization, just identifying a specific (possibly implicit)
9473 // specialization. Don't change the template specialization kind.
9474 //
9475 // FIXME: Is this really valid? Other compilers reject.
9476 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9477 // Preserve instantiation information.
9478 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9479 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9480 cast<CXXMethodDecl>(InstantiatedFrom),
9481 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9482 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9483 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9484 cast<CXXRecordDecl>(InstantiatedFrom),
9485 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9486 }
9487
9488 Previous.clear();
9489 Previous.addDecl(FoundInstantiation);
9490 return false;
9491 }
9492
9493 // Make sure that this is a specialization of a member.
9494 if (!InstantiatedFrom) {
9495 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9496 << Member;
9497 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9498 return true;
9499 }
9500
9501 // C++ [temp.expl.spec]p6:
9502 // If a template, a member template or the member of a class template is
9503 // explicitly specialized then that specialization shall be declared
9504 // before the first use of that specialization that would cause an implicit
9505 // instantiation to take place, in every translation unit in which such a
9506 // use occurs; no diagnostic is required.
9507 assert(MSInfo && "Member specialization info missing?");
9508
9509 bool HasNoEffect = false;
9512 Instantiation,
9514 MSInfo->getPointOfInstantiation(),
9515 HasNoEffect))
9516 return true;
9517
9518 // Check the scope of this explicit specialization.
9520 InstantiatedFrom,
9521 Instantiation, Member->getLocation(),
9522 false))
9523 return true;
9524
9525 // Note that this member specialization is an "instantiation of" the
9526 // corresponding member of the original template.
9527 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9528 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9529 if (InstantiationFunction->getTemplateSpecializationKind() ==
9531 // Explicit specializations of member functions of class templates do not
9532 // inherit '=delete' from the member function they are specializing.
9533 if (InstantiationFunction->isDeleted()) {
9534 // FIXME: This assert will not hold in the presence of modules.
9535 assert(InstantiationFunction->getCanonicalDecl() ==
9536 InstantiationFunction);
9537 // FIXME: We need an update record for this AST mutation.
9538 InstantiationFunction->setDeletedAsWritten(false);
9539 }
9540 }
9541
9542 MemberFunction->setInstantiationOfMemberFunction(
9543 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9544 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9545 MemberVar->setInstantiationOfStaticDataMember(
9546 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9547 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9548 MemberClass->setInstantiationOfMemberClass(
9549 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9550 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9551 MemberEnum->setInstantiationOfMemberEnum(
9552 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9553 } else {
9554 llvm_unreachable("unknown member specialization kind");
9555 }
9556
9557 // Save the caller the trouble of having to figure out which declaration
9558 // this specialization matches.
9559 Previous.clear();
9560 Previous.addDecl(FoundInstantiation);
9561 return false;
9562}
9563
9564/// Complete the explicit specialization of a member of a class template by
9565/// updating the instantiated member to be marked as an explicit specialization.
9566///
9567/// \param OrigD The member declaration instantiated from the template.
9568/// \param Loc The location of the explicit specialization of the member.
9569template<typename DeclT>
9570static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9572 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9573 return;
9574
9575 // FIXME: Inform AST mutation listeners of this AST mutation.
9576 // FIXME: If there are multiple in-class declarations of the member (from
9577 // multiple modules, or a declaration and later definition of a member type),
9578 // should we update all of them?
9579 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9580 OrigD->setLocation(Loc);
9581}
9582
9585 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9586 if (Instantiation == Member)
9587 return;
9588
9589 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9590 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9591 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9592 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9593 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9594 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9595 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9596 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9597 else
9598 llvm_unreachable("unknown member specialization kind");
9599}
9600
9601/// Check the scope of an explicit instantiation.
9602///
9603/// \returns true if a serious error occurs, false otherwise.
9605 SourceLocation InstLoc,
9606 bool WasQualifiedName) {
9608 DeclContext *CurContext = S.CurContext->getRedeclContext();
9609
9610 if (CurContext->isRecord()) {
9611 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9612 << D;
9613 return true;
9614 }
9615
9616 // C++11 [temp.explicit]p3:
9617 // An explicit instantiation shall appear in an enclosing namespace of its
9618 // template. If the name declared in the explicit instantiation is an
9619 // unqualified name, the explicit instantiation shall appear in the
9620 // namespace where its template is declared or, if that namespace is inline
9621 // (7.3.1), any namespace from its enclosing namespace set.
9622 //
9623 // This is DR275, which we do not retroactively apply to C++98/03.
9624 if (WasQualifiedName) {
9625 if (CurContext->Encloses(OrigContext))
9626 return false;
9627 } else {
9628 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9629 return false;
9630 }
9631
9632 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9633 if (WasQualifiedName)
9634 S.Diag(InstLoc,
9635 S.getLangOpts().CPlusPlus11?
9636 diag::err_explicit_instantiation_out_of_scope :
9637 diag::warn_explicit_instantiation_out_of_scope_0x)
9638 << D << NS;
9639 else
9640 S.Diag(InstLoc,
9641 S.getLangOpts().CPlusPlus11?
9642 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9643 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9644 << D << NS;
9645 } else
9646 S.Diag(InstLoc,
9647 S.getLangOpts().CPlusPlus11?
9648 diag::err_explicit_instantiation_must_be_global :
9649 diag::warn_explicit_instantiation_must_be_global_0x)
9650 << D;
9651 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9652 return false;
9653}
9654
9655/// Common checks for whether an explicit instantiation of \p D is valid.
9657 SourceLocation InstLoc,
9658 bool WasQualifiedName,
9660 // C++ [temp.explicit]p13:
9661 // An explicit instantiation declaration shall not name a specialization of
9662 // a template with internal linkage.
9664 D->getFormalLinkage() == Linkage::Internal) {
9665 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9666 return true;
9667 }
9668
9669 // C++11 [temp.explicit]p3: [DR 275]
9670 // An explicit instantiation shall appear in an enclosing namespace of its
9671 // template.
9672 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9673 return true;
9674
9675 return false;
9676}
9677
9678/// Determine whether the given scope specifier has a template-id in it.
9680 if (!SS.isSet())
9681 return false;
9682
9683 // C++11 [temp.explicit]p3:
9684 // If the explicit instantiation is for a member function, a member class
9685 // or a static data member of a class template specialization, the name of
9686 // the class template specialization in the qualified-id for the member
9687 // name shall be a simple-template-id.
9688 //
9689 // C++98 has the same restriction, just worded differently.
9690 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9691 NNS = NNS->getPrefix())
9692 if (const Type *T = NNS->getAsType())
9693 if (isa<TemplateSpecializationType>(T))
9694 return true;
9695
9696 return false;
9697}
9698
9699/// Make a dllexport or dllimport attr on a class template specialization take
9700/// effect.
9703 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9704 assert(A && "dllExportImportClassTemplateSpecialization called "
9705 "on Def without dllexport or dllimport");
9706
9707 // We reject explicit instantiations in class scope, so there should
9708 // never be any delayed exported classes to worry about.
9709 assert(S.DelayedDllExportClasses.empty() &&
9710 "delayed exports present at explicit instantiation");
9712
9713 // Propagate attribute to base class templates.
9714 for (auto &B : Def->bases()) {
9715 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9716 B.getType()->getAsCXXRecordDecl()))
9718 }
9719
9721}
9722
9724 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9725 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9726 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9727 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9728 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9729 // Find the class template we're specializing
9730 TemplateName Name = TemplateD.get();
9731 TemplateDecl *TD = Name.getAsTemplateDecl();
9732 // Check that the specialization uses the same tag kind as the
9733 // original template.
9735 assert(Kind != TagTypeKind::Enum &&
9736 "Invalid enum tag in class template explicit instantiation!");
9737
9738 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9739
9740 if (!ClassTemplate) {
9741 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9742 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9743 << TD << NTK << llvm::to_underlying(Kind);
9744 Diag(TD->getLocation(), diag::note_previous_use);
9745 return true;
9746 }
9747
9748 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9749 Kind, /*isDefinition*/false, KWLoc,
9750 ClassTemplate->getIdentifier())) {
9751 Diag(KWLoc, diag::err_use_with_wrong_tag)
9752 << ClassTemplate
9754 ClassTemplate->getTemplatedDecl()->getKindName());
9755 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9756 diag::note_previous_use);
9757 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9758 }
9759
9760 // C++0x [temp.explicit]p2:
9761 // There are two forms of explicit instantiation: an explicit instantiation
9762 // definition and an explicit instantiation declaration. An explicit
9763 // instantiation declaration begins with the extern keyword. [...]
9764 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9767
9769 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9770 // Check for dllexport class template instantiation declarations,
9771 // except for MinGW mode.
9772 for (const ParsedAttr &AL : Attr) {
9773 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9774 Diag(ExternLoc,
9775 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9776 Diag(AL.getLoc(), diag::note_attribute);
9777 break;
9778 }
9779 }
9780
9781 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9782 Diag(ExternLoc,
9783 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9784 Diag(A->getLocation(), diag::note_attribute);
9785 }
9786 }
9787
9788 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9789 // instantiation declarations for most purposes.
9790 bool DLLImportExplicitInstantiationDef = false;
9793 // Check for dllimport class template instantiation definitions.
9794 bool DLLImport =
9795 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9796 for (const ParsedAttr &AL : Attr) {
9797 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9798 DLLImport = true;
9799 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9800 // dllexport trumps dllimport here.
9801 DLLImport = false;
9802 break;
9803 }
9804 }
9805 if (DLLImport) {
9807 DLLImportExplicitInstantiationDef = true;
9808 }
9809 }
9810
9811 // Translate the parser's template argument list in our AST format.
9812 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9813 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9814
9815 // Check that the template argument list is well-formed for this
9816 // template.
9817 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9818 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9819 /*DefaultArgs=*/{}, false, SugaredConverted,
9820 CanonicalConverted,
9821 /*UpdateArgsWithConversions=*/true))
9822 return true;
9823
9824 // Find the class template specialization declaration that
9825 // corresponds to these arguments.
9826 void *InsertPos = nullptr;
9828 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9829
9830 TemplateSpecializationKind PrevDecl_TSK
9831 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9832
9833 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9834 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9835 // Check for dllexport class template instantiation definitions in MinGW
9836 // mode, if a previous declaration of the instantiation was seen.
9837 for (const ParsedAttr &AL : Attr) {
9838 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9839 Diag(AL.getLoc(),
9840 diag::warn_attribute_dllexport_explicit_instantiation_def);
9841 break;
9842 }
9843 }
9844 }
9845
9846 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9847 SS.isSet(), TSK))
9848 return true;
9849
9851
9852 bool HasNoEffect = false;
9853 if (PrevDecl) {
9854 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9855 PrevDecl, PrevDecl_TSK,
9856 PrevDecl->getPointOfInstantiation(),
9857 HasNoEffect))
9858 return PrevDecl;
9859
9860 // Even though HasNoEffect == true means that this explicit instantiation
9861 // has no effect on semantics, we go on to put its syntax in the AST.
9862
9863 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9864 PrevDecl_TSK == TSK_Undeclared) {
9865 // Since the only prior class template specialization with these
9866 // arguments was referenced but not declared, reuse that
9867 // declaration node as our own, updating the source location
9868 // for the template name to reflect our new declaration.
9869 // (Other source locations will be updated later.)
9870 Specialization = PrevDecl;
9871 Specialization->setLocation(TemplateNameLoc);
9872 PrevDecl = nullptr;
9873 }
9874
9875 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9876 DLLImportExplicitInstantiationDef) {
9877 // The new specialization might add a dllimport attribute.
9878 HasNoEffect = false;
9879 }
9880 }
9881
9882 if (!Specialization) {
9883 // Create a new class template specialization declaration node for
9884 // this explicit specialization.
9886 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9887 ClassTemplate, CanonicalConverted, PrevDecl);
9889
9890 // A MSInheritanceAttr attached to the previous declaration must be
9891 // propagated to the new node prior to instantiation.
9892 if (PrevDecl) {
9893 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9894 auto *Clone = A->clone(getASTContext());
9895 Clone->setInherited(true);
9896 Specialization->addAttr(Clone);
9898 }
9899 }
9900
9901 if (!HasNoEffect && !PrevDecl) {
9902 // Insert the new specialization.
9903 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9904 }
9905 }
9906
9907 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9908
9909 // Set source locations for keywords.
9910 Specialization->setExternKeywordLoc(ExternLoc);
9911 Specialization->setTemplateKeywordLoc(TemplateLoc);
9912 Specialization->setBraceRange(SourceRange());
9913
9914 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9917
9918 // Add the explicit instantiation into its lexical context. However,
9919 // since explicit instantiations are never found by name lookup, we
9920 // just put it into the declaration context directly.
9921 Specialization->setLexicalDeclContext(CurContext);
9923
9924 // Syntax is now OK, so return if it has no other effect on semantics.
9925 if (HasNoEffect) {
9926 // Set the template specialization kind.
9927 Specialization->setTemplateSpecializationKind(TSK);
9928 return Specialization;
9929 }
9930
9931 // C++ [temp.explicit]p3:
9932 // A definition of a class template or class member template
9933 // shall be in scope at the point of the explicit instantiation of
9934 // the class template or class member template.
9935 //
9936 // This check comes when we actually try to perform the
9937 // instantiation.
9939 = cast_or_null<ClassTemplateSpecializationDecl>(
9940 Specialization->getDefinition());
9941 if (!Def)
9943 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9944 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9945 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9946 }
9947
9948 // Instantiate the members of this class template specialization.
9949 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9950 Specialization->getDefinition());
9951 if (Def) {
9953 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9954 // TSK_ExplicitInstantiationDefinition
9955 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9957 DLLImportExplicitInstantiationDef)) {
9958 // FIXME: Need to notify the ASTMutationListener that we did this.
9960
9961 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9963 // An explicit instantiation definition can add a dll attribute to a
9964 // template with a previous instantiation declaration. MinGW doesn't
9965 // allow this.
9966 auto *A = cast<InheritableAttr>(
9968 A->setInherited(true);
9969 Def->addAttr(A);
9971 }
9972 }
9973
9974 // Fix a TSK_ImplicitInstantiation followed by a
9975 // TSK_ExplicitInstantiationDefinition
9976 bool NewlyDLLExported =
9977 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9978 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9980 // An explicit instantiation definition can add a dll attribute to a
9981 // template with a previous implicit instantiation. MinGW doesn't allow
9982 // this. We limit clang to only adding dllexport, to avoid potentially
9983 // strange codegen behavior. For example, if we extend this conditional
9984 // to dllimport, and we have a source file calling a method on an
9985 // implicitly instantiated template class instance and then declaring a
9986 // dllimport explicit instantiation definition for the same template
9987 // class, the codegen for the method call will not respect the dllimport,
9988 // while it will with cl. The Def will already have the DLL attribute,
9989 // since the Def and Specialization will be the same in the case of
9990 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9991 // attribute to the Specialization; we just need to make it take effect.
9992 assert(Def == Specialization &&
9993 "Def and Specialization should match for implicit instantiation");
9995 }
9996
9997 // In MinGW mode, export the template instantiation if the declaration
9998 // was marked dllexport.
9999 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10000 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10001 PrevDecl->hasAttr<DLLExportAttr>()) {
10003 }
10004
10005 // Set the template specialization kind. Make sure it is set before
10006 // instantiating the members which will trigger ASTConsumer callbacks.
10007 Specialization->setTemplateSpecializationKind(TSK);
10008 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10009 } else {
10010
10011 // Set the template specialization kind.
10012 Specialization->setTemplateSpecializationKind(TSK);
10013 }
10014
10015 return Specialization;
10016}
10017
10020 SourceLocation TemplateLoc, unsigned TagSpec,
10021 SourceLocation KWLoc, CXXScopeSpec &SS,
10022 IdentifierInfo *Name, SourceLocation NameLoc,
10023 const ParsedAttributesView &Attr) {
10024
10025 bool Owned = false;
10026 bool IsDependent = false;
10027 Decl *TagD =
10028 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10029 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10030 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10031 false, TypeResult(), /*IsTypeSpecifier*/ false,
10032 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
10033 .get();
10034 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10035
10036 if (!TagD)
10037 return true;
10038
10039 TagDecl *Tag = cast<TagDecl>(TagD);
10040 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10041
10042 if (Tag->isInvalidDecl())
10043 return true;
10044
10045 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10047 if (!Pattern) {
10048 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10050 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10051 return true;
10052 }
10053
10054 // C++0x [temp.explicit]p2:
10055 // If the explicit instantiation is for a class or member class, the
10056 // elaborated-type-specifier in the declaration shall include a
10057 // simple-template-id.
10058 //
10059 // C++98 has the same restriction, just worded differently.
10061 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10062 << Record << SS.getRange();
10063
10064 // C++0x [temp.explicit]p2:
10065 // There are two forms of explicit instantiation: an explicit instantiation
10066 // definition and an explicit instantiation declaration. An explicit
10067 // instantiation declaration begins with the extern keyword. [...]
10071
10072 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10073
10074 // Verify that it is okay to explicitly instantiate here.
10075 CXXRecordDecl *PrevDecl
10076 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10077 if (!PrevDecl && Record->getDefinition())
10078 PrevDecl = Record;
10079 if (PrevDecl) {
10081 bool HasNoEffect = false;
10082 assert(MSInfo && "No member specialization information?");
10083 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10084 PrevDecl,
10086 MSInfo->getPointOfInstantiation(),
10087 HasNoEffect))
10088 return true;
10089 if (HasNoEffect)
10090 return TagD;
10091 }
10092
10093 CXXRecordDecl *RecordDef
10094 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10095 if (!RecordDef) {
10096 // C++ [temp.explicit]p3:
10097 // A definition of a member class of a class template shall be in scope
10098 // at the point of an explicit instantiation of the member class.
10099 CXXRecordDecl *Def
10100 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10101 if (!Def) {
10102 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10103 << 0 << Record->getDeclName() << Record->getDeclContext();
10104 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10105 << Pattern;
10106 return true;
10107 } else {
10108 if (InstantiateClass(NameLoc, Record, Def,
10110 TSK))
10111 return true;
10112
10113 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10114 if (!RecordDef)
10115 return true;
10116 }
10117 }
10118
10119 // Instantiate all of the members of the class.
10120 InstantiateClassMembers(NameLoc, RecordDef,
10122
10124 MarkVTableUsed(NameLoc, RecordDef, true);
10125
10126 // FIXME: We don't have any representation for explicit instantiations of
10127 // member classes. Such a representation is not needed for compilation, but it
10128 // should be available for clients that want to see all of the declarations in
10129 // the source code.
10130 return TagD;
10131}
10132
10134 SourceLocation ExternLoc,
10135 SourceLocation TemplateLoc,
10136 Declarator &D) {
10137 // Explicit instantiations always require a name.
10138 // TODO: check if/when DNInfo should replace Name.
10140 DeclarationName Name = NameInfo.getName();
10141 if (!Name) {
10142 if (!D.isInvalidType())
10143 Diag(D.getDeclSpec().getBeginLoc(),
10144 diag::err_explicit_instantiation_requires_name)
10145 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10146
10147 return true;
10148 }
10149
10150 // Get the innermost enclosing declaration scope.
10151 S = S->getDeclParent();
10152
10153 // Determine the type of the declaration.
10155 QualType R = T->getType();
10156 if (R.isNull())
10157 return true;
10158
10159 // C++ [dcl.stc]p1:
10160 // A storage-class-specifier shall not be specified in [...] an explicit
10161 // instantiation (14.7.2) directive.
10162 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10163 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10164 << Name;
10165 return true;
10166 } else if (D.getDeclSpec().getStorageClassSpec()
10168 // Complain about then remove the storage class specifier.
10169 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10170 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10171
10172 D.getMutableDeclSpec().ClearStorageClassSpecs();
10173 }
10174
10175 // C++0x [temp.explicit]p1:
10176 // [...] An explicit instantiation of a function template shall not use the
10177 // inline or constexpr specifiers.
10178 // Presumably, this also applies to member functions of class templates as
10179 // well.
10180 if (D.getDeclSpec().isInlineSpecified())
10181 Diag(D.getDeclSpec().getInlineSpecLoc(),
10183 diag::err_explicit_instantiation_inline :
10184 diag::warn_explicit_instantiation_inline_0x)
10185 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10186 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10187 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10188 // not already specified.
10189 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10190 diag::err_explicit_instantiation_constexpr);
10191
10192 // A deduction guide is not on the list of entities that can be explicitly
10193 // instantiated.
10194 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10195 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10196 << /*explicit instantiation*/ 0;
10197 return true;
10198 }
10199
10200 // C++0x [temp.explicit]p2:
10201 // There are two forms of explicit instantiation: an explicit instantiation
10202 // definition and an explicit instantiation declaration. An explicit
10203 // instantiation declaration begins with the extern keyword. [...]
10207
10208 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10209 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10210 /*ObjectType=*/QualType());
10211
10212 if (!R->isFunctionType()) {
10213 // C++ [temp.explicit]p1:
10214 // A [...] static data member of a class template can be explicitly
10215 // instantiated from the member definition associated with its class
10216 // template.
10217 // C++1y [temp.explicit]p1:
10218 // A [...] variable [...] template specialization can be explicitly
10219 // instantiated from its template.
10220 if (Previous.isAmbiguous())
10221 return true;
10222
10223 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10224 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10225
10226 if (!PrevTemplate) {
10227 if (!Prev || !Prev->isStaticDataMember()) {
10228 // We expect to see a static data member here.
10229 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10230 << Name;
10231 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10232 P != PEnd; ++P)
10233 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10234 return true;
10235 }
10236
10238 // FIXME: Check for explicit specialization?
10239 Diag(D.getIdentifierLoc(),
10240 diag::err_explicit_instantiation_data_member_not_instantiated)
10241 << Prev;
10242 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10243 // FIXME: Can we provide a note showing where this was declared?
10244 return true;
10245 }
10246 } else {
10247 // Explicitly instantiate a variable template.
10248
10249 // C++1y [dcl.spec.auto]p6:
10250 // ... A program that uses auto or decltype(auto) in a context not
10251 // explicitly allowed in this section is ill-formed.
10252 //
10253 // This includes auto-typed variable template instantiations.
10254 if (R->isUndeducedType()) {
10255 Diag(T->getTypeLoc().getBeginLoc(),
10256 diag::err_auto_not_allowed_var_inst);
10257 return true;
10258 }
10259
10260 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10261 // C++1y [temp.explicit]p3:
10262 // If the explicit instantiation is for a variable, the unqualified-id
10263 // in the declaration shall be a template-id.
10264 Diag(D.getIdentifierLoc(),
10265 diag::err_explicit_instantiation_without_template_id)
10266 << PrevTemplate;
10267 Diag(PrevTemplate->getLocation(),
10268 diag::note_explicit_instantiation_here);
10269 return true;
10270 }
10271
10272 // Translate the parser's template argument list into our AST format.
10273 TemplateArgumentListInfo TemplateArgs =
10274 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10275
10276 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10277 D.getIdentifierLoc(), TemplateArgs);
10278 if (Res.isInvalid())
10279 return true;
10280
10281 if (!Res.isUsable()) {
10282 // We somehow specified dependent template arguments in an explicit
10283 // instantiation. This should probably only happen during error
10284 // recovery.
10285 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10286 return true;
10287 }
10288
10289 // Ignore access control bits, we don't need them for redeclaration
10290 // checking.
10291 Prev = cast<VarDecl>(Res.get());
10292 }
10293
10294 // C++0x [temp.explicit]p2:
10295 // If the explicit instantiation is for a member function, a member class
10296 // or a static data member of a class template specialization, the name of
10297 // the class template specialization in the qualified-id for the member
10298 // name shall be a simple-template-id.
10299 //
10300 // C++98 has the same restriction, just worded differently.
10301 //
10302 // This does not apply to variable template specializations, where the
10303 // template-id is in the unqualified-id instead.
10304 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10305 Diag(D.getIdentifierLoc(),
10306 diag::ext_explicit_instantiation_without_qualified_id)
10307 << Prev << D.getCXXScopeSpec().getRange();
10308
10309 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10310
10311 // Verify that it is okay to explicitly instantiate here.
10314 bool HasNoEffect = false;
10315 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10316 PrevTSK, POI, HasNoEffect))
10317 return true;
10318
10319 if (!HasNoEffect) {
10320 // Instantiate static data member or variable template.
10321 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10322 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10323 VTSD->setExternKeywordLoc(ExternLoc);
10324 VTSD->setTemplateKeywordLoc(TemplateLoc);
10325 }
10326
10327 // Merge attributes.
10328 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10329 if (PrevTemplate)
10330 ProcessAPINotes(Prev);
10331
10333 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10334 }
10335
10336 // Check the new variable specialization against the parsed input.
10337 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10338 Diag(T->getTypeLoc().getBeginLoc(),
10339 diag::err_invalid_var_template_spec_type)
10340 << 0 << PrevTemplate << R << Prev->getType();
10341 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10342 << 2 << PrevTemplate->getDeclName();
10343 return true;
10344 }
10345
10346 // FIXME: Create an ExplicitInstantiation node?
10347 return (Decl*) nullptr;
10348 }
10349
10350 // If the declarator is a template-id, translate the parser's template
10351 // argument list into our AST format.
10352 bool HasExplicitTemplateArgs = false;
10353 TemplateArgumentListInfo TemplateArgs;
10354 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10355 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10356 HasExplicitTemplateArgs = true;
10357 }
10358
10359 // C++ [temp.explicit]p1:
10360 // A [...] function [...] can be explicitly instantiated from its template.
10361 // A member function [...] of a class template can be explicitly
10362 // instantiated from the member definition associated with its class
10363 // template.
10364 UnresolvedSet<8> TemplateMatches;
10365 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10367 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10368 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10369 P != PEnd; ++P) {
10370 NamedDecl *Prev = *P;
10371 if (!HasExplicitTemplateArgs) {
10372 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10373 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10374 /*AdjustExceptionSpec*/true);
10375 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10376 if (Method->getPrimaryTemplate()) {
10377 TemplateMatches.addDecl(Method, P.getAccess());
10378 } else {
10379 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10380 C.FoundDecl = P.getPair();
10381 C.Function = Method;
10382 C.Viable = true;
10384 if (Method->getTrailingRequiresClause() &&
10385 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10386 /*ForOverloadResolution=*/true) ||
10387 !S.IsSatisfied)) {
10388 C.Viable = false;
10390 }
10391 }
10392 }
10393 }
10394 }
10395
10396 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10397 if (!FunTmpl)
10398 continue;
10399
10400 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10401 FunctionDecl *Specialization = nullptr;
10403 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10404 Specialization, Info);
10406 // Keep track of almost-matches.
10407 FailedTemplateCandidates.addCandidate().set(
10408 P.getPair(), FunTmpl->getTemplatedDecl(),
10409 MakeDeductionFailureInfo(Context, TDK, Info));
10410 (void)TDK;
10411 continue;
10412 }
10413
10414 // Target attributes are part of the cuda function signature, so
10415 // the cuda target of the instantiated function must match that of its
10416 // template. Given that C++ template deduction does not take
10417 // target attributes into account, we reject candidates here that
10418 // have a different target.
10419 if (LangOpts.CUDA &&
10421 /* IgnoreImplicitHDAttr = */ true) !=
10422 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10423 FailedTemplateCandidates.addCandidate().set(
10424 P.getPair(), FunTmpl->getTemplatedDecl(),
10427 continue;
10428 }
10429
10430 TemplateMatches.addDecl(Specialization, P.getAccess());
10431 }
10432
10433 FunctionDecl *Specialization = nullptr;
10434 if (!NonTemplateMatches.empty()) {
10435 unsigned Msg = 0;
10436 OverloadCandidateDisplayKind DisplayKind;
10438 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10439 Best)) {
10440 case OR_Success:
10441 case OR_Deleted:
10442 Specialization = cast<FunctionDecl>(Best->Function);
10443 break;
10444 case OR_Ambiguous:
10445 Msg = diag::err_explicit_instantiation_ambiguous;
10446 DisplayKind = OCD_AmbiguousCandidates;
10447 break;
10449 Msg = diag::err_explicit_instantiation_no_candidate;
10450 DisplayKind = OCD_AllCandidates;
10451 break;
10452 }
10453 if (Msg) {
10454 PartialDiagnostic Diag = PDiag(Msg) << Name;
10455 NonTemplateMatches.NoteCandidates(
10456 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10457 {});
10458 return true;
10459 }
10460 }
10461
10462 if (!Specialization) {
10463 // Find the most specialized function template specialization.
10465 TemplateMatches.begin(), TemplateMatches.end(),
10466 FailedTemplateCandidates, D.getIdentifierLoc(),
10467 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10468 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10469 PDiag(diag::note_explicit_instantiation_candidate));
10470
10471 if (Result == TemplateMatches.end())
10472 return true;
10473
10474 // Ignore access control bits, we don't need them for redeclaration checking.
10475 Specialization = cast<FunctionDecl>(*Result);
10476 }
10477
10478 // C++11 [except.spec]p4
10479 // In an explicit instantiation an exception-specification may be specified,
10480 // but is not required.
10481 // If an exception-specification is specified in an explicit instantiation
10482 // directive, it shall be compatible with the exception-specifications of
10483 // other declarations of that function.
10484 if (auto *FPT = R->getAs<FunctionProtoType>())
10485 if (FPT->hasExceptionSpec()) {
10486 unsigned DiagID =
10487 diag::err_mismatched_exception_spec_explicit_instantiation;
10488 if (getLangOpts().MicrosoftExt)
10489 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10491 PDiag(DiagID) << Specialization->getType(),
10492 PDiag(diag::note_explicit_instantiation_here),
10493 Specialization->getType()->getAs<FunctionProtoType>(),
10494 Specialization->getLocation(), FPT, D.getBeginLoc());
10495 // In Microsoft mode, mismatching exception specifications just cause a
10496 // warning.
10497 if (!getLangOpts().MicrosoftExt && Result)
10498 return true;
10499 }
10500
10501 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10502 Diag(D.getIdentifierLoc(),
10503 diag::err_explicit_instantiation_member_function_not_instantiated)
10505 << (Specialization->getTemplateSpecializationKind() ==
10507 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10508 return true;
10509 }
10510
10511 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10512 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10513 PrevDecl = Specialization;
10514
10515 if (PrevDecl) {
10516 bool HasNoEffect = false;
10517 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10518 PrevDecl,
10520 PrevDecl->getPointOfInstantiation(),
10521 HasNoEffect))
10522 return true;
10523
10524 // FIXME: We may still want to build some representation of this
10525 // explicit specialization.
10526 if (HasNoEffect)
10527 return (Decl*) nullptr;
10528 }
10529
10530 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10531 // functions
10532 // valarray<size_t>::valarray(size_t) and
10533 // valarray<size_t>::~valarray()
10534 // that it declared to have internal linkage with the internal_linkage
10535 // attribute. Ignore the explicit instantiation declaration in this case.
10536 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10538 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10539 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10540 RD->isInStdNamespace())
10541 return (Decl*) nullptr;
10542 }
10543
10544 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10546
10547 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10548 // instantiation declarations.
10550 Specialization->hasAttr<DLLImportAttr>() &&
10553
10554 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10555
10556 if (Specialization->isDefined()) {
10557 // Let the ASTConsumer know that this function has been explicitly
10558 // instantiated now, and its linkage might have changed.
10560 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10561 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10562
10563 // C++0x [temp.explicit]p2:
10564 // If the explicit instantiation is for a member function, a member class
10565 // or a static data member of a class template specialization, the name of
10566 // the class template specialization in the qualified-id for the member
10567 // name shall be a simple-template-id.
10568 //
10569 // C++98 has the same restriction, just worded differently.
10570 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10571 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10572 D.getCXXScopeSpec().isSet() &&
10573 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10574 Diag(D.getIdentifierLoc(),
10575 diag::ext_explicit_instantiation_without_qualified_id)
10576 << Specialization << D.getCXXScopeSpec().getRange();
10577
10579 *this,
10580 FunTmpl ? (NamedDecl *)FunTmpl
10581 : Specialization->getInstantiatedFromMemberFunction(),
10582 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10583
10584 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10585 return (Decl*) nullptr;
10586}
10587
10589 const CXXScopeSpec &SS,
10590 const IdentifierInfo *Name,
10591 SourceLocation TagLoc,
10592 SourceLocation NameLoc) {
10593 // This has to hold, because SS is expected to be defined.
10594 assert(Name && "Expected a name in a dependent tag");
10595
10596 NestedNameSpecifier *NNS = SS.getScopeRep();
10597 if (!NNS)
10598 return true;
10599
10601
10602 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10603 Diag(NameLoc, diag::err_dependent_tag_decl)
10604 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10605 << SS.getRange();
10606 return true;
10607 }
10608
10609 // Create the resulting type.
10611 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10612
10613 // Create type-source location information for this type.
10614 TypeLocBuilder TLB;
10616 TL.setElaboratedKeywordLoc(TagLoc);
10618 TL.setNameLoc(NameLoc);
10620}
10621
10623 const CXXScopeSpec &SS,
10624 const IdentifierInfo &II,
10625 SourceLocation IdLoc,
10626 ImplicitTypenameContext IsImplicitTypename) {
10627 if (SS.isInvalid())
10628 return true;
10629
10630 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10631 Diag(TypenameLoc,
10633 diag::warn_cxx98_compat_typename_outside_of_template :
10634 diag::ext_typename_outside_of_template)
10635 << FixItHint::CreateRemoval(TypenameLoc);
10636
10638 TypeSourceInfo *TSI = nullptr;
10639 QualType T =
10640 CheckTypenameType((TypenameLoc.isValid() ||
10641 IsImplicitTypename == ImplicitTypenameContext::Yes)
10644 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10645 /*DeducedTSTContext=*/true);
10646 if (T.isNull())
10647 return true;
10648 return CreateParsedType(T, TSI);
10649}
10650
10653 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10654 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10655 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10656 ASTTemplateArgsPtr TemplateArgsIn,
10657 SourceLocation RAngleLoc) {
10658 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10659 Diag(TypenameLoc,
10661 diag::warn_cxx98_compat_typename_outside_of_template :
10662 diag::ext_typename_outside_of_template)
10663 << FixItHint::CreateRemoval(TypenameLoc);
10664
10665 // Strangely, non-type results are not ignored by this lookup, so the
10666 // program is ill-formed if it finds an injected-class-name.
10667 if (TypenameLoc.isValid()) {
10668 auto *LookupRD =
10669 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10670 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10671 Diag(TemplateIILoc,
10672 diag::ext_out_of_line_qualified_id_type_names_constructor)
10673 << TemplateII << 0 /*injected-class-name used as template name*/
10674 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10675 }
10676 }
10677
10678 // Translate the parser's template argument list in our AST format.
10679 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10680 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10681
10682 TemplateName Template = TemplateIn.get();
10683 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10684 // Construct a dependent template specialization type.
10685 assert(DTN && "dependent template has non-dependent name?");
10686 assert(DTN->getQualifier() == SS.getScopeRep());
10687
10688 if (!DTN->isIdentifier()) {
10689 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10690 NoteAllFoundTemplates(Template);
10691 return true;
10692 }
10693
10695 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10696 DTN->getIdentifier(), TemplateArgs.arguments());
10697
10698 // Create source-location information for this type.
10699 TypeLocBuilder Builder;
10702 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10704 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10705 SpecTL.setTemplateNameLoc(TemplateIILoc);
10706 SpecTL.setLAngleLoc(LAngleLoc);
10707 SpecTL.setRAngleLoc(RAngleLoc);
10708 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10709 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10710 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10711 }
10712
10713 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10714 if (T.isNull())
10715 return true;
10716
10717 // Provide source-location information for the template specialization type.
10718 TypeLocBuilder Builder;
10720 = Builder.push<TemplateSpecializationTypeLoc>(T);
10721 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10722 SpecTL.setTemplateNameLoc(TemplateIILoc);
10723 SpecTL.setLAngleLoc(LAngleLoc);
10724 SpecTL.setRAngleLoc(RAngleLoc);
10725 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10726 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10727
10729 SS.getScopeRep(), T);
10730 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10731 TL.setElaboratedKeywordLoc(TypenameLoc);
10733
10734 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10735 return CreateParsedType(T, TSI);
10736}
10737
10738/// Determine whether this failed name lookup should be treated as being
10739/// disabled by a usage of std::enable_if.
10741 SourceRange &CondRange, Expr *&Cond) {
10742 // We must be looking for a ::type...
10743 if (!II.isStr("type"))
10744 return false;
10745
10746 // ... within an explicitly-written template specialization...
10747 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10748 return false;
10749 TypeLoc EnableIfTy = NNS.getTypeLoc();
10750 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10752 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10753 return false;
10754 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10755
10756 // ... which names a complete class template declaration...
10757 const TemplateDecl *EnableIfDecl =
10758 EnableIfTST->getTemplateName().getAsTemplateDecl();
10759 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10760 return false;
10761
10762 // ... called "enable_if".
10763 const IdentifierInfo *EnableIfII =
10764 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10765 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10766 return false;
10767
10768 // Assume the first template argument is the condition.
10769 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10770
10771 // Dig out the condition.
10772 Cond = nullptr;
10773 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10775 return true;
10776
10777 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10778
10779 // Ignore Boolean literals; they add no value.
10780 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10781 Cond = nullptr;
10782
10783 return true;
10784}
10785
10788 SourceLocation KeywordLoc,
10789 NestedNameSpecifierLoc QualifierLoc,
10790 const IdentifierInfo &II,
10791 SourceLocation IILoc,
10792 TypeSourceInfo **TSI,
10793 bool DeducedTSTContext) {
10794 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10795 DeducedTSTContext);
10796 if (T.isNull())
10797 return QualType();
10798
10800 if (isa<DependentNameType>(T)) {
10802 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10803 TL.setElaboratedKeywordLoc(KeywordLoc);
10804 TL.setQualifierLoc(QualifierLoc);
10805 TL.setNameLoc(IILoc);
10806 } else {
10807 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10808 TL.setElaboratedKeywordLoc(KeywordLoc);
10809 TL.setQualifierLoc(QualifierLoc);
10810 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10811 }
10812 return T;
10813}
10814
10815/// Build the type that describes a C++ typename specifier,
10816/// e.g., "typename T::type".
10819 SourceLocation KeywordLoc,
10820 NestedNameSpecifierLoc QualifierLoc,
10821 const IdentifierInfo &II,
10822 SourceLocation IILoc, bool DeducedTSTContext) {
10823 CXXScopeSpec SS;
10824 SS.Adopt(QualifierLoc);
10825
10826 DeclContext *Ctx = nullptr;
10827 if (QualifierLoc) {
10828 Ctx = computeDeclContext(SS);
10829 if (!Ctx) {
10830 // If the nested-name-specifier is dependent and couldn't be
10831 // resolved to a type, build a typename type.
10832 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10833 return Context.getDependentNameType(Keyword,
10834 QualifierLoc.getNestedNameSpecifier(),
10835 &II);
10836 }
10837
10838 // If the nested-name-specifier refers to the current instantiation,
10839 // the "typename" keyword itself is superfluous. In C++03, the
10840 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10841 // allows such extraneous "typename" keywords, and we retroactively
10842 // apply this DR to C++03 code with only a warning. In any case we continue.
10843
10844 if (RequireCompleteDeclContext(SS, Ctx))
10845 return QualType();
10846 }
10847
10848 DeclarationName Name(&II);
10849 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10850 if (Ctx)
10851 LookupQualifiedName(Result, Ctx, SS);
10852 else
10853 LookupName(Result, CurScope);
10854 unsigned DiagID = 0;
10855 Decl *Referenced = nullptr;
10856 switch (Result.getResultKind()) {
10858 // If we're looking up 'type' within a template named 'enable_if', produce
10859 // a more specific diagnostic.
10860 SourceRange CondRange;
10861 Expr *Cond = nullptr;
10862 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10863 // If we have a condition, narrow it down to the specific failed
10864 // condition.
10865 if (Cond) {
10866 Expr *FailedCond;
10867 std::string FailedDescription;
10868 std::tie(FailedCond, FailedDescription) =
10870
10871 Diag(FailedCond->getExprLoc(),
10872 diag::err_typename_nested_not_found_requirement)
10873 << FailedDescription
10874 << FailedCond->getSourceRange();
10875 return QualType();
10876 }
10877
10878 Diag(CondRange.getBegin(),
10879 diag::err_typename_nested_not_found_enable_if)
10880 << Ctx << CondRange;
10881 return QualType();
10882 }
10883
10884 DiagID = Ctx ? diag::err_typename_nested_not_found
10885 : diag::err_unknown_typename;
10886 break;
10887 }
10888
10890 // We found a using declaration that is a value. Most likely, the using
10891 // declaration itself is meant to have the 'typename' keyword.
10892 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10893 IILoc);
10894 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10895 << Name << Ctx << FullRange;
10896 if (UnresolvedUsingValueDecl *Using
10897 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10898 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10899 Diag(Loc, diag::note_using_value_decl_missing_typename)
10900 << FixItHint::CreateInsertion(Loc, "typename ");
10901 }
10902 }
10903 // Fall through to create a dependent typename type, from which we can recover
10904 // better.
10905 [[fallthrough]];
10906
10908 // Okay, it's a member of an unknown instantiation.
10909 return Context.getDependentNameType(Keyword,
10910 QualifierLoc.getNestedNameSpecifier(),
10911 &II);
10912
10914 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10915 // C++ [class.qual]p2:
10916 // In a lookup in which function names are not ignored and the
10917 // nested-name-specifier nominates a class C, if the name specified
10918 // after the nested-name-specifier, when looked up in C, is the
10919 // injected-class-name of C [...] then the name is instead considered
10920 // to name the constructor of class C.
10921 //
10922 // Unlike in an elaborated-type-specifier, function names are not ignored
10923 // in typename-specifier lookup. However, they are ignored in all the
10924 // contexts where we form a typename type with no keyword (that is, in
10925 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10926 //
10927 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10928 // ignore functions, but that appears to be an oversight.
10929 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10930 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10931 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10932 FoundRD->isInjectedClassName() &&
10933 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10934 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10935 << &II << 1 << 0 /*'typename' keyword used*/;
10936
10937 // We found a type. Build an ElaboratedType, since the
10938 // typename-specifier was just sugar.
10939 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10940 return Context.getElaboratedType(Keyword,
10941 QualifierLoc.getNestedNameSpecifier(),
10943 }
10944
10945 // C++ [dcl.type.simple]p2:
10946 // A type-specifier of the form
10947 // typename[opt] nested-name-specifier[opt] template-name
10948 // is a placeholder for a deduced class type [...].
10949 if (getLangOpts().CPlusPlus17) {
10950 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10951 if (!DeducedTSTContext) {
10952 QualType T(QualifierLoc
10953 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10954 : nullptr, 0);
10955 if (!T.isNull())
10956 Diag(IILoc, diag::err_dependent_deduced_tst)
10958 else
10959 Diag(IILoc, diag::err_deduced_tst)
10962 return QualType();
10963 }
10965 Keyword, QualifierLoc.getNestedNameSpecifier(),
10967 QualType(), false));
10968 }
10969 }
10970
10971 DiagID = Ctx ? diag::err_typename_nested_not_type
10972 : diag::err_typename_not_type;
10973 Referenced = Result.getFoundDecl();
10974 break;
10975
10977 DiagID = Ctx ? diag::err_typename_nested_not_type
10978 : diag::err_typename_not_type;
10979 Referenced = *Result.begin();
10980 break;
10981
10983 return QualType();
10984 }
10985
10986 // If we get here, it's because name lookup did not find a
10987 // type. Emit an appropriate diagnostic and return an error.
10988 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10989 IILoc);
10990 if (Ctx)
10991 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10992 else
10993 Diag(IILoc, DiagID) << FullRange << Name;
10994 if (Referenced)
10995 Diag(Referenced->getLocation(),
10996 Ctx ? diag::note_typename_member_refers_here
10997 : diag::note_typename_refers_here)
10998 << Name;
10999 return QualType();
11000}
11001
11002namespace {
11003 // See Sema::RebuildTypeInCurrentInstantiation
11004 class CurrentInstantiationRebuilder
11005 : public TreeTransform<CurrentInstantiationRebuilder> {
11007 DeclarationName Entity;
11008
11009 public:
11011
11012 CurrentInstantiationRebuilder(Sema &SemaRef,
11014 DeclarationName Entity)
11015 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11016 Loc(Loc), Entity(Entity) { }
11017
11018 /// Determine whether the given type \p T has already been
11019 /// transformed.
11020 ///
11021 /// For the purposes of type reconstruction, a type has already been
11022 /// transformed if it is NULL or if it is not dependent.
11023 bool AlreadyTransformed(QualType T) {
11024 return T.isNull() || !T->isInstantiationDependentType();
11025 }
11026
11027 /// Returns the location of the entity whose type is being
11028 /// rebuilt.
11029 SourceLocation getBaseLocation() { return Loc; }
11030
11031 /// Returns the name of the entity whose type is being rebuilt.
11032 DeclarationName getBaseEntity() { return Entity; }
11033
11034 /// Sets the "base" location and entity when that
11035 /// information is known based on another transformation.
11036 void setBase(SourceLocation Loc, DeclarationName Entity) {
11037 this->Loc = Loc;
11038 this->Entity = Entity;
11039 }
11040
11041 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11042 // Lambdas never need to be transformed.
11043 return E;
11044 }
11045 };
11046} // end anonymous namespace
11047
11050 DeclarationName Name) {
11051 if (!T || !T->getType()->isInstantiationDependentType())
11052 return T;
11053
11054 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11055 return Rebuilder.TransformType(T);
11056}
11057
11059 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11060 DeclarationName());
11061 return Rebuilder.TransformExpr(E);
11062}
11063
11065 if (SS.isInvalid())
11066 return true;
11067
11069 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11070 DeclarationName());
11072 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11073 if (!Rebuilt)
11074 return true;
11075
11076 SS.Adopt(Rebuilt);
11077 return false;
11078}
11079
11081 TemplateParameterList *Params) {
11082 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11083 Decl *Param = Params->getParam(I);
11084
11085 // There is nothing to rebuild in a type parameter.
11086 if (isa<TemplateTypeParmDecl>(Param))
11087 continue;
11088
11089 // Rebuild the template parameter list of a template template parameter.
11091 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11093 TTP->getTemplateParameters()))
11094 return true;
11095
11096 continue;
11097 }
11098
11099 // Rebuild the type of a non-type template parameter.
11100 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11101 TypeSourceInfo *NewTSI
11103 NTTP->getLocation(),
11104 NTTP->getDeclName());
11105 if (!NewTSI)
11106 return true;
11107
11108 if (NewTSI->getType()->isUndeducedType()) {
11109 // C++17 [temp.dep.expr]p3:
11110 // An id-expression is type-dependent if it contains
11111 // - an identifier associated by name lookup with a non-type
11112 // template-parameter declared with a type that contains a
11113 // placeholder type (7.1.7.4),
11114 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11115 }
11116
11117 if (NewTSI != NTTP->getTypeSourceInfo()) {
11118 NTTP->setTypeSourceInfo(NewTSI);
11119 NTTP->setType(NewTSI->getType());
11120 }
11121 }
11122
11123 return false;
11124}
11125
11126std::string
11128 const TemplateArgumentList &Args) {
11129 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11130}
11131
11132std::string
11134 const TemplateArgument *Args,
11135 unsigned NumArgs) {
11136 SmallString<128> Str;
11137 llvm::raw_svector_ostream Out(Str);
11138
11139 if (!Params || Params->size() == 0 || NumArgs == 0)
11140 return std::string();
11141
11142 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11143 if (I >= NumArgs)
11144 break;
11145
11146 if (I == 0)
11147 Out << "[with ";
11148 else
11149 Out << ", ";
11150
11151 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11152 Out << Id->getName();
11153 } else {
11154 Out << '$' << I;
11155 }
11156
11157 Out << " = ";
11158 Args[I].print(getPrintingPolicy(), Out,
11160 getPrintingPolicy(), Params, I));
11161 }
11162
11163 Out << ']';
11164 return std::string(Out.str());
11165}
11166
11168 CachedTokens &Toks) {
11169 if (!FD)
11170 return;
11171
11172 auto LPT = std::make_unique<LateParsedTemplate>();
11173
11174 // Take tokens to avoid allocations
11175 LPT->Toks.swap(Toks);
11176 LPT->D = FnD;
11177 LPT->FPO = getCurFPFeatures();
11178 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11179
11180 FD->setLateTemplateParsed(true);
11181}
11182
11184 if (!FD)
11185 return;
11186 FD->setLateTemplateParsed(false);
11187}
11188
11190 DeclContext *DC = CurContext;
11191
11192 while (DC) {
11193 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11194 const FunctionDecl *FD = RD->isLocalClass();
11195 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11196 } else if (DC->isTranslationUnit() || DC->isNamespace())
11197 return false;
11198
11199 DC = DC->getParent();
11200 }
11201 return false;
11202}
11203
11204namespace {
11205/// Walk the path from which a declaration was instantiated, and check
11206/// that every explicit specialization along that path is visible. This enforces
11207/// C++ [temp.expl.spec]/6:
11208///
11209/// If a template, a member template or a member of a class template is
11210/// explicitly specialized then that specialization shall be declared before
11211/// the first use of that specialization that would cause an implicit
11212/// instantiation to take place, in every translation unit in which such a
11213/// use occurs; no diagnostic is required.
11214///
11215/// and also C++ [temp.class.spec]/1:
11216///
11217/// A partial specialization shall be declared before the first use of a
11218/// class template specialization that would make use of the partial
11219/// specialization as the result of an implicit or explicit instantiation
11220/// in every translation unit in which such a use occurs; no diagnostic is
11221/// required.
11222class ExplicitSpecializationVisibilityChecker {
11223 Sema &S;
11227
11228public:
11229 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11231 : S(S), Loc(Loc), Kind(Kind) {}
11232
11233 void check(NamedDecl *ND) {
11234 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11235 return checkImpl(FD);
11236 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11237 return checkImpl(RD);
11238 if (auto *VD = dyn_cast<VarDecl>(ND))
11239 return checkImpl(VD);
11240 if (auto *ED = dyn_cast<EnumDecl>(ND))
11241 return checkImpl(ED);
11242 }
11243
11244private:
11245 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11246 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11247 : Sema::MissingImportKind::ExplicitSpecialization;
11248 const bool Recover = true;
11249
11250 // If we got a custom set of modules (because only a subset of the
11251 // declarations are interesting), use them, otherwise let
11252 // diagnoseMissingImport intelligently pick some.
11253 if (Modules.empty())
11254 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11255 else
11256 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11257 }
11258
11259 bool CheckMemberSpecialization(const NamedDecl *D) {
11260 return Kind == Sema::AcceptableKind::Visible
11263 }
11264
11265 bool CheckExplicitSpecialization(const NamedDecl *D) {
11266 return Kind == Sema::AcceptableKind::Visible
11269 }
11270
11271 bool CheckDeclaration(const NamedDecl *D) {
11272 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11274 }
11275
11276 // Check a specific declaration. There are three problematic cases:
11277 //
11278 // 1) The declaration is an explicit specialization of a template
11279 // specialization.
11280 // 2) The declaration is an explicit specialization of a member of an
11281 // templated class.
11282 // 3) The declaration is an instantiation of a template, and that template
11283 // is an explicit specialization of a member of a templated class.
11284 //
11285 // We don't need to go any deeper than that, as the instantiation of the
11286 // surrounding class / etc is not triggered by whatever triggered this
11287 // instantiation, and thus should be checked elsewhere.
11288 template<typename SpecDecl>
11289 void checkImpl(SpecDecl *Spec) {
11290 bool IsHiddenExplicitSpecialization = false;
11291 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11292 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11293 ? !CheckMemberSpecialization(Spec)
11294 : !CheckExplicitSpecialization(Spec);
11295 } else {
11296 checkInstantiated(Spec);
11297 }
11298
11299 if (IsHiddenExplicitSpecialization)
11300 diagnose(Spec->getMostRecentDecl(), false);
11301 }
11302
11303 void checkInstantiated(FunctionDecl *FD) {
11304 if (auto *TD = FD->getPrimaryTemplate())
11305 checkTemplate(TD);
11306 }
11307
11308 void checkInstantiated(CXXRecordDecl *RD) {
11309 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11310 if (!SD)
11311 return;
11312
11313 auto From = SD->getSpecializedTemplateOrPartial();
11314 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11315 checkTemplate(TD);
11316 else if (auto *TD =
11317 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11318 if (!CheckDeclaration(TD))
11319 diagnose(TD, true);
11320 checkTemplate(TD);
11321 }
11322 }
11323
11324 void checkInstantiated(VarDecl *RD) {
11325 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11326 if (!SD)
11327 return;
11328
11329 auto From = SD->getSpecializedTemplateOrPartial();
11330 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11331 checkTemplate(TD);
11332 else if (auto *TD =
11333 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11334 if (!CheckDeclaration(TD))
11335 diagnose(TD, true);
11336 checkTemplate(TD);
11337 }
11338 }
11339
11340 void checkInstantiated(EnumDecl *FD) {}
11341
11342 template<typename TemplDecl>
11343 void checkTemplate(TemplDecl *TD) {
11344 if (TD->isMemberSpecialization()) {
11345 if (!CheckMemberSpecialization(TD))
11346 diagnose(TD->getMostRecentDecl(), false);
11347 }
11348 }
11349};
11350} // end anonymous namespace
11351
11353 if (!getLangOpts().Modules)
11354 return;
11355
11356 ExplicitSpecializationVisibilityChecker(*this, Loc,
11358 .check(Spec);
11359}
11360
11362 NamedDecl *Spec) {
11363 if (!getLangOpts().CPlusPlusModules)
11364 return checkSpecializationVisibility(Loc, Spec);
11365
11366 ExplicitSpecializationVisibilityChecker(*this, Loc,
11368 .check(Spec);
11369}
11370
11373 return N->getLocation();
11374 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11376 return FD->getLocation();
11379 return N->getLocation();
11380 }
11381 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11382 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11383 continue;
11384 return CSC.PointOfInstantiation;
11385 }
11386 return N->getLocation();
11387}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
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:31
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.
uint32_t Id
Definition: SemaARM.cpp:1134
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6822
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static 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 SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static 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 QualType builtinCommonTypeImpl(Sema &S, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
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 bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static 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 bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
static const TemplateArgument & getArgument(const TemplateArgument &A)
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:973
APSInt & getInt()
Definition: APValue.h:465
APSInt & getComplexIntImag()
Definition: APValue.h:503
ValueKind getKind() const
Definition: APValue.h:437
APFixedPoint & getFixedPoint()
Definition: APValue.h:487
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1056
APValue & getVectorElt(unsigned I)
Definition: APValue.h:539
unsigned getVectorLength() const
Definition: APValue.h:547
bool isLValue() const
Definition: APValue.h:448
bool isMemberPointer() const
Definition: APValue.h:453
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
@ 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:1009
APSInt & getComplexIntReal()
Definition: APValue.h:495
APFloat & getComplexFloatImag()
Definition: APValue.h:519
APFloat & getComplexFloatReal()
Definition: APValue.h:511
APFloat & getFloat()
Definition: APValue.h:479
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:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
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:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1187
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:1703
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
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
CanQualType BoolTy
Definition: ASTContext.h:1161
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1188
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:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1188
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
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:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
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...
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1101
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
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition: Attr.h:43
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2220
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2238
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2288
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2262
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2281
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2256
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2268
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6556
bool isDecltypeAuto() const
Definition: Type.h:6579
A fixed int type of a specified bitwidth.
Definition: Type.h:7814
Pointer to a block type.
Definition: Type.h:3408
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:3034
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:2113
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3683
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:1533
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:541
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:1970
base_class_range bases()
Definition: DeclCXX.h:620
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
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:1999
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1995
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1977
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:2010
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:532
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
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...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
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)
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
bool isTypeConcept() const
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:87
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:3615
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:4232
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:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isFileContext() const
Definition: DeclBase.h:2160
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2045
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1368
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
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:2027
bool isNamespace() const
Definition: DeclBase.h:2178
bool isTranslationUnit() const
Definition: DeclBase.h:2165
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1285
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1385
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1389
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1404
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1360
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1050
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
T * getAttr() const
Definition: DeclBase.h:576
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:239
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:281
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:805
void dropAttrs()
Definition: DeclBase.cpp:1003
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1051
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:1169
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2766
bool isInvalidDecl() const
Definition: DeclBase.h:591
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:229
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
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:907
bool hasAttr() const
Definition: DeclBase.h:580
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:359
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
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.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
Represents the type decltype(expr) (C++11).
Definition: Type.h:5874
Represents a C++17 deduced template specialization type.
Definition: Type.h:6604
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6522
bool isDeduced() const
Definition: Type.h:6544
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7024
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3323
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:531
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3862
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4291
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:548
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:607
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:604
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:610
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2503
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2523
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2491
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2547
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2539
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2555
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2531
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7076
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4086
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTypeLoc(TypeLoc TL)
Recursively visit a type with location, by dispatching to Traverse*TypeLoc() based on the argument ty...
virtual bool TraverseStmt(Stmt *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
bool isEmpty() const
Definition: TypeLoc.h:2396
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2392
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3847
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4106
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4961
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
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:3095
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:3090
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:822
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:3070
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:3963
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:4126
Represents a member of a struct/union/class.
Definition: Decl.h:3033
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:995
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1074
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1935
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4370
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4031
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
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:4236
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2297
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4276
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3133
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4681
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
ArrayRef< QualType > param_types() const
Definition: Type.h:5511
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:472
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:547
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:558
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:530
QualType getReturnType() const
Definition: Type.h:4643
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:3724
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3764
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5088
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:7579
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:6793
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:973
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Represents a linkage specification.
Definition: DeclCXX.h:2952
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.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
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:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition: Lookup.h:318
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4307
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:642
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:660
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:240
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
NamedDecl * getMostRecentDecl()
Definition: Decl.h:480
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:699
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
Represent a C++ namespace.
Definition: Decl.h:551
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.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
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.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
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.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
Represents a pointer to an Objective C object.
Definition: Type.h:7580
Represents a class type in Objective C.
Definition: Type.h:7326
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:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1209
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:116
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:7141
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
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:7780
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:929
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8020
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
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:8134
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
void * getAsOpaquePtr() const
Definition: Type.h:976
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition: Type.cpp:3514
bool isCanonical() const
Definition: Type.h:7988
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7977
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
The collection of all-type qualifiers we support.
Definition: Type.h:324
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
void addConst()
Definition: Type.h:453
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:541
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4148
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4339
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:6072
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:859
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:864
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4981
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
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:263
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1060
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13212
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
Whether and why a template name is required in this lookup.
Definition: Sema.h:11090
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11098
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7229
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9207
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6394
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13146
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2388
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1559
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15498
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8986
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8993
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19647
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:36
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
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:6090
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...
TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, bool Typename, 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:9300
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6075
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...
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition: Sema.h:1071
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 * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6218
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:17145
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 ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1665
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11061
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11635
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11638
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11642
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:909
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5782
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
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:1497
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition: Sema.h:532
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Definition: SemaDecl.cpp:1713
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool IsDeduced)
Check a template argument against its corresponding template template parameter.
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9435
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
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:16951
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2204
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:11051
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:11781
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:11799
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:11810
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11789
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11820
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:11111
@ 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)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition: Sema.h:11044
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:527
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
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:13957
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13945
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13954
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:13948
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13972
const LangOptions & getLangOpts() const
Definition: Sema.h:525
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1388
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:908
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, std::optional< unsigned > NumExpansions)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
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:14387
const LangOptions & LangOpts
Definition: Sema.h:907
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:20059
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:8978
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:9531
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8119
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:16926
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1324
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:9783
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:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
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:1044
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14949
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5787
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9765
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1289
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4707
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:9190
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3842
@ NTK_TypeAliasTemplate
Definition: Sema.h:3850
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
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,...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
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:216
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:14957
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:9384
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10001
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:3083
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:1893
ASTConsumer & Consumer
Definition: Sema.h:910
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8403
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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:9653
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:5703
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:17135
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:9068
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
@ TemplateNameIsRequired
Definition: Sema.h:11088
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:516
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:14984
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:11277
@ TPC_ClassTemplate
Definition: Sema.h:11278
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11283
@ TPC_ClassTemplateMember
Definition: Sema.h:11281
@ TPC_FunctionTemplate
Definition: Sema.h:11280
@ TPC_FriendClassTemplate
Definition: Sema.h:11282
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11284
@ TPC_TypeAliasTemplate
Definition: Sema.h:11285
@ TPC_VarTemplate
Definition: Sema.h:11279
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:1579
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
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:1564
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
@ OOK_Outside
Definition: Sema.h:3868
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5809
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21161
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation Loc, bool IsDeduced)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1703
@ 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.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2750
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:3003
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:11053
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.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:9309
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12487
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6036
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:317
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
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:357
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:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6464
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6383
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
StringRef getKindName() const
Definition: Decl.h:3755
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4760
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4843
TagKind getTagKind() const
Definition: Decl.h:3759
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4126
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:1262
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1300
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:250
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:289
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:286
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...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
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:399
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:431
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isNull() const
Determine whether this template name is NULL.
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:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
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:132
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
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:205
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:1718
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1694
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1726
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1735
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1702
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1710
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6727
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4332
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, bool Typename, 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.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, 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 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)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
unsigned getIndex() const
Definition: Type.h:6343
unsigned getDepth() const
Definition: Type.h:6342
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:3535
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
Represents a declaration of a type.
Definition: Decl.h:3370
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3398
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
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:749
bool isNull() const
Definition: TypeLoc.h:121
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:5797
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5847
A container of type source information.
Definition: Type.h:7902
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:7913
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
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:3196
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3178
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBooleanType() const
Definition: Type.h:8638
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2251
bool isRValueReferenceType() const
Definition: Type.h:8212
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8258
bool isPointerType() const
Definition: Type.h:8186
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isScalarType() const
Definition: Type.h:8609
bool isChar8Type() const
Definition: Type.cpp:2139
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
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:460
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8336
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isBitIntType() const
Definition: Type.h:8424
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8282
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:3002
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isChar16Type() const
Definition: Type.cpp:2145
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
bool isMemberPointerType() const
Definition: Type.h:8240
bool isChar32Type() const
Definition: Type.cpp:2151
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4653
bool isPointerOrReferenceType() const
Definition: Type.h:8190
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isVectorType() const
Definition: Type.h:8298
bool isWideCharType() const
Definition: Type.cpp:2132
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
QualType getUnderlyingType() const
Definition: Decl.h:3468
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:2232
A unary type transform, which is a type constructed from another.
Definition: Type.h:5989
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
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:5667
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3880
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3338
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3402
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
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:2883
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:2776
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:2755
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
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...
VarTemplateDecl * getMostRecentDecl()
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Represents a GCC generic vector type.
Definition: Type.h:4034
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
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:1886
bool isa(CodeGen::Address addr)
Definition: Address.h:328
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:859
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ 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:248
@ SC_Extern
Definition: Specifiers.h:251
@ TSCS_unspecified
Definition: Specifiers.h:236
@ 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:50
TagUseKind
Definition: Sema.h:447
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6871
@ 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:313
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:316
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:310
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
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:1274
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:365
@ 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:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6846
@ 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:1589
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
#define false
Definition: stdbool.h:26
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.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
Definition: TemplateName.h:187
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:5187
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
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:12660
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12767
A stack object to be created when performing template instantiation.
Definition: Sema.h:12845
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12999
NamedDecl * Previous
Definition: Sema.h:352
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.