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() != 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 (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1535 Invalid = true;
1536
1537 if (Invalid)
1538 Param->setInvalidDecl();
1539
1540 if (Param->isParameterPack())
1541 if (auto *CSI = getEnclosingLambdaOrBlock())
1542 CSI->LocalPacks.push_back(Param);
1543
1544 if (ParamName) {
1545 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1546 ParamName);
1547
1548 // Add the template parameter into the current scope.
1549 S->AddDecl(Param);
1550 IdResolver.AddDecl(Param);
1551 }
1552
1553 // C++0x [temp.param]p9:
1554 // A default template-argument may be specified for any kind of
1555 // template-parameter that is not a template parameter pack.
1556 if (Default && IsParameterPack) {
1557 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1558 Default = nullptr;
1559 }
1560
1561 // Check the well-formedness of the default template argument, if provided.
1562 if (Default) {
1563 // Check for unexpanded parameter packs.
1565 return Param;
1566
1567 Param->setDefaultArgument(
1569 QualType(), SourceLocation()));
1570 }
1571
1572 return Param;
1573}
1574
1576 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1577 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1578 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1580 assert(S->isTemplateParamScope() &&
1581 "Template template parameter not in template parameter scope!");
1582
1583 // Construct the parameter object.
1584 bool IsParameterPack = EllipsisLoc.isValid();
1587 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1588 Name, Typename, Params);
1589 Param->setAccess(AS_public);
1590
1591 if (Param->isParameterPack())
1592 if (auto *LSI = getEnclosingLambdaOrBlock())
1593 LSI->LocalPacks.push_back(Param);
1594
1595 // If the template template parameter has a name, then link the identifier
1596 // into the scope and lookup mechanisms.
1597 if (Name) {
1598 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1599
1600 S->AddDecl(Param);
1601 IdResolver.AddDecl(Param);
1602 }
1603
1604 if (Params->size() == 0) {
1605 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1606 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1607 Param->setInvalidDecl();
1608 }
1609
1610 // C++0x [temp.param]p9:
1611 // A default template-argument may be specified for any kind of
1612 // template-parameter that is not a template parameter pack.
1613 if (IsParameterPack && !Default.isInvalid()) {
1614 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1616 }
1617
1618 if (!Default.isInvalid()) {
1619 // Check only that we have a template template argument. We don't want to
1620 // try to check well-formedness now, because our template template parameter
1621 // might have dependent types in its template parameters, which we wouldn't
1622 // be able to match now.
1623 //
1624 // If none of the template template parameter's template arguments mention
1625 // other template parameters, we could actually perform more checking here.
1626 // However, it isn't worth doing.
1628 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1629 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1630 << DefaultArg.getSourceRange();
1631 return Param;
1632 }
1633
1634 // Check for unexpanded parameter packs.
1636 DefaultArg.getArgument().getAsTemplate(),
1638 return Param;
1639
1640 Param->setDefaultArgument(Context, DefaultArg);
1641 }
1642
1643 return Param;
1644}
1645
1646namespace {
1647class ConstraintRefersToContainingTemplateChecker
1648 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1649 bool Result = false;
1650 const FunctionDecl *Friend = nullptr;
1651 unsigned TemplateDepth = 0;
1652
1653 // Check a record-decl that we've seen to see if it is a lexical parent of the
1654 // Friend, likely because it was referred to without its template arguments.
1655 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1656 CheckingRD = CheckingRD->getMostRecentDecl();
1657 if (!CheckingRD->isTemplated())
1658 return;
1659
1660 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1661 DC && !DC->isFileContext(); DC = DC->getParent())
1662 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1663 if (CheckingRD == RD->getMostRecentDecl())
1664 Result = true;
1665 }
1666
1667 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1668 if (D->getDepth() < TemplateDepth)
1669 Result = true;
1670
1671 // Necessary because the type of the NTTP might be what refers to the parent
1672 // constriant.
1673 TransformType(D->getType());
1674 }
1675
1676public:
1678
1679 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1680 const FunctionDecl *Friend,
1681 unsigned TemplateDepth)
1682 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1683 bool getResult() const { return Result; }
1684
1685 // This should be the only template parm type that we have to deal with.
1686 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1687 // FunctionParmPackExpr are all partially substituted, which cannot happen
1688 // with concepts at this point in translation.
1689 using inherited::TransformTemplateTypeParmType;
1690 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1691 TemplateTypeParmTypeLoc TL, bool) {
1692 if (TL.getDecl()->getDepth() < TemplateDepth)
1693 Result = true;
1694 return inherited::TransformTemplateTypeParmType(
1695 TLB, TL,
1696 /*SuppressObjCLifetime=*/false);
1697 }
1698
1699 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1700 if (!D)
1701 return D;
1702 // FIXME : This is possibly an incomplete list, but it is unclear what other
1703 // Decl kinds could be used to refer to the template parameters. This is a
1704 // best guess so far based on examples currently available, but the
1705 // unreachable should catch future instances/cases.
1706 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1707 TransformType(TD->getUnderlyingType());
1708 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1709 CheckNonTypeTemplateParmDecl(NTTPD);
1710 else if (auto *VD = dyn_cast<ValueDecl>(D))
1711 TransformType(VD->getType());
1712 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1713 TransformTemplateParameterList(TD->getTemplateParameters());
1714 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1715 CheckIfContainingRecord(RD);
1716 else if (isa<NamedDecl>(D)) {
1717 // No direct types to visit here I believe.
1718 } else
1719 llvm_unreachable("Don't know how to handle this declaration type yet");
1720 return D;
1721 }
1722};
1723} // namespace
1724
1726 const FunctionDecl *Friend, unsigned TemplateDepth,
1727 const Expr *Constraint) {
1728 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1729 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1730 TemplateDepth);
1731 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1732 return Checker.getResult();
1733}
1734
1737 SourceLocation ExportLoc,
1738 SourceLocation TemplateLoc,
1739 SourceLocation LAngleLoc,
1740 ArrayRef<NamedDecl *> Params,
1741 SourceLocation RAngleLoc,
1742 Expr *RequiresClause) {
1743 if (ExportLoc.isValid())
1744 Diag(ExportLoc, diag::warn_template_export_unsupported);
1745
1746 for (NamedDecl *P : Params)
1748
1750 Context, TemplateLoc, LAngleLoc,
1751 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1752}
1753
1755 const CXXScopeSpec &SS) {
1756 if (SS.isSet())
1757 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1758}
1759
1760// Returns the template parameter list with all default template argument
1761// information.
1763 // Make sure we get the template parameter list from the most
1764 // recent declaration, since that is the only one that is guaranteed to
1765 // have all the default template argument information.
1766 Decl *D = TD->getMostRecentDecl();
1767 // C++11 N3337 [temp.param]p12:
1768 // A default template argument shall not be specified in a friend class
1769 // template declaration.
1770 //
1771 // Skip past friend *declarations* because they are not supposed to contain
1772 // default template arguments. Moreover, these declarations may introduce
1773 // template parameters living in different template depths than the
1774 // corresponding template parameters in TD, causing unmatched constraint
1775 // substitution.
1776 //
1777 // FIXME: Diagnose such cases within a class template:
1778 // template <class T>
1779 // struct S {
1780 // template <class = void> friend struct C;
1781 // };
1782 // template struct S<int>;
1784 D->getPreviousDecl())
1785 D = D->getPreviousDecl();
1786 return cast<TemplateDecl>(D)->getTemplateParameters();
1787}
1788
1790 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1791 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1792 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1793 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1794 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1795 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1796 assert(TemplateParams && TemplateParams->size() > 0 &&
1797 "No template parameters");
1798 assert(TUK != TagUseKind::Reference &&
1799 "Can only declare or define class templates");
1800 bool Invalid = false;
1801
1802 // Check that we can declare a template here.
1803 if (CheckTemplateDeclScope(S, TemplateParams))
1804 return true;
1805
1807 assert(Kind != TagTypeKind::Enum &&
1808 "can't build template of enumerated type");
1809
1810 // There is no such thing as an unnamed class template.
1811 if (!Name) {
1812 Diag(KWLoc, diag::err_template_unnamed_class);
1813 return true;
1814 }
1815
1816 // Find any previous declaration with this name. For a friend with no
1817 // scope explicitly specified, we only look for tag declarations (per
1818 // C++11 [basic.lookup.elab]p2).
1819 DeclContext *SemanticContext;
1820 LookupResult Previous(*this, Name, NameLoc,
1821 (SS.isEmpty() && TUK == TagUseKind::Friend)
1825 if (SS.isNotEmpty() && !SS.isInvalid()) {
1826 SemanticContext = computeDeclContext(SS, true);
1827 if (!SemanticContext) {
1828 // FIXME: Horrible, horrible hack! We can't currently represent this
1829 // in the AST, and historically we have just ignored such friend
1830 // class templates, so don't complain here.
1831 Diag(NameLoc, TUK == TagUseKind::Friend
1832 ? diag::warn_template_qualified_friend_ignored
1833 : diag::err_template_qualified_declarator_no_match)
1834 << SS.getScopeRep() << SS.getRange();
1835 return TUK != TagUseKind::Friend;
1836 }
1837
1838 if (RequireCompleteDeclContext(SS, SemanticContext))
1839 return true;
1840
1841 // If we're adding a template to a dependent context, we may need to
1842 // rebuilding some of the types used within the template parameter list,
1843 // now that we know what the current instantiation is.
1844 if (SemanticContext->isDependentContext()) {
1845 ContextRAII SavedContext(*this, SemanticContext);
1847 Invalid = true;
1848 }
1849
1850 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1851 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1852 /*TemplateId-*/ nullptr,
1853 /*IsMemberSpecialization*/ false);
1854
1855 LookupQualifiedName(Previous, SemanticContext);
1856 } else {
1857 SemanticContext = CurContext;
1858
1859 // C++14 [class.mem]p14:
1860 // If T is the name of a class, then each of the following shall have a
1861 // name different from T:
1862 // -- every member template of class T
1863 if (TUK != TagUseKind::Friend &&
1864 DiagnoseClassNameShadow(SemanticContext,
1865 DeclarationNameInfo(Name, NameLoc)))
1866 return true;
1867
1868 LookupName(Previous, S);
1869 }
1870
1871 if (Previous.isAmbiguous())
1872 return true;
1873
1874 // Let the template parameter scope enter the lookup chain of the current
1875 // class template. For example, given
1876 //
1877 // namespace ns {
1878 // template <class> bool Param = false;
1879 // template <class T> struct N;
1880 // }
1881 //
1882 // template <class Param> struct ns::N { void foo(Param); };
1883 //
1884 // When we reference Param inside the function parameter list, our name lookup
1885 // chain for it should be like:
1886 // FunctionScope foo
1887 // -> RecordScope N
1888 // -> TemplateParamScope (where we will find Param)
1889 // -> NamespaceScope ns
1890 //
1891 // See also CppLookupName().
1892 if (S->isTemplateParamScope())
1893 EnterTemplatedContext(S, SemanticContext);
1894
1895 NamedDecl *PrevDecl = nullptr;
1896 if (Previous.begin() != Previous.end())
1897 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1898
1899 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1900 // Maybe we will complain about the shadowed template parameter.
1901 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1902 // Just pretend that we didn't see the previous declaration.
1903 PrevDecl = nullptr;
1904 }
1905
1906 // If there is a previous declaration with the same name, check
1907 // whether this is a valid redeclaration.
1908 ClassTemplateDecl *PrevClassTemplate =
1909 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1910
1911 // We may have found the injected-class-name of a class template,
1912 // class template partial specialization, or class template specialization.
1913 // In these cases, grab the template that is being defined or specialized.
1914 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1917 PrevClassTemplate
1918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1920 PrevClassTemplate
1921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1922 ->getSpecializedTemplate();
1923 }
1924 }
1925
1926 if (TUK == TagUseKind::Friend) {
1927 // C++ [namespace.memdef]p3:
1928 // [...] When looking for a prior declaration of a class or a function
1929 // declared as a friend, and when the name of the friend class or
1930 // function is neither a qualified name nor a template-id, scopes outside
1931 // the innermost enclosing namespace scope are not considered.
1932 if (!SS.isSet()) {
1933 DeclContext *OutermostContext = CurContext;
1934 while (!OutermostContext->isFileContext())
1935 OutermostContext = OutermostContext->getLookupParent();
1936
1937 if (PrevDecl &&
1938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1940 SemanticContext = PrevDecl->getDeclContext();
1941 } else {
1942 // Declarations in outer scopes don't matter. However, the outermost
1943 // context we computed is the semantic context for our new
1944 // declaration.
1945 PrevDecl = PrevClassTemplate = nullptr;
1946 SemanticContext = OutermostContext;
1947
1948 // Check that the chosen semantic context doesn't already contain a
1949 // declaration of this name as a non-tag type.
1951 DeclContext *LookupContext = SemanticContext;
1952 while (LookupContext->isTransparentContext())
1953 LookupContext = LookupContext->getLookupParent();
1954 LookupQualifiedName(Previous, LookupContext);
1955
1956 if (Previous.isAmbiguous())
1957 return true;
1958
1959 if (Previous.begin() != Previous.end())
1960 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1961 }
1962 }
1963 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1964 SemanticContext, S, SS.isValid()))
1965 PrevDecl = PrevClassTemplate = nullptr;
1966
1967 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1968 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1969 if (SS.isEmpty() &&
1970 !(PrevClassTemplate &&
1971 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1972 SemanticContext->getRedeclContext()))) {
1973 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1974 Diag(Shadow->getTargetDecl()->getLocation(),
1975 diag::note_using_decl_target);
1976 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1977 // Recover by ignoring the old declaration.
1978 PrevDecl = PrevClassTemplate = nullptr;
1979 }
1980 }
1981
1982 if (PrevClassTemplate) {
1983 // Ensure that the template parameter lists are compatible. Skip this check
1984 // for a friend in a dependent context: the template parameter list itself
1985 // could be dependent.
1986 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1988 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1989 : CurContext,
1990 CurContext, KWLoc),
1991 TemplateParams, PrevClassTemplate,
1992 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1994 return true;
1995
1996 // C++ [temp.class]p4:
1997 // In a redeclaration, partial specialization, explicit
1998 // specialization or explicit instantiation of a class template,
1999 // the class-key shall agree in kind with the original class
2000 // template declaration (7.1.5.3).
2001 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2003 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2004 Diag(KWLoc, diag::err_use_with_wrong_tag)
2005 << Name
2006 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2007 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2008 Kind = PrevRecordDecl->getTagKind();
2009 }
2010
2011 // Check for redefinition of this class template.
2012 if (TUK == TagUseKind::Definition) {
2013 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2014 // If we have a prior definition that is not visible, treat this as
2015 // simply making that previous definition visible.
2016 NamedDecl *Hidden = nullptr;
2017 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2018 SkipBody->ShouldSkip = true;
2019 SkipBody->Previous = Def;
2020 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2021 assert(Tmpl && "original definition of a class template is not a "
2022 "class template?");
2025 } else {
2026 Diag(NameLoc, diag::err_redefinition) << Name;
2027 Diag(Def->getLocation(), diag::note_previous_definition);
2028 // FIXME: Would it make sense to try to "forget" the previous
2029 // definition, as part of error recovery?
2030 return true;
2031 }
2032 }
2033 }
2034 } else if (PrevDecl) {
2035 // C++ [temp]p5:
2036 // A class template shall not have the same name as any other
2037 // template, class, function, object, enumeration, enumerator,
2038 // namespace, or type in the same scope (3.3), except as specified
2039 // in (14.5.4).
2040 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2041 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2042 return true;
2043 }
2044
2045 // Check the template parameter list of this declaration, possibly
2046 // merging in the template parameter list from the previous class
2047 // template declaration. Skip this check for a friend in a dependent
2048 // context, because the template parameter list might be dependent.
2049 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2051 TemplateParams,
2052 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2053 : nullptr,
2054 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2055 SemanticContext->isDependentContext())
2059 SkipBody))
2060 Invalid = true;
2061
2062 if (SS.isSet()) {
2063 // If the name of the template was qualified, we must be defining the
2064 // template out-of-line.
2065 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2066 Diag(NameLoc, TUK == TagUseKind::Friend
2067 ? diag::err_friend_decl_does_not_match
2068 : diag::err_member_decl_does_not_match)
2069 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2070 Invalid = true;
2071 }
2072 }
2073
2074 // If this is a templated friend in a dependent context we should not put it
2075 // on the redecl chain. In some cases, the templated friend can be the most
2076 // recent declaration tricking the template instantiator to make substitutions
2077 // there.
2078 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2079 bool ShouldAddRedecl =
2081
2082 CXXRecordDecl *NewClass =
2083 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2084 PrevClassTemplate && ShouldAddRedecl ?
2085 PrevClassTemplate->getTemplatedDecl() : nullptr,
2086 /*DelayTypeCreation=*/true);
2087 SetNestedNameSpecifier(*this, NewClass, SS);
2088 if (NumOuterTemplateParamLists > 0)
2090 Context,
2091 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2092
2093 // Add alignment attributes if necessary; these attributes are checked when
2094 // the ASTContext lays out the structure.
2095 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2098 }
2099
2100 ClassTemplateDecl *NewTemplate
2101 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2102 DeclarationName(Name), TemplateParams,
2103 NewClass);
2104
2105 if (ShouldAddRedecl)
2106 NewTemplate->setPreviousDecl(PrevClassTemplate);
2107
2108 NewClass->setDescribedClassTemplate(NewTemplate);
2109
2110 if (ModulePrivateLoc.isValid())
2111 NewTemplate->setModulePrivate();
2112
2113 // Build the type for the class template declaration now.
2115 T = Context.getInjectedClassNameType(NewClass, T);
2116 assert(T->isDependentType() && "Class template type is not dependent?");
2117 (void)T;
2118
2119 // If we are providing an explicit specialization of a member that is a
2120 // class template, make a note of that.
2121 if (PrevClassTemplate &&
2122 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2123 PrevClassTemplate->setMemberSpecialization();
2124
2125 // Set the access specifier.
2126 if (!Invalid && TUK != TagUseKind::Friend &&
2127 NewTemplate->getDeclContext()->isRecord())
2128 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2129
2130 // Set the lexical context of these templates
2132 NewTemplate->setLexicalDeclContext(CurContext);
2133
2134 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2135 NewClass->startDefinition();
2136
2137 ProcessDeclAttributeList(S, NewClass, Attr);
2138 ProcessAPINotes(NewClass);
2139
2140 if (PrevClassTemplate)
2141 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2142
2146
2147 if (TUK != TagUseKind::Friend) {
2148 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2149 Scope *Outer = S;
2150 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2151 Outer = Outer->getParent();
2152 PushOnScopeChains(NewTemplate, Outer);
2153 } else {
2154 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2155 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2156 NewClass->setAccess(PrevClassTemplate->getAccess());
2157 }
2158
2159 NewTemplate->setObjectOfFriendDecl();
2160
2161 // Friend templates are visible in fairly strange ways.
2163 DeclContext *DC = SemanticContext->getRedeclContext();
2164 DC->makeDeclVisibleInContext(NewTemplate);
2165 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2166 PushOnScopeChains(NewTemplate, EnclosingScope,
2167 /* AddToContext = */ false);
2168 }
2169
2171 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2172 Friend->setAccess(AS_public);
2174 }
2175
2176 if (PrevClassTemplate)
2177 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2178
2179 if (Invalid) {
2180 NewTemplate->setInvalidDecl();
2181 NewClass->setInvalidDecl();
2182 }
2183
2184 ActOnDocumentableDecl(NewTemplate);
2185
2186 if (SkipBody && SkipBody->ShouldSkip)
2187 return SkipBody->Previous;
2188
2189 return NewTemplate;
2190}
2191
2192/// Diagnose the presence of a default template argument on a
2193/// template parameter, which is ill-formed in certain contexts.
2194///
2195/// \returns true if the default template argument should be dropped.
2198 SourceLocation ParamLoc,
2199 SourceRange DefArgRange) {
2200 switch (TPC) {
2204 return false;
2205
2208 // C++ [temp.param]p9:
2209 // A default template-argument shall not be specified in a
2210 // function template declaration or a function template
2211 // definition [...]
2212 // If a friend function template declaration specifies a default
2213 // template-argument, that declaration shall be a definition and shall be
2214 // the only declaration of the function template in the translation unit.
2215 // (C++98/03 doesn't have this wording; see DR226).
2216 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2217 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2218 : diag::ext_template_parameter_default_in_function_template)
2219 << DefArgRange;
2220 return false;
2221
2223 // C++0x [temp.param]p9:
2224 // A default template-argument shall not be specified in the
2225 // template-parameter-lists of the definition of a member of a
2226 // class template that appears outside of the member's class.
2227 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2228 << DefArgRange;
2229 return true;
2230
2233 // C++ [temp.param]p9:
2234 // A default template-argument shall not be specified in a
2235 // friend template declaration.
2236 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2237 << DefArgRange;
2238 return true;
2239
2240 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2241 // for friend function templates if there is only a single
2242 // declaration (and it is a definition). Strange!
2243 }
2244
2245 llvm_unreachable("Invalid TemplateParamListContext!");
2246}
2247
2248/// Check for unexpanded parameter packs within the template parameters
2249/// of a template template parameter, recursively.
2252 // A template template parameter which is a parameter pack is also a pack
2253 // expansion.
2254 if (TTP->isParameterPack())
2255 return false;
2256
2258 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2259 NamedDecl *P = Params->getParam(I);
2260 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2261 if (!TTP->isParameterPack())
2262 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2263 if (TC->hasExplicitTemplateArgs())
2264 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2267 return true;
2268 continue;
2269 }
2270
2271 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2272 if (!NTTP->isParameterPack() &&
2273 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2274 NTTP->getTypeSourceInfo(),
2276 return true;
2277
2278 continue;
2279 }
2280
2281 if (TemplateTemplateParmDecl *InnerTTP
2282 = dyn_cast<TemplateTemplateParmDecl>(P))
2283 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2284 return true;
2285 }
2286
2287 return false;
2288}
2289
2291 TemplateParameterList *OldParams,
2293 SkipBodyInfo *SkipBody) {
2294 bool Invalid = false;
2295
2296 // C++ [temp.param]p10:
2297 // The set of default template-arguments available for use with a
2298 // template declaration or definition is obtained by merging the
2299 // default arguments from the definition (if in scope) and all
2300 // declarations in scope in the same way default function
2301 // arguments are (8.3.6).
2302 bool SawDefaultArgument = false;
2303 SourceLocation PreviousDefaultArgLoc;
2304
2305 // Dummy initialization to avoid warnings.
2306 TemplateParameterList::iterator OldParam = NewParams->end();
2307 if (OldParams)
2308 OldParam = OldParams->begin();
2309
2310 bool RemoveDefaultArguments = false;
2311 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2312 NewParamEnd = NewParams->end();
2313 NewParam != NewParamEnd; ++NewParam) {
2314 // Whether we've seen a duplicate default argument in the same translation
2315 // unit.
2316 bool RedundantDefaultArg = false;
2317 // Whether we've found inconsis inconsitent default arguments in different
2318 // translation unit.
2319 bool InconsistentDefaultArg = false;
2320 // The name of the module which contains the inconsistent default argument.
2321 std::string PrevModuleName;
2322
2323 SourceLocation OldDefaultLoc;
2324 SourceLocation NewDefaultLoc;
2325
2326 // Variable used to diagnose missing default arguments
2327 bool MissingDefaultArg = false;
2328
2329 // Variable used to diagnose non-final parameter packs
2330 bool SawParameterPack = false;
2331
2332 if (TemplateTypeParmDecl *NewTypeParm
2333 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2334 // Check the presence of a default argument here.
2335 if (NewTypeParm->hasDefaultArgument() &&
2337 *this, TPC, NewTypeParm->getLocation(),
2338 NewTypeParm->getDefaultArgument().getSourceRange()))
2339 NewTypeParm->removeDefaultArgument();
2340
2341 // Merge default arguments for template type parameters.
2342 TemplateTypeParmDecl *OldTypeParm
2343 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2344 if (NewTypeParm->isParameterPack()) {
2345 assert(!NewTypeParm->hasDefaultArgument() &&
2346 "Parameter packs can't have a default argument!");
2347 SawParameterPack = true;
2348 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2349 NewTypeParm->hasDefaultArgument() &&
2350 (!SkipBody || !SkipBody->ShouldSkip)) {
2351 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2352 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2353 SawDefaultArgument = true;
2354
2355 if (!OldTypeParm->getOwningModule())
2356 RedundantDefaultArg = true;
2357 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2358 NewTypeParm)) {
2359 InconsistentDefaultArg = true;
2360 PrevModuleName =
2362 }
2363 PreviousDefaultArgLoc = NewDefaultLoc;
2364 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2365 // Merge the default argument from the old declaration to the
2366 // new declaration.
2367 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2368 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2369 } else if (NewTypeParm->hasDefaultArgument()) {
2370 SawDefaultArgument = true;
2371 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2372 } else if (SawDefaultArgument)
2373 MissingDefaultArg = true;
2374 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2375 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2376 // Check for unexpanded parameter packs.
2377 if (!NewNonTypeParm->isParameterPack() &&
2378 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2379 NewNonTypeParm->getTypeSourceInfo(),
2381 Invalid = true;
2382 continue;
2383 }
2384
2385 // Check the presence of a default argument here.
2386 if (NewNonTypeParm->hasDefaultArgument() &&
2388 *this, TPC, NewNonTypeParm->getLocation(),
2389 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2390 NewNonTypeParm->removeDefaultArgument();
2391 }
2392
2393 // Merge default arguments for non-type template parameters
2394 NonTypeTemplateParmDecl *OldNonTypeParm
2395 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2396 if (NewNonTypeParm->isParameterPack()) {
2397 assert(!NewNonTypeParm->hasDefaultArgument() &&
2398 "Parameter packs can't have a default argument!");
2399 if (!NewNonTypeParm->isPackExpansion())
2400 SawParameterPack = true;
2401 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2402 NewNonTypeParm->hasDefaultArgument() &&
2403 (!SkipBody || !SkipBody->ShouldSkip)) {
2404 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2405 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2406 SawDefaultArgument = true;
2407 if (!OldNonTypeParm->getOwningModule())
2408 RedundantDefaultArg = true;
2409 else if (!getASTContext().isSameDefaultTemplateArgument(
2410 OldNonTypeParm, NewNonTypeParm)) {
2411 InconsistentDefaultArg = true;
2412 PrevModuleName =
2413 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2414 }
2415 PreviousDefaultArgLoc = NewDefaultLoc;
2416 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2417 // Merge the default argument from the old declaration to the
2418 // new declaration.
2419 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2420 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2421 } else if (NewNonTypeParm->hasDefaultArgument()) {
2422 SawDefaultArgument = true;
2423 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2424 } else if (SawDefaultArgument)
2425 MissingDefaultArg = true;
2426 } else {
2427 TemplateTemplateParmDecl *NewTemplateParm
2428 = cast<TemplateTemplateParmDecl>(*NewParam);
2429
2430 // Check for unexpanded parameter packs, recursively.
2431 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2432 Invalid = true;
2433 continue;
2434 }
2435
2436 // Check the presence of a default argument here.
2437 if (NewTemplateParm->hasDefaultArgument() &&
2439 NewTemplateParm->getLocation(),
2440 NewTemplateParm->getDefaultArgument().getSourceRange()))
2441 NewTemplateParm->removeDefaultArgument();
2442
2443 // Merge default arguments for template template parameters
2444 TemplateTemplateParmDecl *OldTemplateParm
2445 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2446 if (NewTemplateParm->isParameterPack()) {
2447 assert(!NewTemplateParm->hasDefaultArgument() &&
2448 "Parameter packs can't have a default argument!");
2449 if (!NewTemplateParm->isPackExpansion())
2450 SawParameterPack = true;
2451 } else if (OldTemplateParm &&
2452 hasVisibleDefaultArgument(OldTemplateParm) &&
2453 NewTemplateParm->hasDefaultArgument() &&
2454 (!SkipBody || !SkipBody->ShouldSkip)) {
2455 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2456 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2457 SawDefaultArgument = true;
2458 if (!OldTemplateParm->getOwningModule())
2459 RedundantDefaultArg = true;
2460 else if (!getASTContext().isSameDefaultTemplateArgument(
2461 OldTemplateParm, NewTemplateParm)) {
2462 InconsistentDefaultArg = true;
2463 PrevModuleName =
2464 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2465 }
2466 PreviousDefaultArgLoc = NewDefaultLoc;
2467 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2468 // Merge the default argument from the old declaration to the
2469 // new declaration.
2470 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2471 PreviousDefaultArgLoc
2472 = OldTemplateParm->getDefaultArgument().getLocation();
2473 } else if (NewTemplateParm->hasDefaultArgument()) {
2474 SawDefaultArgument = true;
2475 PreviousDefaultArgLoc
2476 = NewTemplateParm->getDefaultArgument().getLocation();
2477 } else if (SawDefaultArgument)
2478 MissingDefaultArg = true;
2479 }
2480
2481 // C++11 [temp.param]p11:
2482 // If a template parameter of a primary class template or alias template
2483 // is a template parameter pack, it shall be the last template parameter.
2484 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2485 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2486 TPC == TPC_TypeAliasTemplate)) {
2487 Diag((*NewParam)->getLocation(),
2488 diag::err_template_param_pack_must_be_last_template_parameter);
2489 Invalid = true;
2490 }
2491
2492 // [basic.def.odr]/13:
2493 // There can be more than one definition of a
2494 // ...
2495 // default template argument
2496 // ...
2497 // in a program provided that each definition appears in a different
2498 // translation unit and the definitions satisfy the [same-meaning
2499 // criteria of the ODR].
2500 //
2501 // Simply, the design of modules allows the definition of template default
2502 // argument to be repeated across translation unit. Note that the ODR is
2503 // checked elsewhere. But it is still not allowed to repeat template default
2504 // argument in the same translation unit.
2505 if (RedundantDefaultArg) {
2506 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2507 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2508 Invalid = true;
2509 } else if (InconsistentDefaultArg) {
2510 // We could only diagnose about the case that the OldParam is imported.
2511 // The case NewParam is imported should be handled in ASTReader.
2512 Diag(NewDefaultLoc,
2513 diag::err_template_param_default_arg_inconsistent_redefinition);
2514 Diag(OldDefaultLoc,
2515 diag::note_template_param_prev_default_arg_in_other_module)
2516 << PrevModuleName;
2517 Invalid = true;
2518 } else if (MissingDefaultArg &&
2519 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2520 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2521 // C++ 23[temp.param]p14:
2522 // If a template-parameter of a class template, variable template, or
2523 // alias template has a default template argument, each subsequent
2524 // template-parameter shall either have a default template argument
2525 // supplied or be a template parameter pack.
2526 Diag((*NewParam)->getLocation(),
2527 diag::err_template_param_default_arg_missing);
2528 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2529 Invalid = true;
2530 RemoveDefaultArguments = true;
2531 }
2532
2533 // If we have an old template parameter list that we're merging
2534 // in, move on to the next parameter.
2535 if (OldParams)
2536 ++OldParam;
2537 }
2538
2539 // We were missing some default arguments at the end of the list, so remove
2540 // all of the default arguments.
2541 if (RemoveDefaultArguments) {
2542 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2543 NewParamEnd = NewParams->end();
2544 NewParam != NewParamEnd; ++NewParam) {
2545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2546 TTP->removeDefaultArgument();
2547 else if (NonTypeTemplateParmDecl *NTTP
2548 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2549 NTTP->removeDefaultArgument();
2550 else
2551 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2552 }
2553 }
2554
2555 return Invalid;
2556}
2557
2558namespace {
2559
2560/// A class which looks for a use of a certain level of template
2561/// parameter.
2562struct DependencyChecker : DynamicRecursiveASTVisitor {
2563 unsigned Depth;
2564
2565 // Whether we're looking for a use of a template parameter that makes the
2566 // overall construct type-dependent / a dependent type. This is strictly
2567 // best-effort for now; we may fail to match at all for a dependent type
2568 // in some cases if this is set.
2569 bool IgnoreNonTypeDependent;
2570
2571 bool Match;
2572 SourceLocation MatchLoc;
2573
2574 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2575 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2576 Match(false) {}
2577
2578 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2579 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2580 NamedDecl *ND = Params->getParam(0);
2581 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2582 Depth = PD->getDepth();
2583 } else if (NonTypeTemplateParmDecl *PD =
2584 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2585 Depth = PD->getDepth();
2586 } else {
2587 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2588 }
2589 }
2590
2591 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2592 if (ParmDepth >= Depth) {
2593 Match = true;
2594 MatchLoc = Loc;
2595 return true;
2596 }
2597 return false;
2598 }
2599
2600 bool TraverseStmt(Stmt *S) override {
2601 // Prune out non-type-dependent expressions if requested. This can
2602 // sometimes result in us failing to find a template parameter reference
2603 // (if a value-dependent expression creates a dependent type), but this
2604 // mode is best-effort only.
2605 if (auto *E = dyn_cast_or_null<Expr>(S))
2606 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2607 return true;
2609 }
2610
2611 bool TraverseTypeLoc(TypeLoc TL) override {
2612 if (IgnoreNonTypeDependent && !TL.isNull() &&
2613 !TL.getType()->isDependentType())
2614 return true;
2616 }
2617
2618 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2619 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2620 }
2621
2622 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2623 // For a best-effort search, keep looking until we find a location.
2624 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2625 }
2626
2627 bool TraverseTemplateName(TemplateName N) override {
2628 if (TemplateTemplateParmDecl *PD =
2629 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2630 if (Matches(PD->getDepth()))
2631 return false;
2633 }
2634
2635 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2636 if (NonTypeTemplateParmDecl *PD =
2637 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2638 if (Matches(PD->getDepth(), E->getExprLoc()))
2639 return false;
2640 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2641 }
2642
2643 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2644 return TraverseType(T->getReplacementType());
2645 }
2646
2647 bool VisitSubstTemplateTypeParmPackType(
2648 SubstTemplateTypeParmPackType *T) override {
2649 return TraverseTemplateArgument(T->getArgumentPack());
2650 }
2651
2652 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2653 return TraverseType(T->getInjectedSpecializationType());
2654 }
2655};
2656} // end anonymous namespace
2657
2658/// Determines whether a given type depends on the given parameter
2659/// list.
2660static bool
2662 if (!Params->size())
2663 return false;
2664
2665 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2666 Checker.TraverseType(T);
2667 return Checker.Match;
2668}
2669
2670// Find the source range corresponding to the named type in the given
2671// nested-name-specifier, if any.
2673 QualType T,
2674 const CXXScopeSpec &SS) {
2676 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2677 if (const Type *CurType = NNS->getAsType()) {
2678 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2679 return NNSLoc.getTypeLoc().getSourceRange();
2680 } else
2681 break;
2682
2683 NNSLoc = NNSLoc.getPrefix();
2684 }
2685
2686 return SourceRange();
2687}
2688
2690 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2691 TemplateIdAnnotation *TemplateId,
2692 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2693 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2694 IsMemberSpecialization = false;
2695 Invalid = false;
2696
2697 // The sequence of nested types to which we will match up the template
2698 // parameter lists. We first build this list by starting with the type named
2699 // by the nested-name-specifier and walking out until we run out of types.
2700 SmallVector<QualType, 4> NestedTypes;
2701 QualType T;
2702 if (SS.getScopeRep()) {
2704 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2706 else
2707 T = QualType(SS.getScopeRep()->getAsType(), 0);
2708 }
2709
2710 // If we found an explicit specialization that prevents us from needing
2711 // 'template<>' headers, this will be set to the location of that
2712 // explicit specialization.
2713 SourceLocation ExplicitSpecLoc;
2714
2715 while (!T.isNull()) {
2716 NestedTypes.push_back(T);
2717
2718 // Retrieve the parent of a record type.
2720 // If this type is an explicit specialization, we're done.
2722 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2723 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2724 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2725 ExplicitSpecLoc = Spec->getLocation();
2726 break;
2727 }
2728 } else if (Record->getTemplateSpecializationKind()
2730 ExplicitSpecLoc = Record->getLocation();
2731 break;
2732 }
2733
2734 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2736 else
2737 T = QualType();
2738 continue;
2739 }
2740
2741 if (const TemplateSpecializationType *TST
2743 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2746 else
2747 T = QualType();
2748 continue;
2749 }
2750 }
2751
2752 // Look one step prior in a dependent template specialization type.
2753 if (const DependentTemplateSpecializationType *DependentTST
2755 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2756 T = QualType(NNS->getAsType(), 0);
2757 else
2758 T = QualType();
2759 continue;
2760 }
2761
2762 // Look one step prior in a dependent name type.
2763 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2764 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2765 T = QualType(NNS->getAsType(), 0);
2766 else
2767 T = QualType();
2768 continue;
2769 }
2770
2771 // Retrieve the parent of an enumeration type.
2772 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2773 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2774 // check here.
2775 EnumDecl *Enum = EnumT->getDecl();
2776
2777 // Get to the parent type.
2778 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2780 else
2781 T = QualType();
2782 continue;
2783 }
2784
2785 T = QualType();
2786 }
2787 // Reverse the nested types list, since we want to traverse from the outermost
2788 // to the innermost while checking template-parameter-lists.
2789 std::reverse(NestedTypes.begin(), NestedTypes.end());
2790
2791 // C++0x [temp.expl.spec]p17:
2792 // A member or a member template may be nested within many
2793 // enclosing class templates. In an explicit specialization for
2794 // such a member, the member declaration shall be preceded by a
2795 // template<> for each enclosing class template that is
2796 // explicitly specialized.
2797 bool SawNonEmptyTemplateParameterList = false;
2798
2799 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2800 if (SawNonEmptyTemplateParameterList) {
2801 if (!SuppressDiagnostic)
2802 Diag(DeclLoc, diag::err_specialize_member_of_template)
2803 << !Recovery << Range;
2804 Invalid = true;
2805 IsMemberSpecialization = false;
2806 return true;
2807 }
2808
2809 return false;
2810 };
2811
2812 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2813 // Check that we can have an explicit specialization here.
2814 if (CheckExplicitSpecialization(Range, true))
2815 return true;
2816
2817 // We don't have a template header, but we should.
2818 SourceLocation ExpectedTemplateLoc;
2819 if (!ParamLists.empty())
2820 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2821 else
2822 ExpectedTemplateLoc = DeclStartLoc;
2823
2824 if (!SuppressDiagnostic)
2825 Diag(DeclLoc, diag::err_template_spec_needs_header)
2826 << Range
2827 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2828 return false;
2829 };
2830
2831 unsigned ParamIdx = 0;
2832 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2833 ++TypeIdx) {
2834 T = NestedTypes[TypeIdx];
2835
2836 // Whether we expect a 'template<>' header.
2837 bool NeedEmptyTemplateHeader = false;
2838
2839 // Whether we expect a template header with parameters.
2840 bool NeedNonemptyTemplateHeader = false;
2841
2842 // For a dependent type, the set of template parameters that we
2843 // expect to see.
2844 TemplateParameterList *ExpectedTemplateParams = nullptr;
2845
2846 // C++0x [temp.expl.spec]p15:
2847 // A member or a member template may be nested within many enclosing
2848 // class templates. In an explicit specialization for such a member, the
2849 // member declaration shall be preceded by a template<> for each
2850 // enclosing class template that is explicitly specialized.
2853 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2854 ExpectedTemplateParams = Partial->getTemplateParameters();
2855 NeedNonemptyTemplateHeader = true;
2856 } else if (Record->isDependentType()) {
2857 if (Record->getDescribedClassTemplate()) {
2858 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2859 ->getTemplateParameters();
2860 NeedNonemptyTemplateHeader = true;
2861 }
2862 } else if (ClassTemplateSpecializationDecl *Spec
2863 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2864 // C++0x [temp.expl.spec]p4:
2865 // Members of an explicitly specialized class template are defined
2866 // in the same manner as members of normal classes, and not using
2867 // the template<> syntax.
2868 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2869 NeedEmptyTemplateHeader = true;
2870 else
2871 continue;
2872 } else if (Record->getTemplateSpecializationKind()) {
2873 if (Record->getTemplateSpecializationKind()
2875 TypeIdx == NumTypes - 1)
2876 IsMemberSpecialization = true;
2877
2878 continue;
2879 }
2880 } else if (const TemplateSpecializationType *TST
2882 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2883 ExpectedTemplateParams = Template->getTemplateParameters();
2884 NeedNonemptyTemplateHeader = true;
2885 }
2887 // FIXME: We actually could/should check the template arguments here
2888 // against the corresponding template parameter list.
2889 NeedNonemptyTemplateHeader = false;
2890 }
2891
2892 // C++ [temp.expl.spec]p16:
2893 // In an explicit specialization declaration for a member of a class
2894 // template or a member template that appears in namespace scope, the
2895 // member template and some of its enclosing class templates may remain
2896 // unspecialized, except that the declaration shall not explicitly
2897 // specialize a class member template if its enclosing class templates
2898 // are not explicitly specialized as well.
2899 if (ParamIdx < ParamLists.size()) {
2900 if (ParamLists[ParamIdx]->size() == 0) {
2901 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2902 false))
2903 return nullptr;
2904 } else
2905 SawNonEmptyTemplateParameterList = true;
2906 }
2907
2908 if (NeedEmptyTemplateHeader) {
2909 // If we're on the last of the types, and we need a 'template<>' header
2910 // here, then it's a member specialization.
2911 if (TypeIdx == NumTypes - 1)
2912 IsMemberSpecialization = true;
2913
2914 if (ParamIdx < ParamLists.size()) {
2915 if (ParamLists[ParamIdx]->size() > 0) {
2916 // The header has template parameters when it shouldn't. Complain.
2917 if (!SuppressDiagnostic)
2918 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2919 diag::err_template_param_list_matches_nontemplate)
2920 << T
2921 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2922 ParamLists[ParamIdx]->getRAngleLoc())
2924 Invalid = true;
2925 return nullptr;
2926 }
2927
2928 // Consume this template header.
2929 ++ParamIdx;
2930 continue;
2931 }
2932
2933 if (!IsFriend)
2934 if (DiagnoseMissingExplicitSpecialization(
2936 return nullptr;
2937
2938 continue;
2939 }
2940
2941 if (NeedNonemptyTemplateHeader) {
2942 // In friend declarations we can have template-ids which don't
2943 // depend on the corresponding template parameter lists. But
2944 // assume that empty parameter lists are supposed to match this
2945 // template-id.
2946 if (IsFriend && T->isDependentType()) {
2947 if (ParamIdx < ParamLists.size() &&
2949 ExpectedTemplateParams = nullptr;
2950 else
2951 continue;
2952 }
2953
2954 if (ParamIdx < ParamLists.size()) {
2955 // Check the template parameter list, if we can.
2956 if (ExpectedTemplateParams &&
2958 ExpectedTemplateParams,
2959 !SuppressDiagnostic, TPL_TemplateMatch))
2960 Invalid = true;
2961
2962 if (!Invalid &&
2963 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2965 Invalid = true;
2966
2967 ++ParamIdx;
2968 continue;
2969 }
2970
2971 if (!SuppressDiagnostic)
2972 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2973 << T
2975 Invalid = true;
2976 continue;
2977 }
2978 }
2979
2980 // If there were at least as many template-ids as there were template
2981 // parameter lists, then there are no template parameter lists remaining for
2982 // the declaration itself.
2983 if (ParamIdx >= ParamLists.size()) {
2984 if (TemplateId && !IsFriend) {
2985 // We don't have a template header for the declaration itself, but we
2986 // should.
2987 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2988 TemplateId->RAngleLoc));
2989
2990 // Fabricate an empty template parameter list for the invented header.
2992 SourceLocation(), {},
2993 SourceLocation(), nullptr);
2994 }
2995
2996 return nullptr;
2997 }
2998
2999 // If there were too many template parameter lists, complain about that now.
3000 if (ParamIdx < ParamLists.size() - 1) {
3001 bool HasAnyExplicitSpecHeader = false;
3002 bool AllExplicitSpecHeaders = true;
3003 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3004 if (ParamLists[I]->size() == 0)
3005 HasAnyExplicitSpecHeader = true;
3006 else
3007 AllExplicitSpecHeaders = false;
3008 }
3009
3010 if (!SuppressDiagnostic)
3011 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3012 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3013 : diag::err_template_spec_extra_headers)
3014 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3015 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3016
3017 // If there was a specialization somewhere, such that 'template<>' is
3018 // not required, and there were any 'template<>' headers, note where the
3019 // specialization occurred.
3020 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3021 !SuppressDiagnostic)
3022 Diag(ExplicitSpecLoc,
3023 diag::note_explicit_template_spec_does_not_need_header)
3024 << NestedTypes.back();
3025
3026 // We have a template parameter list with no corresponding scope, which
3027 // means that the resulting template declaration can't be instantiated
3028 // properly (we'll end up with dependent nodes when we shouldn't).
3029 if (!AllExplicitSpecHeaders)
3030 Invalid = true;
3031 }
3032
3033 // C++ [temp.expl.spec]p16:
3034 // In an explicit specialization declaration for a member of a class
3035 // template or a member template that ap- pears in namespace scope, the
3036 // member template and some of its enclosing class templates may remain
3037 // unspecialized, except that the declaration shall not explicitly
3038 // specialize a class member template if its en- closing class templates
3039 // are not explicitly specialized as well.
3040 if (ParamLists.back()->size() == 0 &&
3041 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3042 false))
3043 return nullptr;
3044
3045 // Return the last template parameter list, which corresponds to the
3046 // entity being declared.
3047 return ParamLists.back();
3048}
3049
3051 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3052 Diag(Template->getLocation(), diag::note_template_declared_here)
3053 << (isa<FunctionTemplateDecl>(Template)
3054 ? 0
3055 : isa<ClassTemplateDecl>(Template)
3056 ? 1
3057 : isa<VarTemplateDecl>(Template)
3058 ? 2
3059 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3060 << Template->getDeclName();
3061 return;
3062 }
3063
3064 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3065 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3066 IEnd = OST->end();
3067 I != IEnd; ++I)
3068 Diag((*I)->getLocation(), diag::note_template_declared_here)
3069 << 0 << (*I)->getDeclName();
3070
3071 return;
3072 }
3073}
3074
3076 SourceLocation TemplateLoc,
3078 auto lookUpCommonType = [&](TemplateArgument T1,
3079 TemplateArgument T2) -> QualType {
3080 // Don't bother looking for other specializations if both types are
3081 // builtins - users aren't allowed to specialize for them
3082 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3083 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3084
3089 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3090
3091 EnterExpressionEvaluationContext UnevaluatedContext(
3093 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3095
3096 QualType BaseTemplateInst =
3097 S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3098
3099 if (SFINAE.hasErrorOccurred())
3100 return QualType();
3101
3102 return BaseTemplateInst;
3103 };
3104
3105 // Note A: For the common_type trait applied to a template parameter pack T of
3106 // types, the member type shall be either defined or not present as follows:
3107 switch (Ts.size()) {
3108
3109 // If sizeof...(T) is zero, there shall be no member type.
3110 case 0:
3111 return QualType();
3112
3113 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3114 // pack T. The member typedef-name type shall denote the same type, if any, as
3115 // common_type_t<T0, T0>; otherwise there shall be no member type.
3116 case 1:
3117 return lookUpCommonType(Ts[0], Ts[0]);
3118
3119 // If sizeof...(T) is two, let the first and second types constituting T be
3120 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3121 // as decay_t<T1> and decay_t<T2>, respectively.
3122 case 2: {
3123 QualType T1 = Ts[0].getAsType();
3124 QualType T2 = Ts[1].getAsType();
3125 QualType D1 = S.BuiltinDecay(T1, {});
3126 QualType D2 = S.BuiltinDecay(T2, {});
3127
3128 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3129 // the same type, if any, as common_type_t<D1, D2>.
3130 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3131 return lookUpCommonType(D1, D2);
3132
3133 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3134 // denotes a valid type, let C denote that type.
3135 {
3136 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3137 EnterExpressionEvaluationContext UnevaluatedContext(
3139 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3141
3142 // false
3144 VK_PRValue);
3145 ExprResult Cond = &CondExpr;
3146
3147 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3148 if (ConstRefQual) {
3149 D1.addConst();
3150 D2.addConst();
3151 }
3152
3153 // declval<D1>()
3154 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3155 ExprResult LHS = &LHSExpr;
3156
3157 // declval<D2>()
3158 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3159 ExprResult RHS = &RHSExpr;
3160
3163
3164 // decltype(false ? declval<D1>() : declval<D2>())
3166 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3167
3168 if (Result.isNull() || SFINAE.hasErrorOccurred())
3169 return QualType();
3170
3171 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3172 return S.BuiltinDecay(Result, TemplateLoc);
3173 };
3174
3175 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3176 return Res;
3177
3178 // Let:
3179 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3180 // COND-RES(X, Y) be
3181 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3182
3183 // C++20 only
3184 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3185 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3186 if (!S.Context.getLangOpts().CPlusPlus20)
3187 return QualType();
3188 return CheckConditionalOperands(true);
3189 }
3190 }
3191
3192 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3193 // denote the first, second, and (pack of) remaining types constituting T. Let
3194 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3195 // a type C, the member typedef-name type shall denote the same type, if any,
3196 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3197 default: {
3198 QualType Result = Ts.front().getAsType();
3199 for (auto T : llvm::drop_begin(Ts)) {
3200 Result = lookUpCommonType(Result, T.getAsType());
3201 if (Result.isNull())
3202 return QualType();
3203 }
3204 return Result;
3205 }
3206 }
3207}
3208
3209static QualType
3212 SourceLocation TemplateLoc,
3213 TemplateArgumentListInfo &TemplateArgs) {
3214 ASTContext &Context = SemaRef.getASTContext();
3215
3216 switch (BTD->getBuiltinTemplateKind()) {
3217 case BTK__make_integer_seq: {
3218 // Specializations of __make_integer_seq<S, T, N> are treated like
3219 // S<T, 0, ..., N-1>.
3220
3221 QualType OrigType = Converted[1].getAsType();
3222 // C++14 [inteseq.intseq]p1:
3223 // T shall be an integer type.
3224 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3225 SemaRef.Diag(TemplateArgs[1].getLocation(),
3226 diag::err_integer_sequence_integral_element_type);
3227 return QualType();
3228 }
3229
3230 TemplateArgument NumArgsArg = Converted[2];
3231 if (NumArgsArg.isDependent())
3233 Converted);
3234
3235 TemplateArgumentListInfo SyntheticTemplateArgs;
3236 // The type argument, wrapped in substitution sugar, gets reused as the
3237 // first template argument in the synthetic template argument list.
3238 SyntheticTemplateArgs.addArgument(
3241 OrigType, TemplateArgs[1].getLocation())));
3242
3243 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3244 // Expand N into 0 ... N-1.
3245 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3246 I < NumArgs; ++I) {
3247 TemplateArgument TA(Context, I, OrigType);
3248 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3249 TA, OrigType, TemplateArgs[2].getLocation()));
3250 }
3251 } else {
3252 // C++14 [inteseq.make]p1:
3253 // If N is negative the program is ill-formed.
3254 SemaRef.Diag(TemplateArgs[2].getLocation(),
3255 diag::err_integer_sequence_negative_length);
3256 return QualType();
3257 }
3258
3259 // The first template argument will be reused as the template decl that
3260 // our synthetic template arguments will be applied to.
3261 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3262 TemplateLoc, SyntheticTemplateArgs);
3263 }
3264
3266 // Specializations of
3267 // __type_pack_element<Index, T_1, ..., T_N>
3268 // are treated like T_Index.
3269 assert(Converted.size() == 2 &&
3270 "__type_pack_element should be given an index and a parameter pack");
3271
3272 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3273 if (IndexArg.isDependent() || Ts.isDependent())
3275 Converted);
3276
3277 llvm::APSInt Index = IndexArg.getAsIntegral();
3278 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3279 "type std::size_t, and hence be non-negative");
3280 // If the Index is out of bounds, the program is ill-formed.
3281 if (Index >= Ts.pack_size()) {
3282 SemaRef.Diag(TemplateArgs[0].getLocation(),
3283 diag::err_type_pack_element_out_of_bounds);
3284 return QualType();
3285 }
3286
3287 // We simply return the type at index `Index`.
3288 int64_t N = Index.getExtValue();
3289 return Ts.getPackAsArray()[N].getAsType();
3290 }
3291
3293 assert(Converted.size() == 4);
3294 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3296 Converted);
3297
3298 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3299 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3300 QualType HasNoTypeMember = Converted[2].getAsType();
3301 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3302 if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3303 !CT.isNull()) {
3307 CT, TemplateArgs[1].getLocation())));
3308
3309 return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3310 }
3311 return HasNoTypeMember;
3312 }
3313 }
3314 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3315}
3316
3317/// Determine whether this alias template is "enable_if_t".
3318/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3320 return AliasTemplate->getName() == "enable_if_t" ||
3321 AliasTemplate->getName() == "__enable_if_t";
3322}
3323
3324/// Collect all of the separable terms in the given condition, which
3325/// might be a conjunction.
3326///
3327/// FIXME: The right answer is to convert the logical expression into
3328/// disjunctive normal form, so we can find the first failed term
3329/// within each possible clause.
3330static void collectConjunctionTerms(Expr *Clause,
3331 SmallVectorImpl<Expr *> &Terms) {
3332 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3333 if (BinOp->getOpcode() == BO_LAnd) {
3334 collectConjunctionTerms(BinOp->getLHS(), Terms);
3335 collectConjunctionTerms(BinOp->getRHS(), Terms);
3336 return;
3337 }
3338 }
3339
3340 Terms.push_back(Clause);
3341}
3342
3343// The ranges-v3 library uses an odd pattern of a top-level "||" with
3344// a left-hand side that is value-dependent but never true. Identify
3345// the idiom and ignore that term.
3347 // Top-level '||'.
3348 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3349 if (!BinOp) return Cond;
3350
3351 if (BinOp->getOpcode() != BO_LOr) return Cond;
3352
3353 // With an inner '==' that has a literal on the right-hand side.
3354 Expr *LHS = BinOp->getLHS();
3355 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3356 if (!InnerBinOp) return Cond;
3357
3358 if (InnerBinOp->getOpcode() != BO_EQ ||
3359 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3360 return Cond;
3361
3362 // If the inner binary operation came from a macro expansion named
3363 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3364 // of the '||', which is the real, user-provided condition.
3365 SourceLocation Loc = InnerBinOp->getExprLoc();
3366 if (!Loc.isMacroID()) return Cond;
3367
3368 StringRef MacroName = PP.getImmediateMacroName(Loc);
3369 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3370 return BinOp->getRHS();
3371
3372 return Cond;
3373}
3374
3375namespace {
3376
3377// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3378// within failing boolean expression, such as substituting template parameters
3379// for actual types.
3380class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3381public:
3382 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3383 : Policy(P) {}
3384
3385 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3386 const auto *DR = dyn_cast<DeclRefExpr>(E);
3387 if (DR && DR->getQualifier()) {
3388 // If this is a qualified name, expand the template arguments in nested
3389 // qualifiers.
3390 DR->getQualifier()->print(OS, Policy, true);
3391 // Then print the decl itself.
3392 const ValueDecl *VD = DR->getDecl();
3393 OS << VD->getName();
3394 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3395 // This is a template variable, print the expanded template arguments.
3397 OS, IV->getTemplateArgs().asArray(), Policy,
3398 IV->getSpecializedTemplate()->getTemplateParameters());
3399 }
3400 return true;
3401 }
3402 return false;
3403 }
3404
3405private:
3406 const PrintingPolicy Policy;
3407};
3408
3409} // end anonymous namespace
3410
3411std::pair<Expr *, std::string>
3413 Cond = lookThroughRangesV3Condition(PP, Cond);
3414
3415 // Separate out all of the terms in a conjunction.
3417 collectConjunctionTerms(Cond, Terms);
3418
3419 // Determine which term failed.
3420 Expr *FailedCond = nullptr;
3421 for (Expr *Term : Terms) {
3422 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3423
3424 // Literals are uninteresting.
3425 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3426 isa<IntegerLiteral>(TermAsWritten))
3427 continue;
3428
3429 // The initialization of the parameter from the argument is
3430 // a constant-evaluated context.
3433
3434 bool Succeeded;
3435 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3436 !Succeeded) {
3437 FailedCond = TermAsWritten;
3438 break;
3439 }
3440 }
3441 if (!FailedCond)
3442 FailedCond = Cond->IgnoreParenImpCasts();
3443
3444 std::string Description;
3445 {
3446 llvm::raw_string_ostream Out(Description);
3448 Policy.PrintCanonicalTypes = true;
3449 FailedBooleanConditionPrinterHelper Helper(Policy);
3450 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3451 }
3452 return { FailedCond, Description };
3453}
3454
3456 SourceLocation TemplateLoc,
3457 TemplateArgumentListInfo &TemplateArgs) {
3459 Name.getUnderlying().getAsDependentTemplateName();
3460 if (DTN && DTN->isIdentifier())
3461 // When building a template-id where the template-name is dependent,
3462 // assume the template is a type template. Either our assumption is
3463 // correct, or the code is ill-formed and will be diagnosed when the
3464 // dependent name is substituted.
3467 TemplateArgs.arguments());
3468
3469 if (Name.getAsAssumedTemplateName() &&
3470 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3471 return QualType();
3472
3473 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3474
3475 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3476 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3477 // We might have a substituted template template parameter pack. If so,
3478 // build a template specialization type for it.
3479 if (Name.getAsSubstTemplateTemplateParmPack())
3481 TemplateArgs.arguments());
3482
3483 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3484 << Name;
3486 return QualType();
3487 }
3488
3489 // Check that the template argument list is well-formed for this
3490 // template.
3491 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3492 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3493 DefaultArgs, false, SugaredConverted,
3494 CanonicalConverted,
3495 /*UpdateArgsWithConversions=*/true))
3496 return QualType();
3497
3498 QualType CanonType;
3499
3501 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3502
3503 // Find the canonical type for this type alias template specialization.
3504 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3505 if (Pattern->isInvalidDecl())
3506 return QualType();
3507
3508 // Only substitute for the innermost template argument list. NOTE: Some
3509 // external resugarers rely on leaving a Subst* node here. Make the
3510 // substitution non-final in that case. Note that these external resugarers
3511 // will still miss some information in this representation, because we don't
3512 // provide enough context in the Subst* nodes in order to tell different
3513 // template type alias specializations apart.
3514 MultiLevelTemplateArgumentList TemplateArgLists;
3515 TemplateArgLists.addOuterTemplateArguments(
3516 Template, SugaredConverted,
3517 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3518 TemplateArgLists.addOuterRetainedLevels(
3519 AliasTemplate->getTemplateParameters()->getDepth());
3520
3523 *this, /*PointOfInstantiation=*/TemplateLoc,
3524 /*Entity=*/AliasTemplate,
3525 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3526
3527 // Diagnose uses of this alias.
3528 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3529
3530 if (Inst.isInvalid())
3531 return QualType();
3532
3533 std::optional<ContextRAII> SavedContext;
3534 if (!AliasTemplate->getDeclContext()->isFileContext())
3535 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3536
3537 CanonType =
3538 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3539 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3540 if (CanonType.isNull()) {
3541 // If this was enable_if and we failed to find the nested type
3542 // within enable_if in a SFINAE context, dig out the specific
3543 // enable_if condition that failed and present that instead.
3545 if (auto DeductionInfo = isSFINAEContext()) {
3546 if (*DeductionInfo &&
3547 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3548 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3549 diag::err_typename_nested_not_found_enable_if &&
3550 TemplateArgs[0].getArgument().getKind()
3552 Expr *FailedCond;
3553 std::string FailedDescription;
3554 std::tie(FailedCond, FailedDescription) =
3555 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3556
3557 // Remove the old SFINAE diagnostic.
3558 PartialDiagnosticAt OldDiag =
3560 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3561
3562 // Add a new SFINAE diagnostic specifying which condition
3563 // failed.
3564 (*DeductionInfo)->addSFINAEDiagnostic(
3565 OldDiag.first,
3566 PDiag(diag::err_typename_nested_not_found_requirement)
3567 << FailedDescription
3568 << FailedCond->getSourceRange());
3569 }
3570 }
3571 }
3572
3573 return QualType();
3574 }
3575 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3576 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3577 TemplateLoc, TemplateArgs);
3578 } else if (Name.isDependent() ||
3580 TemplateArgs, CanonicalConverted)) {
3581 // This class template specialization is a dependent
3582 // type. Therefore, its canonical type is another class template
3583 // specialization type that contains all of the converted
3584 // arguments in canonical form. This ensures that, e.g., A<T> and
3585 // A<T, T> have identical types when A is declared as:
3586 //
3587 // template<typename T, typename U = T> struct A;
3589 Name, CanonicalConverted);
3590
3591 // This might work out to be a current instantiation, in which
3592 // case the canonical type needs to be the InjectedClassNameType.
3593 //
3594 // TODO: in theory this could be a simple hashtable lookup; most
3595 // changes to CurContext don't change the set of current
3596 // instantiations.
3597 if (isa<ClassTemplateDecl>(Template)) {
3598 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3599 // If we get out to a namespace, we're done.
3600 if (Ctx->isFileContext()) break;
3601
3602 // If this isn't a record, keep looking.
3603 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3604 if (!Record) continue;
3605
3606 // Look for one of the two cases with InjectedClassNameTypes
3607 // and check whether it's the same template.
3608 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3609 !Record->getDescribedClassTemplate())
3610 continue;
3611
3612 // Fetch the injected class name type and check whether its
3613 // injected type is equal to the type we just built.
3615 QualType Injected = cast<InjectedClassNameType>(ICNT)
3616 ->getInjectedSpecializationType();
3617
3618 if (CanonType != Injected->getCanonicalTypeInternal())
3619 continue;
3620
3621 // If so, the canonical type of this TST is the injected
3622 // class name type of the record we just found.
3623 assert(ICNT.isCanonical());
3624 CanonType = ICNT;
3625 break;
3626 }
3627 }
3628 } else if (ClassTemplateDecl *ClassTemplate =
3629 dyn_cast<ClassTemplateDecl>(Template)) {
3630 // Find the class template specialization declaration that
3631 // corresponds to these arguments.
3632 void *InsertPos = nullptr;
3634 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3635 if (!Decl) {
3636 // This is the first time we have referenced this class template
3637 // specialization. Create the canonical declaration and add it to
3638 // the set of specializations.
3640 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3641 ClassTemplate->getDeclContext(),
3642 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3643 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3644 nullptr);
3645 ClassTemplate->AddSpecialization(Decl, InsertPos);
3646 if (ClassTemplate->isOutOfLine())
3647 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3648 }
3649
3650 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3651 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3652 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3653 if (!Inst.isInvalid()) {
3654 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3655 CanonicalConverted,
3656 /*Final=*/false);
3657 InstantiateAttrsForDecl(TemplateArgLists,
3658 ClassTemplate->getTemplatedDecl(), Decl);
3659 }
3660 }
3661
3662 // Diagnose uses of this specialization.
3663 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3664
3665 CanonType = Context.getTypeDeclType(Decl);
3666 assert(isa<RecordType>(CanonType) &&
3667 "type of non-dependent specialization is not a RecordType");
3668 } else {
3669 llvm_unreachable("Unhandled template kind");
3670 }
3671
3672 // Build the fully-sugared type for this class template
3673 // specialization, which refers back to the class template
3674 // specialization we created or found.
3675 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3676 CanonType);
3677}
3678
3680 TemplateNameKind &TNK,
3681 SourceLocation NameLoc,
3682 IdentifierInfo *&II) {
3683 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3684
3685 TemplateName Name = ParsedName.get();
3686 auto *ATN = Name.getAsAssumedTemplateName();
3687 assert(ATN && "not an assumed template name");
3688 II = ATN->getDeclName().getAsIdentifierInfo();
3689
3690 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3691 // Resolved to a type template name.
3692 ParsedName = TemplateTy::make(Name);
3693 TNK = TNK_Type_template;
3694 }
3695}
3696
3698 SourceLocation NameLoc,
3699 bool Diagnose) {
3700 // We assumed this undeclared identifier to be an (ADL-only) function
3701 // template name, but it was used in a context where a type was required.
3702 // Try to typo-correct it now.
3703 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3704 assert(ATN && "not an assumed template name");
3705
3706 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3707 struct CandidateCallback : CorrectionCandidateCallback {
3708 bool ValidateCandidate(const TypoCorrection &TC) override {
3709 return TC.getCorrectionDecl() &&
3711 }
3712 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3713 return std::make_unique<CandidateCallback>(*this);
3714 }
3715 } FilterCCC;
3716
3717 TypoCorrection Corrected =
3718 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3719 FilterCCC, CTK_ErrorRecovery);
3720 if (Corrected && Corrected.getFoundDecl()) {
3721 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3722 << ATN->getDeclName());
3724 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3726 return false;
3727 }
3728
3729 if (Diagnose)
3730 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3731 return true;
3732}
3733
3735 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3736 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3737 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3738 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3739 bool IsCtorOrDtorName, bool IsClassName,
3740 ImplicitTypenameContext AllowImplicitTypename) {
3741 if (SS.isInvalid())
3742 return true;
3743
3744 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3745 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3746
3747 // C++ [temp.res]p3:
3748 // A qualified-id that refers to a type and in which the
3749 // nested-name-specifier depends on a template-parameter (14.6.2)
3750 // shall be prefixed by the keyword typename to indicate that the
3751 // qualified-id denotes a type, forming an
3752 // elaborated-type-specifier (7.1.5.3).
3753 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3754 // C++2a relaxes some of those restrictions in [temp.res]p5.
3755 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3757 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3758 else
3759 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3760 << SS.getScopeRep() << TemplateII->getName()
3761 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3762 } else
3763 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3764 << SS.getScopeRep() << TemplateII->getName();
3765
3766 // FIXME: This is not quite correct recovery as we don't transform SS
3767 // into the corresponding dependent form (and we don't diagnose missing
3768 // 'template' keywords within SS as a result).
3769 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3770 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3771 TemplateArgsIn, RAngleLoc);
3772 }
3773
3774 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3775 // it's not actually allowed to be used as a type in most cases. Because
3776 // we annotate it before we know whether it's valid, we have to check for
3777 // this case here.
3778 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3779 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3780 Diag(TemplateIILoc,
3781 TemplateKWLoc.isInvalid()
3782 ? diag::err_out_of_line_qualified_id_type_names_constructor
3783 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3784 << TemplateII << 0 /*injected-class-name used as template name*/
3785 << 1 /*if any keyword was present, it was 'template'*/;
3786 }
3787 }
3788
3789 TemplateName Template = TemplateD.get();
3790 if (Template.getAsAssumedTemplateName() &&
3791 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3792 return true;
3793
3794 // Translate the parser's template argument list in our AST format.
3795 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3796 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3797
3798 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3799 assert(SS.getScopeRep() == DTN->getQualifier());
3801 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3802 TemplateArgs.arguments());
3803 // Build type-source information.
3804 TypeLocBuilder TLB;
3809 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3810 SpecTL.setTemplateNameLoc(TemplateIILoc);
3811 SpecTL.setLAngleLoc(LAngleLoc);
3812 SpecTL.setRAngleLoc(RAngleLoc);
3813 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3814 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3816 }
3817
3818 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3819 if (SpecTy.isNull())
3820 return true;
3821
3822 // Build type-source information.
3823 TypeLocBuilder TLB;
3826 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3827 SpecTL.setTemplateNameLoc(TemplateIILoc);
3828 SpecTL.setLAngleLoc(LAngleLoc);
3829 SpecTL.setRAngleLoc(RAngleLoc);
3830 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3831 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3832
3833 // Create an elaborated-type-specifier containing the nested-name-specifier.
3834 QualType ElTy =
3836 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3837 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3839 if (!ElabTL.isEmpty())
3841 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3842}
3843
3845 TypeSpecifierType TagSpec,
3846 SourceLocation TagLoc,
3847 CXXScopeSpec &SS,
3848 SourceLocation TemplateKWLoc,
3849 TemplateTy TemplateD,
3850 SourceLocation TemplateLoc,
3851 SourceLocation LAngleLoc,
3852 ASTTemplateArgsPtr TemplateArgsIn,
3853 SourceLocation RAngleLoc) {
3854 if (SS.isInvalid())
3855 return TypeResult(true);
3856
3857 TemplateName Template = TemplateD.get();
3858
3859 // Translate the parser's template argument list in our AST format.
3860 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3861 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3862
3863 // Determine the tag kind
3865 ElaboratedTypeKeyword Keyword
3867
3868 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3869 assert(SS.getScopeRep() == DTN->getQualifier());
3871 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3872 TemplateArgs.arguments());
3873
3874 // Build type-source information.
3875 TypeLocBuilder TLB;
3878 SpecTL.setElaboratedKeywordLoc(TagLoc);
3880 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3881 SpecTL.setTemplateNameLoc(TemplateLoc);
3882 SpecTL.setLAngleLoc(LAngleLoc);
3883 SpecTL.setRAngleLoc(RAngleLoc);
3884 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3885 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3887 }
3888
3889 if (TypeAliasTemplateDecl *TAT =
3890 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3891 // C++0x [dcl.type.elab]p2:
3892 // If the identifier resolves to a typedef-name or the simple-template-id
3893 // resolves to an alias template specialization, the
3894 // elaborated-type-specifier is ill-formed.
3895 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3896 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3897 Diag(TAT->getLocation(), diag::note_declared_at);
3898 }
3899
3900 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3901 if (Result.isNull())
3902 return TypeResult(true);
3903
3904 // Check the tag kind
3905 if (const RecordType *RT = Result->getAs<RecordType>()) {
3906 RecordDecl *D = RT->getDecl();
3907
3908 IdentifierInfo *Id = D->getIdentifier();
3909 assert(Id && "templated class must have an identifier");
3910
3912 TagLoc, Id)) {
3913 Diag(TagLoc, diag::err_use_with_wrong_tag)
3914 << Result
3915 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3916 Diag(D->getLocation(), diag::note_previous_use);
3917 }
3918 }
3919
3920 // Provide source-location information for the template specialization.
3921 TypeLocBuilder TLB;
3924 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3925 SpecTL.setTemplateNameLoc(TemplateLoc);
3926 SpecTL.setLAngleLoc(LAngleLoc);
3927 SpecTL.setRAngleLoc(RAngleLoc);
3928 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3929 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3930
3931 // Construct an elaborated type containing the nested-name-specifier (if any)
3932 // and tag keyword.
3935 ElabTL.setElaboratedKeywordLoc(TagLoc);
3938}
3939
3940static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3941 NamedDecl *PrevDecl,
3944
3946
3948 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3949 switch (Arg.getKind()) {
3957 return false;
3958
3960 QualType Type = Arg.getAsType();
3961 const TemplateTypeParmType *TPT =
3963 return TPT && !Type.hasQualifiers() &&
3964 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3965 }
3966
3968 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3969 if (!DRE || !DRE->getDecl())
3970 return false;
3971 const NonTypeTemplateParmDecl *NTTP =
3972 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3973 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3974 }
3975
3977 const TemplateTemplateParmDecl *TTP =
3978 dyn_cast_or_null<TemplateTemplateParmDecl>(
3980 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3981 }
3982 llvm_unreachable("unexpected kind of template argument");
3983}
3984
3987 if (Params->size() != Args.size())
3988 return false;
3989
3990 unsigned Depth = Params->getDepth();
3991
3992 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3993 TemplateArgument Arg = Args[I];
3994
3995 // If the parameter is a pack expansion, the argument must be a pack
3996 // whose only element is a pack expansion.
3997 if (Params->getParam(I)->isParameterPack()) {
3998 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3999 !Arg.pack_begin()->isPackExpansion())
4000 return false;
4001 Arg = Arg.pack_begin()->getPackExpansionPattern();
4002 }
4003
4004 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4005 return false;
4006 }
4007
4008 return true;
4009}
4010
4011template<typename PartialSpecDecl>
4012static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4013 if (Partial->getDeclContext()->isDependentContext())
4014 return;
4015
4016 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4017 // for non-substitution-failure issues?
4018 TemplateDeductionInfo Info(Partial->getLocation());
4019 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4020 return;
4021
4022 auto *Template = Partial->getSpecializedTemplate();
4023 S.Diag(Partial->getLocation(),
4024 diag::ext_partial_spec_not_more_specialized_than_primary)
4025 << isa<VarTemplateDecl>(Template);
4026
4027 if (Info.hasSFINAEDiagnostic()) {
4031 SmallString<128> SFINAEArgString;
4032 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4033 S.Diag(Diag.first,
4034 diag::note_partial_spec_not_more_specialized_than_primary)
4035 << SFINAEArgString;
4036 }
4037
4038 S.NoteTemplateLocation(*Template);
4039 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4040 Template->getAssociatedConstraints(TemplateAC);
4041 Partial->getAssociatedConstraints(PartialAC);
4042 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4043 TemplateAC);
4044}
4045
4046static void
4048 const llvm::SmallBitVector &DeducibleParams) {
4049 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4050 if (!DeducibleParams[I]) {
4051 NamedDecl *Param = TemplateParams->getParam(I);
4052 if (Param->getDeclName())
4053 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4054 << Param->getDeclName();
4055 else
4056 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4057 << "(anonymous)";
4058 }
4059 }
4060}
4061
4062
4063template<typename PartialSpecDecl>
4065 PartialSpecDecl *Partial) {
4066 // C++1z [temp.class.spec]p8: (DR1495)
4067 // - The specialization shall be more specialized than the primary
4068 // template (14.5.5.2).
4070
4071 // C++ [temp.class.spec]p8: (DR1315)
4072 // - Each template-parameter shall appear at least once in the
4073 // template-id outside a non-deduced context.
4074 // C++1z [temp.class.spec.match]p3 (P0127R2)
4075 // If the template arguments of a partial specialization cannot be
4076 // deduced because of the structure of its template-parameter-list
4077 // and the template-id, the program is ill-formed.
4078 auto *TemplateParams = Partial->getTemplateParameters();
4079 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4080 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4081 TemplateParams->getDepth(), DeducibleParams);
4082
4083 if (!DeducibleParams.all()) {
4084 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4085 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4086 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4087 << (NumNonDeducible > 1)
4088 << SourceRange(Partial->getLocation(),
4089 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4090 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4091 }
4092}
4093
4096 checkTemplatePartialSpecialization(*this, Partial);
4097}
4098
4101 checkTemplatePartialSpecialization(*this, Partial);
4102}
4103
4105 // C++1z [temp.param]p11:
4106 // A template parameter of a deduction guide template that does not have a
4107 // default-argument shall be deducible from the parameter-type-list of the
4108 // deduction guide template.
4109 auto *TemplateParams = TD->getTemplateParameters();
4110 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4111 MarkDeducedTemplateParameters(TD, DeducibleParams);
4112 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4113 // A parameter pack is deducible (to an empty pack).
4114 auto *Param = TemplateParams->getParam(I);
4115 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4116 DeducibleParams[I] = true;
4117 }
4118
4119 if (!DeducibleParams.all()) {
4120 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4121 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4122 << (NumNonDeducible > 1);
4123 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4124 }
4125}
4126
4129 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4131 // D must be variable template id.
4132 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4133 "Variable template specialization is declared with a template id.");
4134
4135 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4136 TemplateArgumentListInfo TemplateArgs =
4137 makeTemplateArgumentListInfo(*this, *TemplateId);
4138 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4139 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4140 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4141
4142 TemplateName Name = TemplateId->Template.get();
4143
4144 // The template-id must name a variable template.
4146 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4147 if (!VarTemplate) {
4148 NamedDecl *FnTemplate;
4149 if (auto *OTS = Name.getAsOverloadedTemplate())
4150 FnTemplate = *OTS->begin();
4151 else
4152 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4153 if (FnTemplate)
4154 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4155 << FnTemplate->getDeclName();
4156 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4158 }
4159
4160 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4161 auto Message = DSA->getMessage();
4162 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4163 << VarTemplate << !Message.empty() << Message;
4164 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4165 }
4166
4167 // Check for unexpanded parameter packs in any of the template arguments.
4168 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4169 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4173 return true;
4174
4175 // Check that the template argument list is well-formed for this
4176 // template.
4177 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4178 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4179 /*DefaultArgs=*/{}, false, SugaredConverted,
4180 CanonicalConverted,
4181 /*UpdateArgsWithConversions=*/true))
4182 return true;
4183
4184 // Find the variable template (partial) specialization declaration that
4185 // corresponds to these arguments.
4188 TemplateArgs.size(),
4189 CanonicalConverted))
4190 return true;
4191
4192 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4193 // also do them during instantiation.
4194 if (!Name.isDependent() &&
4196 TemplateArgs, CanonicalConverted)) {
4197 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4198 << VarTemplate->getDeclName();
4200 }
4201
4202 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4203 CanonicalConverted) &&
4204 (!Context.getLangOpts().CPlusPlus20 ||
4205 !TemplateParams->hasAssociatedConstraints())) {
4206 // C++ [temp.class.spec]p9b3:
4207 //
4208 // -- The argument list of the specialization shall not be identical
4209 // to the implicit argument list of the primary template.
4210 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4211 << /*variable template*/ 1
4212 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4213 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4214 // FIXME: Recover from this by treating the declaration as a redeclaration
4215 // of the primary template.
4216 return true;
4217 }
4218 }
4219
4220 void *InsertPos = nullptr;
4221 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4222
4224 PrevDecl = VarTemplate->findPartialSpecialization(
4225 CanonicalConverted, TemplateParams, InsertPos);
4226 else
4227 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4228
4230
4231 // Check whether we can declare a variable template specialization in
4232 // the current scope.
4233 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4234 TemplateNameLoc,
4236 return true;
4237
4238 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4239 // Since the only prior variable template specialization with these
4240 // arguments was referenced but not declared, reuse that
4241 // declaration node as our own, updating its source location and
4242 // the list of outer template parameters to reflect our new declaration.
4243 Specialization = PrevDecl;
4244 Specialization->setLocation(TemplateNameLoc);
4245 PrevDecl = nullptr;
4246 } else if (IsPartialSpecialization) {
4247 // Create a new class template partial specialization declaration node.
4249 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4252 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4253 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4254 CanonicalConverted);
4255 Partial->setTemplateArgsAsWritten(TemplateArgs);
4256
4257 if (!PrevPartial)
4258 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4259 Specialization = Partial;
4260
4261 // If we are providing an explicit specialization of a member variable
4262 // template specialization, make a note of that.
4263 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4264 PrevPartial->setMemberSpecialization();
4265
4267 } else {
4268 // Create a new class template specialization declaration node for
4269 // this explicit specialization or friend declaration.
4271 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4272 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4273 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4274
4275 if (!PrevDecl)
4276 VarTemplate->AddSpecialization(Specialization, InsertPos);
4277 }
4278
4279 // C++ [temp.expl.spec]p6:
4280 // If a template, a member template or the member of a class template is
4281 // explicitly specialized then that specialization shall be declared
4282 // before the first use of that specialization that would cause an implicit
4283 // instantiation to take place, in every translation unit in which such a
4284 // use occurs; no diagnostic is required.
4285 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4286 bool Okay = false;
4287 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4288 // Is there any previous explicit specialization declaration?
4290 Okay = true;
4291 break;
4292 }
4293 }
4294
4295 if (!Okay) {
4296 SourceRange Range(TemplateNameLoc, RAngleLoc);
4297 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4298 << Name << Range;
4299
4300 Diag(PrevDecl->getPointOfInstantiation(),
4301 diag::note_instantiation_required_here)
4302 << (PrevDecl->getTemplateSpecializationKind() !=
4304 return true;
4305 }
4306 }
4307
4308 Specialization->setLexicalDeclContext(CurContext);
4309
4310 // Add the specialization into its lexical context, so that it can
4311 // be seen when iterating through the list of declarations in that
4312 // context. However, specializations are not found by name lookup.
4314
4315 // Note that this is an explicit specialization.
4316 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4317
4318 Previous.clear();
4319 if (PrevDecl)
4320 Previous.addDecl(PrevDecl);
4321 else if (Specialization->isStaticDataMember() &&
4322 Specialization->isOutOfLine())
4323 Specialization->setAccess(VarTemplate->getAccess());
4324
4325 return Specialization;
4326}
4327
4328namespace {
4329/// A partial specialization whose template arguments have matched
4330/// a given template-id.
4331struct PartialSpecMatchResult {
4334};
4335} // end anonymous namespace
4336
4339 SourceLocation TemplateNameLoc,
4340 const TemplateArgumentListInfo &TemplateArgs) {
4341 assert(Template && "A variable template id without template?");
4342
4343 // Check that the template argument list is well-formed for this template.
4344 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4346 Template, TemplateNameLoc,
4347 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4348 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4349 /*UpdateArgsWithConversions=*/true))
4350 return true;
4351
4352 // Produce a placeholder value if the specialization is dependent.
4353 if (Template->getDeclContext()->isDependentContext() ||
4355 TemplateArgs, CanonicalConverted))
4356 return DeclResult();
4357
4358 // Find the variable template specialization declaration that
4359 // corresponds to these arguments.
4360 void *InsertPos = nullptr;
4362 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4363 checkSpecializationReachability(TemplateNameLoc, Spec);
4364 // If we already have a variable template specialization, return it.
4365 return Spec;
4366 }
4367
4368 // This is the first time we have referenced this variable template
4369 // specialization. Create the canonical declaration and add it to
4370 // the set of specializations, based on the closest partial specialization
4371 // that it represents. That is,
4372 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4373 const TemplateArgumentList *PartialSpecArgs = nullptr;
4374 bool AmbiguousPartialSpec = false;
4375 typedef PartialSpecMatchResult MatchResult;
4377 SourceLocation PointOfInstantiation = TemplateNameLoc;
4378 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4379 /*ForTakingAddress=*/false);
4380
4381 // 1. Attempt to find the closest partial specialization that this
4382 // specializes, if any.
4383 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4384 // Perhaps better after unification of DeduceTemplateArguments() and
4385 // getMoreSpecializedPartialSpecialization().
4387 Template->getPartialSpecializations(PartialSpecs);
4388
4389 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4390 // C++ [temp.spec.partial.member]p2:
4391 // If the primary member template is explicitly specialized for a given
4392 // (implicit) specialization of the enclosing class template, the partial
4393 // specializations of the member template are ignored for this
4394 // specialization of the enclosing class template. If a partial
4395 // specialization of the member template is explicitly specialized for a
4396 // given (implicit) specialization of the enclosing class template, the
4397 // primary member template and its other partial specializations are still
4398 // considered for this specialization of the enclosing class template.
4399 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4400 !Partial->getMostRecentDecl()->isMemberSpecialization())
4401 continue;
4402
4403 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4404
4406 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4408 // Store the failed-deduction information for use in diagnostics, later.
4409 // TODO: Actually use the failed-deduction info?
4410 FailedCandidates.addCandidate().set(
4411 DeclAccessPair::make(Template, AS_public), Partial,
4413 (void)Result;
4414 } else {
4415 Matched.push_back(PartialSpecMatchResult());
4416 Matched.back().Partial = Partial;
4417 Matched.back().Args = Info.takeSugared();
4418 }
4419 }
4420
4421 if (Matched.size() >= 1) {
4422 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4423 if (Matched.size() == 1) {
4424 // -- If exactly one matching specialization is found, the
4425 // instantiation is generated from that specialization.
4426 // We don't need to do anything for this.
4427 } else {
4428 // -- If more than one matching specialization is found, the
4429 // partial order rules (14.5.4.2) are used to determine
4430 // whether one of the specializations is more specialized
4431 // than the others. If none of the specializations is more
4432 // specialized than all of the other matching
4433 // specializations, then the use of the variable template is
4434 // ambiguous and the program is ill-formed.
4436 PEnd = Matched.end();
4437 P != PEnd; ++P) {
4438 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4439 PointOfInstantiation) ==
4440 P->Partial)
4441 Best = P;
4442 }
4443
4444 // Determine if the best partial specialization is more specialized than
4445 // the others.
4446 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4447 PEnd = Matched.end();
4448 P != PEnd; ++P) {
4450 P->Partial, Best->Partial,
4451 PointOfInstantiation) != Best->Partial) {
4452 AmbiguousPartialSpec = true;
4453 break;
4454 }
4455 }
4456 }
4457
4458 // Instantiate using the best variable template partial specialization.
4459 InstantiationPattern = Best->Partial;
4460 PartialSpecArgs = Best->Args;
4461 } else {
4462 // -- If no match is found, the instantiation is generated
4463 // from the primary template.
4464 // InstantiationPattern = Template->getTemplatedDecl();
4465 }
4466
4467 // 2. Create the canonical declaration.
4468 // Note that we do not instantiate a definition until we see an odr-use
4469 // in DoMarkVarDeclReferenced().
4470 // FIXME: LateAttrs et al.?
4472 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4473 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4474 if (!Decl)
4475 return true;
4476
4477 if (AmbiguousPartialSpec) {
4478 // Partial ordering did not produce a clear winner. Complain.
4480 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4481 << Decl;
4482
4483 // Print the matching partial specializations.
4484 for (MatchResult P : Matched)
4485 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4486 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4487 *P.Args);
4488 return true;
4489 }
4490
4492 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4493 Decl->setInstantiationOf(D, PartialSpecArgs);
4494
4495 checkSpecializationReachability(TemplateNameLoc, Decl);
4496
4497 assert(Decl && "No variable template specialization?");
4498 return Decl;
4499}
4500
4502 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4503 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4504 const TemplateArgumentListInfo *TemplateArgs) {
4505
4506 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4507 *TemplateArgs);
4508 if (Decl.isInvalid())
4509 return ExprError();
4510
4511 if (!Decl.get())
4512 return ExprResult();
4513
4514 VarDecl *Var = cast<VarDecl>(Decl.get());
4517 NameInfo.getLoc());
4518
4519 // Build an ordinary singleton decl ref.
4520 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4521}
4522
4525 Diag(Loc, diag::err_template_missing_args)
4526 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4527 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4528 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4529 }
4530}
4531
4533 bool TemplateKeyword,
4534 TemplateDecl *TD,
4537 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4539}
4540
4543 SourceLocation TemplateKWLoc,
4544 const DeclarationNameInfo &ConceptNameInfo,
4545 NamedDecl *FoundDecl,
4546 ConceptDecl *NamedConcept,
4547 const TemplateArgumentListInfo *TemplateArgs) {
4548 assert(NamedConcept && "A concept template id without a template?");
4549
4550 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4552 NamedConcept, ConceptNameInfo.getLoc(),
4553 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4554 /*DefaultArgs=*/{},
4555 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4556 /*UpdateArgsWithConversions=*/false))
4557 return ExprError();
4558
4559 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4560
4562 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4563 CanonicalConverted);
4564 ConstraintSatisfaction Satisfaction;
4565 bool AreArgsDependent =
4567 *TemplateArgs, CanonicalConverted);
4568 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4569 /*Final=*/false);
4571
4574
4575 if (!AreArgsDependent &&
4577 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4578 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4579 TemplateArgs->getRAngleLoc()),
4580 Satisfaction))
4581 return ExprError();
4582 auto *CL = ConceptReference::Create(
4583 Context,
4585 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4588 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4589}
4590
4592 SourceLocation TemplateKWLoc,
4593 LookupResult &R,
4594 bool RequiresADL,
4595 const TemplateArgumentListInfo *TemplateArgs) {
4596 // FIXME: Can we do any checking at this point? I guess we could check the
4597 // template arguments that we have against the template name, if the template
4598 // name refers to a single template. That's not a terribly common case,
4599 // though.
4600 // foo<int> could identify a single function unambiguously
4601 // This approach does NOT work, since f<int>(1);
4602 // gets resolved prior to resorting to overload resolution
4603 // i.e., template<class T> void f(double);
4604 // vs template<class T, class U> void f(U);
4605
4606 // These should be filtered out by our callers.
4607 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4608
4609 // Non-function templates require a template argument list.
4610 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4611 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4613 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4614 return ExprError();
4615 }
4616 }
4617 bool KnownDependent = false;
4618 // In C++1y, check variable template ids.
4619 if (R.getAsSingle<VarTemplateDecl>()) {
4622 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4623 if (Res.isInvalid() || Res.isUsable())
4624 return Res;
4625 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4626 KnownDependent = true;
4627 }
4628
4629 if (R.getAsSingle<ConceptDecl>()) {
4630 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4632 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4633 }
4634
4635 // We don't want lookup warnings at this point.
4637
4640 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4641 R.begin(), R.end(), KnownDependent,
4642 /*KnownInstantiationDependent=*/false);
4643
4644 // Model the templates with UnresolvedTemplateTy. The expression should then
4645 // either be transformed in an instantiation or be diagnosed in
4646 // CheckPlaceholderExpr.
4647 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4650
4651 return ULE;
4652}
4653
4655 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4656 const DeclarationNameInfo &NameInfo,
4657 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4658 assert(TemplateArgs || TemplateKWLoc.isValid());
4659
4660 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4661 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4662 /*EnteringContext=*/false, TemplateKWLoc))
4663 return ExprError();
4664
4665 if (R.isAmbiguous())
4666 return ExprError();
4667
4669 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4670
4671 if (R.empty()) {
4673 Diag(NameInfo.getLoc(), diag::err_no_member)
4674 << NameInfo.getName() << DC << SS.getRange();
4675 return ExprError();
4676 }
4677
4678 // If necessary, build an implicit class member access.
4679 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4680 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4681 /*S=*/nullptr);
4682
4683 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4684}
4685
4687 CXXScopeSpec &SS,
4688 SourceLocation TemplateKWLoc,
4689 const UnqualifiedId &Name,
4690 ParsedType ObjectType,
4691 bool EnteringContext,
4693 bool AllowInjectedClassName) {
4694 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4695 Diag(TemplateKWLoc,
4697 diag::warn_cxx98_compat_template_outside_of_template :
4698 diag::ext_template_outside_of_template)
4699 << FixItHint::CreateRemoval(TemplateKWLoc);
4700
4701 if (SS.isInvalid())
4702 return TNK_Non_template;
4703
4704 // Figure out where isTemplateName is going to look.
4705 DeclContext *LookupCtx = nullptr;
4706 if (SS.isNotEmpty())
4707 LookupCtx = computeDeclContext(SS, EnteringContext);
4708 else if (ObjectType)
4709 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4710
4711 // C++0x [temp.names]p5:
4712 // If a name prefixed by the keyword template is not the name of
4713 // a template, the program is ill-formed. [Note: the keyword
4714 // template may not be applied to non-template members of class
4715 // templates. -end note ] [ Note: as is the case with the
4716 // typename prefix, the template prefix is allowed in cases
4717 // where it is not strictly necessary; i.e., when the
4718 // nested-name-specifier or the expression on the left of the ->
4719 // or . is not dependent on a template-parameter, or the use
4720 // does not appear in the scope of a template. -end note]
4721 //
4722 // Note: C++03 was more strict here, because it banned the use of
4723 // the "template" keyword prior to a template-name that was not a
4724 // dependent name. C++ DR468 relaxed this requirement (the
4725 // "template" keyword is now permitted). We follow the C++0x
4726 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4727 bool MemberOfUnknownSpecialization;
4728 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4729 ObjectType, EnteringContext, Result,
4730 MemberOfUnknownSpecialization);
4731 if (TNK != TNK_Non_template) {
4732 // We resolved this to a (non-dependent) template name. Return it.
4733 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4734 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4735 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4736 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4737 // C++14 [class.qual]p2:
4738 // In a lookup in which function names are not ignored and the
4739 // nested-name-specifier nominates a class C, if the name specified
4740 // [...] is the injected-class-name of C, [...] the name is instead
4741 // considered to name the constructor
4742 //
4743 // We don't get here if naming the constructor would be valid, so we
4744 // just reject immediately and recover by treating the
4745 // injected-class-name as naming the template.
4746 Diag(Name.getBeginLoc(),
4747 diag::ext_out_of_line_qualified_id_type_names_constructor)
4748 << Name.Identifier
4749 << 0 /*injected-class-name used as template name*/
4750 << TemplateKWLoc.isValid();
4751 }
4752 return TNK;
4753 }
4754
4755 if (!MemberOfUnknownSpecialization) {
4756 // Didn't find a template name, and the lookup wasn't dependent.
4757 // Do the lookup again to determine if this is a "nothing found" case or
4758 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4759 // need to do this.
4761 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4763 // Tell LookupTemplateName that we require a template so that it diagnoses
4764 // cases where it finds a non-template.
4765 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4766 ? RequiredTemplateKind(TemplateKWLoc)
4768 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4769 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4770 !R.isAmbiguous()) {
4771 if (LookupCtx)
4772 Diag(Name.getBeginLoc(), diag::err_no_member)
4773 << DNI.getName() << LookupCtx << SS.getRange();
4774 else
4775 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4776 << DNI.getName() << SS.getRange();
4777 }
4778 return TNK_Non_template;
4779 }
4780
4781 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4782
4783 switch (Name.getKind()) {
4786 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4788
4791 Qualifier, Name.OperatorFunctionId.Operator));
4792 return TNK_Function_template;
4793
4795 // This is a kind of template name, but can never occur in a dependent
4796 // scope (literal operators can only be declared at namespace scope).
4797 break;
4798
4799 default:
4800 break;
4801 }
4802
4803 // This name cannot possibly name a dependent template. Diagnose this now
4804 // rather than building a dependent template name that can never be valid.
4805 Diag(Name.getBeginLoc(),
4806 diag::err_template_kw_refers_to_dependent_non_template)
4807 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4808 << TemplateKWLoc.isValid() << TemplateKWLoc;
4809 return TNK_Non_template;
4810}
4811
4814 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4815 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4816 const TemplateArgument &Arg = AL.getArgument();
4817 QualType ArgType;
4818 TypeSourceInfo *TSI = nullptr;
4819
4820 // Check template type parameter.
4821 switch(Arg.getKind()) {
4823 // C++ [temp.arg.type]p1:
4824 // A template-argument for a template-parameter which is a
4825 // type shall be a type-id.
4826 ArgType = Arg.getAsType();
4827 TSI = AL.getTypeSourceInfo();
4828 break;
4831 // We have a template type parameter but the template argument
4832 // is a template without any arguments.
4833 SourceRange SR = AL.getSourceRange();
4836 return true;
4837 }
4839 // We have a template type parameter but the template argument is an
4840 // expression; see if maybe it is missing the "typename" keyword.
4841 CXXScopeSpec SS;
4842 DeclarationNameInfo NameInfo;
4843
4844 if (DependentScopeDeclRefExpr *ArgExpr =
4845 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4846 SS.Adopt(ArgExpr->getQualifierLoc());
4847 NameInfo = ArgExpr->getNameInfo();
4848 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4849 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4850 if (ArgExpr->isImplicitAccess()) {
4851 SS.Adopt(ArgExpr->getQualifierLoc());
4852 NameInfo = ArgExpr->getMemberNameInfo();
4853 }
4854 }
4855
4856 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4857 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4858 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4859
4860 if (Result.getAsSingle<TypeDecl>() ||
4861 Result.wasNotFoundInCurrentInstantiation()) {
4862 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4863 // Suggest that the user add 'typename' before the NNS.
4865 Diag(Loc, getLangOpts().MSVCCompat
4866 ? diag::ext_ms_template_type_arg_missing_typename
4867 : diag::err_template_arg_must_be_type_suggest)
4868 << FixItHint::CreateInsertion(Loc, "typename ");
4870
4871 // Recover by synthesizing a type using the location information that we
4872 // already have.
4874 SS.getScopeRep(), II);
4875 TypeLocBuilder TLB;
4877 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4879 TL.setNameLoc(NameInfo.getLoc());
4880 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4881
4882 // Overwrite our input TemplateArgumentLoc so that we can recover
4883 // properly.
4886
4887 break;
4888 }
4889 }
4890 // fallthrough
4891 [[fallthrough]];
4892 }
4893 default: {
4894 // We allow instantiateing a template with template argument packs when
4895 // building deduction guides.
4896 if (Arg.getKind() == TemplateArgument::Pack &&
4897 CodeSynthesisContexts.back().Kind ==
4899 SugaredConverted.push_back(Arg);
4900 CanonicalConverted.push_back(Arg);
4901 return false;
4902 }
4903 // We have a template type parameter but the template argument
4904 // is not a type.
4905 SourceRange SR = AL.getSourceRange();
4906 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4908
4909 return true;
4910 }
4911 }
4912
4913 if (CheckTemplateArgument(TSI))
4914 return true;
4915
4916 // Objective-C ARC:
4917 // If an explicitly-specified template argument type is a lifetime type
4918 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4919 if (getLangOpts().ObjCAutoRefCount &&
4920 ArgType->isObjCLifetimeType() &&
4921 !ArgType.getObjCLifetime()) {
4922 Qualifiers Qs;
4924 ArgType = Context.getQualifiedType(ArgType, Qs);
4925 }
4926
4927 SugaredConverted.push_back(TemplateArgument(ArgType));
4928 CanonicalConverted.push_back(
4930 return false;
4931}
4932
4933/// Substitute template arguments into the default template argument for
4934/// the given template type parameter.
4935///
4936/// \param SemaRef the semantic analysis object for which we are performing
4937/// the substitution.
4938///
4939/// \param Template the template that we are synthesizing template arguments
4940/// for.
4941///
4942/// \param TemplateLoc the location of the template name that started the
4943/// template-id we are checking.
4944///
4945/// \param RAngleLoc the location of the right angle bracket ('>') that
4946/// terminates the template-id.
4947///
4948/// \param Param the template template parameter whose default we are
4949/// substituting into.
4950///
4951/// \param Converted the list of template arguments provided for template
4952/// parameters that precede \p Param in the template parameter list.
4953///
4954/// \param Output the resulting substituted template argument.
4955///
4956/// \returns true if an error occurred.
4958 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4959 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4960 ArrayRef<TemplateArgument> SugaredConverted,
4961 ArrayRef<TemplateArgument> CanonicalConverted,
4962 TemplateArgumentLoc &Output) {
4963 Output = Param->getDefaultArgument();
4964
4965 // If the argument type is dependent, instantiate it now based
4966 // on the previously-computed template arguments.
4967 if (Output.getArgument().isInstantiationDependent()) {
4968 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4969 SugaredConverted,
4970 SourceRange(TemplateLoc, RAngleLoc));
4971 if (Inst.isInvalid())
4972 return true;
4973
4974 // Only substitute for the innermost template argument list.
4975 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4976 /*Final=*/true);
4977 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4978 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4979
4980 bool ForLambdaCallOperator = false;
4981 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4982 ForLambdaCallOperator = Rec->isLambda();
4983 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4984 !ForLambdaCallOperator);
4985
4986 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4987 Param->getDefaultArgumentLoc(),
4988 Param->getDeclName()))
4989 return true;
4990 }
4991
4992 return false;
4993}
4994
4995/// Substitute template arguments into the default template argument for
4996/// the given non-type template parameter.
4997///
4998/// \param SemaRef the semantic analysis object for which we are performing
4999/// the substitution.
5000///
5001/// \param Template the template that we are synthesizing template arguments
5002/// for.
5003///
5004/// \param TemplateLoc the location of the template name that started the
5005/// template-id we are checking.
5006///
5007/// \param RAngleLoc the location of the right angle bracket ('>') that
5008/// terminates the template-id.
5009///
5010/// \param Param the non-type template parameter whose default we are
5011/// substituting into.
5012///
5013/// \param Converted the list of template arguments provided for template
5014/// parameters that precede \p Param in the template parameter list.
5015///
5016/// \returns the substituted template argument, or NULL if an error occurred.
5018 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5019 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5020 ArrayRef<TemplateArgument> SugaredConverted,
5021 ArrayRef<TemplateArgument> CanonicalConverted,
5022 TemplateArgumentLoc &Output) {
5023 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5024 SugaredConverted,
5025 SourceRange(TemplateLoc, RAngleLoc));
5026 if (Inst.isInvalid())
5027 return true;
5028
5029 // Only substitute for the innermost template argument list.
5030 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5031 /*Final=*/true);
5032 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5033 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5034
5035 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5036 EnterExpressionEvaluationContext ConstantEvaluated(
5038 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5039 TemplateArgLists, Output);
5040}
5041
5042/// Substitute template arguments into the default template argument for
5043/// the given template template parameter.
5044///
5045/// \param SemaRef the semantic analysis object for which we are performing
5046/// the substitution.
5047///
5048/// \param Template the template that we are synthesizing template arguments
5049/// for.
5050///
5051/// \param TemplateLoc the location of the template name that started the
5052/// template-id we are checking.
5053///
5054/// \param RAngleLoc the location of the right angle bracket ('>') that
5055/// terminates the template-id.
5056///
5057/// \param Param the template template parameter whose default we are
5058/// substituting into.
5059///
5060/// \param Converted the list of template arguments provided for template
5061/// parameters that precede \p Param in the template parameter list.
5062///
5063/// \param QualifierLoc Will be set to the nested-name-specifier (with
5064/// source-location information) that precedes the template name.
5065///
5066/// \returns the substituted template argument, or NULL if an error occurred.
5068 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5069 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5070 ArrayRef<TemplateArgument> SugaredConverted,
5071 ArrayRef<TemplateArgument> CanonicalConverted,
5072 NestedNameSpecifierLoc &QualifierLoc) {
5074 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5075 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5076 if (Inst.isInvalid())
5077 return TemplateName();
5078
5079 // Only substitute for the innermost template argument list.
5080 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5081 /*Final=*/true);
5082 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5083 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5084
5085 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5086 // Substitute into the nested-name-specifier first,
5087 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5088 if (QualifierLoc) {
5089 QualifierLoc =
5090 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5091 if (!QualifierLoc)
5092 return TemplateName();
5093 }
5094
5095 return SemaRef.SubstTemplateName(
5096 QualifierLoc,
5099 TemplateArgLists);
5100}
5101
5103 TemplateDecl *Template, SourceLocation TemplateLoc,
5104 SourceLocation RAngleLoc, Decl *Param,
5105 ArrayRef<TemplateArgument> SugaredConverted,
5106 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5107 HasDefaultArg = false;
5108
5109 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5110 if (!hasReachableDefaultArgument(TypeParm))
5111 return TemplateArgumentLoc();
5112
5113 HasDefaultArg = true;
5114 TemplateArgumentLoc Output;
5115 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5116 TypeParm, SugaredConverted,
5117 CanonicalConverted, Output))
5118 return TemplateArgumentLoc();
5119 return Output;
5120 }
5121
5122 if (NonTypeTemplateParmDecl *NonTypeParm
5123 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5124 if (!hasReachableDefaultArgument(NonTypeParm))
5125 return TemplateArgumentLoc();
5126
5127 HasDefaultArg = true;
5128 TemplateArgumentLoc Output;
5129 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5130 NonTypeParm, SugaredConverted,
5131 CanonicalConverted, Output))
5132 return TemplateArgumentLoc();
5133 return Output;
5134 }
5135
5136 TemplateTemplateParmDecl *TempTempParm
5137 = cast<TemplateTemplateParmDecl>(Param);
5138 if (!hasReachableDefaultArgument(TempTempParm))
5139 return TemplateArgumentLoc();
5140
5141 HasDefaultArg = true;
5142 NestedNameSpecifierLoc QualifierLoc;
5144 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5145 CanonicalConverted, QualifierLoc);
5146 if (TName.isNull())
5147 return TemplateArgumentLoc();
5148
5149 return TemplateArgumentLoc(
5150 Context, TemplateArgument(TName),
5152 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5153}
5154
5155/// Convert a template-argument that we parsed as a type into a template, if
5156/// possible. C++ permits injected-class-names to perform dual service as
5157/// template template arguments and as template type arguments.
5160 // Extract and step over any surrounding nested-name-specifier.
5161 NestedNameSpecifierLoc QualLoc;
5162 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5163 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5164 return TemplateArgumentLoc();
5165
5166 QualLoc = ETLoc.getQualifierLoc();
5167 TLoc = ETLoc.getNamedTypeLoc();
5168 }
5169 // If this type was written as an injected-class-name, it can be used as a
5170 // template template argument.
5171 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5172 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5173 QualLoc, InjLoc.getNameLoc());
5174
5175 // If this type was written as an injected-class-name, it may have been
5176 // converted to a RecordType during instantiation. If the RecordType is
5177 // *not* wrapped in a TemplateSpecializationType and denotes a class
5178 // template specialization, it must have come from an injected-class-name.
5179 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5180 if (auto *CTSD =
5181 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5182 return TemplateArgumentLoc(Context,
5183 TemplateName(CTSD->getSpecializedTemplate()),
5184 QualLoc, RecLoc.getNameLoc());
5185
5186 return TemplateArgumentLoc();
5187}
5188
5190 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5191 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5192 unsigned ArgumentPackIndex,
5193 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5194 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5196 // Check template type parameters.
5197 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5198 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5199 CanonicalConverted);
5200
5201 // Check non-type template parameters.
5202 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5203 // Do substitution on the type of the non-type template parameter
5204 // with the template arguments we've seen thus far. But if the
5205 // template has a dependent context then we cannot substitute yet.
5206 QualType NTTPType = NTTP->getType();
5207 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5208 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5209
5210 if (NTTPType->isInstantiationDependentType() &&
5211 !isa<TemplateTemplateParmDecl>(Template) &&
5212 !Template->getDeclContext()->isDependentContext()) {
5213 // Do substitution on the type of the non-type template parameter.
5214 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5215 SugaredConverted,
5216 SourceRange(TemplateLoc, RAngleLoc));
5217 if (Inst.isInvalid())
5218 return true;
5219
5220 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5221 /*Final=*/true);
5222 // If the parameter is a pack expansion, expand this slice of the pack.
5223 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5225 ArgumentPackIndex);
5226 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5227 NTTP->getDeclName());
5228 } else {
5229 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5230 NTTP->getDeclName());
5231 }
5232
5233 // If that worked, check the non-type template parameter type
5234 // for validity.
5235 if (!NTTPType.isNull())
5236 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5237 NTTP->getLocation());
5238 if (NTTPType.isNull())
5239 return true;
5240 }
5241
5242 switch (Arg.getArgument().getKind()) {
5244 llvm_unreachable("Should never see a NULL template argument here");
5245
5247 Expr *E = Arg.getArgument().getAsExpr();
5248 TemplateArgument SugaredResult, CanonicalResult;
5249 unsigned CurSFINAEErrors = NumSFINAEErrors;
5250 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5251 CanonicalResult, CTAK);
5252 if (Res.isInvalid())
5253 return true;
5254 // If the current template argument causes an error, give up now.
5255 if (CurSFINAEErrors < NumSFINAEErrors)
5256 return true;
5257
5258 // If the resulting expression is new, then use it in place of the
5259 // old expression in the template argument.
5260 if (Res.get() != E) {
5261 TemplateArgument TA(Res.get());
5262 Arg = TemplateArgumentLoc(TA, Res.get());
5263 }
5264
5265 SugaredConverted.push_back(SugaredResult);
5266 CanonicalConverted.push_back(CanonicalResult);
5267 break;
5268 }
5269
5274 // We've already checked this template argument, so just copy
5275 // it to the list of converted arguments.
5276 SugaredConverted.push_back(Arg.getArgument());
5277 CanonicalConverted.push_back(
5279 break;
5280
5283 // We were given a template template argument. It may not be ill-formed;
5284 // see below.
5285 if (DependentTemplateName *DTN
5288 // We have a template argument such as \c T::template X, which we
5289 // parsed as a template template argument. However, since we now
5290 // know that we need a non-type template argument, convert this
5291 // template name into an expression.
5292
5293 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5294 Arg.getTemplateNameLoc());
5295
5296 CXXScopeSpec SS;
5298 // FIXME: the template-template arg was a DependentTemplateName,
5299 // so it was provided with a template keyword. However, its source
5300 // location is not stored in the template argument structure.
5301 SourceLocation TemplateKWLoc;
5303 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5304 nullptr);
5305
5306 // If we parsed the template argument as a pack expansion, create a
5307 // pack expansion expression.
5310 if (E.isInvalid())
5311 return true;
5312 }
5313
5314 TemplateArgument SugaredResult, CanonicalResult;
5315 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5316 CanonicalResult, CTAK_Specified);
5317 if (E.isInvalid())
5318 return true;
5319
5320 SugaredConverted.push_back(SugaredResult);
5321 CanonicalConverted.push_back(CanonicalResult);
5322 break;
5323 }
5324
5325 // We have a template argument that actually does refer to a class
5326 // template, alias template, or template template parameter, and
5327 // therefore cannot be a non-type template argument.
5328 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5329 << Arg.getSourceRange();
5331
5332 return true;
5333
5335 // We have a non-type template parameter but the template
5336 // argument is a type.
5337
5338 // C++ [temp.arg]p2:
5339 // In a template-argument, an ambiguity between a type-id and
5340 // an expression is resolved to a type-id, regardless of the
5341 // form of the corresponding template-parameter.
5342 //
5343 // We warn specifically about this case, since it can be rather
5344 // confusing for users.
5345 QualType T = Arg.getArgument().getAsType();
5346 SourceRange SR = Arg.getSourceRange();
5347 if (T->isFunctionType())
5348 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5349 else
5350 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5352 return true;
5353 }
5354
5356 llvm_unreachable("Caller must expand template argument packs");
5357 }
5358
5359 return false;
5360 }
5361
5362
5363 // Check template template parameters.
5364 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5365
5366 TemplateParameterList *Params = TempParm->getTemplateParameters();
5367 if (TempParm->isExpandedParameterPack())
5368 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5369
5370 // Substitute into the template parameter list of the template
5371 // template parameter, since previously-supplied template arguments
5372 // may appear within the template template parameter.
5373 //
5374 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5375 {
5376 // Set up a template instantiation context.
5378 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5379 SugaredConverted,
5380 SourceRange(TemplateLoc, RAngleLoc));
5381 if (Inst.isInvalid())
5382 return true;
5383
5384 Params =
5387 Template, SugaredConverted, /*Final=*/true),
5388 /*EvaluateConstraints=*/false);
5389 if (!Params)
5390 return true;
5391 }
5392
5393 // C++1z [temp.local]p1: (DR1004)
5394 // When [the injected-class-name] is used [...] as a template-argument for
5395 // a template template-parameter [...] it refers to the class template
5396 // itself.
5400 if (!ConvertedArg.getArgument().isNull())
5401 Arg = ConvertedArg;
5402 }
5403
5404 switch (Arg.getArgument().getKind()) {
5406 llvm_unreachable("Should never see a NULL template argument here");
5407
5410 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5411 /*IsDeduced=*/CTAK != CTAK_Specified))
5412 return true;
5413
5414 SugaredConverted.push_back(Arg.getArgument());
5415 CanonicalConverted.push_back(
5417 break;
5418
5421 // We have a template template parameter but the template
5422 // argument does not refer to a template.
5423 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5424 << getLangOpts().CPlusPlus11;
5425 return true;
5426
5431 llvm_unreachable("non-type argument with template template parameter");
5432
5434 llvm_unreachable("Caller must expand template argument packs");
5435 }
5436
5437 return false;
5438}
5439
5440/// Diagnose a missing template argument.
5441template<typename TemplateParmDecl>
5443 TemplateDecl *TD,
5444 const TemplateParmDecl *D,
5446 // Dig out the most recent declaration of the template parameter; there may be
5447 // declarations of the template that are more recent than TD.
5448 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5449 ->getTemplateParameters()
5450 ->getParam(D->getIndex()));
5451
5452 // If there's a default argument that's not reachable, diagnose that we're
5453 // missing a module import.
5455 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5456 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5457 D->getDefaultArgumentLoc(), Modules,
5459 /*Recover*/true);
5460 return true;
5461 }
5462
5463 // FIXME: If there's a more recent default argument that *is* visible,
5464 // diagnose that it was declared too late.
5465
5467
5468 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5469 << /*not enough args*/0
5471 << TD;
5472 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5473 return true;
5474}
5475
5476/// Check that the given template argument list is well-formed
5477/// for specializing the given template.
5479 TemplateDecl *Template, SourceLocation TemplateLoc,
5480 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5481 bool PartialTemplateArgs,
5482 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5483 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5484 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5485 bool PartialOrderingTTP) {
5486
5488 *ConstraintsNotSatisfied = false;
5489
5490 // Make a copy of the template arguments for processing. Only make the
5491 // changes at the end when successful in matching the arguments to the
5492 // template.
5493 TemplateArgumentListInfo NewArgs = TemplateArgs;
5494
5496
5497 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5498
5499 // C++ [temp.arg]p1:
5500 // [...] The type and form of each template-argument specified in
5501 // a template-id shall match the type and form specified for the
5502 // corresponding parameter declared by the template in its
5503 // template-parameter-list.
5504 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5505 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5506 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5507 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5508 LocalInstantiationScope InstScope(*this, true);
5509 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5510 ParamEnd = Params->end(),
5511 Param = ParamBegin;
5512 Param != ParamEnd;
5513 /* increment in loop */) {
5514 if (size_t ParamIdx = Param - ParamBegin;
5515 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5516 // All written arguments should have been consumed by this point.
5517 assert(ArgIdx == NumArgs && "bad default argument deduction");
5518 // FIXME: Don't ignore parameter packs.
5519 if (ParamIdx == DefaultArgs.StartPos && !(*Param)->isParameterPack()) {
5520 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5521 // Default arguments from a DeducedTemplateName are already converted.
5522 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5523 SugaredConverted.push_back(DefArg);
5524 CanonicalConverted.push_back(
5526 ++Param;
5527 }
5528 continue;
5529 }
5530 }
5531
5532 // If we have an expanded parameter pack, make sure we don't have too
5533 // many arguments.
5534 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5535 if (*Expansions == SugaredArgumentPack.size()) {
5536 // We're done with this parameter pack. Pack up its arguments and add
5537 // them to the list.
5538 SugaredConverted.push_back(
5539 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5540 SugaredArgumentPack.clear();
5541
5542 CanonicalConverted.push_back(
5543 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5544 CanonicalArgumentPack.clear();
5545
5546 // This argument is assigned to the next parameter.
5547 ++Param;
5548 continue;
5549 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5550 // Not enough arguments for this parameter pack.
5551 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5552 << /*not enough args*/0
5554 << Template;
5555 NoteTemplateLocation(*Template, Params->getSourceRange());
5556 return true;
5557 }
5558 }
5559
5560 if (ArgIdx < NumArgs) {
5561 // Check the template argument we were given.
5562 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5563 RAngleLoc, SugaredArgumentPack.size(),
5564 SugaredConverted, CanonicalConverted,
5566 return true;
5567
5568 CanonicalConverted.back().setIsDefaulted(
5570 Context, NewArgs[ArgIdx].getArgument(), *Param,
5571 CanonicalConverted, Params->getDepth()));
5572
5573 bool PackExpansionIntoNonPack =
5574 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5575 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5576 // CWG1430: Don't diagnose this pack expansion when partial
5577 // ordering template template parameters. Some uses of the template could
5578 // be valid, and invalid uses will be diagnosed later during
5579 // instantiation.
5580 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5581 (isa<TypeAliasTemplateDecl>(Template) ||
5582 isa<ConceptDecl>(Template))) {
5583 // CWG1430: we have a pack expansion as an argument to an
5584 // alias template, and it's not part of a parameter pack. This
5585 // can't be canonicalized, so reject it now.
5586 // As for concepts - we cannot normalize constraints where this
5587 // situation exists.
5588 Diag(NewArgs[ArgIdx].getLocation(),
5589 diag::err_template_expansion_into_fixed_list)
5590 << (isa<ConceptDecl>(Template) ? 1 : 0)
5591 << NewArgs[ArgIdx].getSourceRange();
5593 return true;
5594 }
5595
5596 // We're now done with this argument.
5597 ++ArgIdx;
5598
5599 if ((*Param)->isTemplateParameterPack()) {
5600 // The template parameter was a template parameter pack, so take the
5601 // deduced argument and place it on the argument pack. Note that we
5602 // stay on the same template parameter so that we can deduce more
5603 // arguments.
5604 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5605 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5606 } else {
5607 // Move to the next template parameter.
5608 ++Param;
5609 }
5610
5611 // If we just saw a pack expansion into a non-pack, then directly convert
5612 // the remaining arguments, because we don't know what parameters they'll
5613 // match up with.
5614 if (PackExpansionIntoNonPack) {
5615 if (!SugaredArgumentPack.empty()) {
5616 // If we were part way through filling in an expanded parameter pack,
5617 // fall back to just producing individual arguments.
5618 SugaredConverted.insert(SugaredConverted.end(),
5619 SugaredArgumentPack.begin(),
5620 SugaredArgumentPack.end());
5621 SugaredArgumentPack.clear();
5622
5623 CanonicalConverted.insert(CanonicalConverted.end(),
5624 CanonicalArgumentPack.begin(),
5625 CanonicalArgumentPack.end());
5626 CanonicalArgumentPack.clear();
5627 }
5628
5629 while (ArgIdx < NumArgs) {
5630 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5631 SugaredConverted.push_back(Arg);
5632 CanonicalConverted.push_back(
5634 ++ArgIdx;
5635 }
5636
5637 return false;
5638 }
5639
5640 continue;
5641 }
5642
5643 // If we're checking a partial template argument list, we're done.
5644 if (PartialTemplateArgs) {
5645 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5646 SugaredConverted.push_back(
5647 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5648 CanonicalConverted.push_back(
5649 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5650 }
5651 return false;
5652 }
5653
5654 // If we have a template parameter pack with no more corresponding
5655 // arguments, just break out now and we'll fill in the argument pack below.
5656 if ((*Param)->isTemplateParameterPack()) {
5657 assert(!getExpandedPackSize(*Param) &&
5658 "Should have dealt with this already");
5659
5660 // A non-expanded parameter pack before the end of the parameter list
5661 // only occurs for an ill-formed template parameter list, unless we've
5662 // got a partial argument list for a function template, so just bail out.
5663 if (Param + 1 != ParamEnd) {
5664 assert(
5665 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5666 "Concept templates must have parameter packs at the end.");
5667 return true;
5668 }
5669
5670 SugaredConverted.push_back(
5671 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5672 SugaredArgumentPack.clear();
5673
5674 CanonicalConverted.push_back(
5675 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5676 CanonicalArgumentPack.clear();
5677
5678 ++Param;
5679 continue;
5680 }
5681
5682 // Check whether we have a default argument.
5683 bool HasDefaultArg;
5684
5685 // Retrieve the default template argument from the template
5686 // parameter. For each kind of template parameter, we substitute the
5687 // template arguments provided thus far and any "outer" template arguments
5688 // (when the template parameter was part of a nested template) into
5689 // the default argument.
5691 Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5692 CanonicalConverted, HasDefaultArg);
5693
5694 if (Arg.getArgument().isNull()) {
5695 if (!HasDefaultArg) {
5696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5697 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5698 NewArgs);
5699 if (NonTypeTemplateParmDecl *NTTP =
5700 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5701 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5702 NewArgs);
5703 return diagnoseMissingArgument(*this, TemplateLoc, Template,
5704 cast<TemplateTemplateParmDecl>(*Param),
5705 NewArgs);
5706 }
5707 return true;
5708 }
5709
5710 // Introduce an instantiation record that describes where we are using
5711 // the default template argument. We're not actually instantiating a
5712 // template here, we just create this object to put a note into the
5713 // context stack.
5714 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5715 SugaredConverted,
5716 SourceRange(TemplateLoc, RAngleLoc));
5717 if (Inst.isInvalid())
5718 return true;
5719
5720 // Check the default template argument.
5721 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5722 SugaredConverted, CanonicalConverted,
5724 return true;
5725
5726 SugaredConverted.back().setIsDefaulted(true);
5727 CanonicalConverted.back().setIsDefaulted(true);
5728
5729 // Core issue 150 (assumed resolution): if this is a template template
5730 // parameter, keep track of the default template arguments from the
5731 // template definition.
5732 if (isTemplateTemplateParameter)
5733 NewArgs.addArgument(Arg);
5734
5735 // Move to the next template parameter and argument.
5736 ++Param;
5737 ++ArgIdx;
5738 }
5739
5740 // If we're performing a partial argument substitution, allow any trailing
5741 // pack expansions; they might be empty. This can happen even if
5742 // PartialTemplateArgs is false (the list of arguments is complete but
5743 // still dependent).
5744 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5746 while (ArgIdx < NumArgs &&
5747 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5748 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5749 SugaredConverted.push_back(Arg);
5750 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5751 }
5752 }
5753
5754 // If we have any leftover arguments, then there were too many arguments.
5755 // Complain and fail.
5756 if (ArgIdx < NumArgs) {
5757 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5758 << /*too many args*/1
5760 << Template
5761 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5762 NoteTemplateLocation(*Template, Params->getSourceRange());
5763 return true;
5764 }
5765
5766 // No problems found with the new argument list, propagate changes back
5767 // to caller.
5768 if (UpdateArgsWithConversions)
5769 TemplateArgs = std::move(NewArgs);
5770
5771 if (!PartialTemplateArgs) {
5772 // Setup the context/ThisScope for the case where we are needing to
5773 // re-instantiate constraints outside of normal instantiation.
5774 DeclContext *NewContext = Template->getDeclContext();
5775
5776 // If this template is in a template, make sure we extract the templated
5777 // decl.
5778 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5779 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5780 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5781
5782 Qualifiers ThisQuals;
5783 if (const auto *Method =
5784 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5785 ThisQuals = Method->getMethodQualifiers();
5786
5787 ContextRAII Context(*this, NewContext);
5788 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5789
5791 Template, NewContext, /*Final=*/false, CanonicalConverted,
5792 /*RelativeToPrimary=*/true,
5793 /*Pattern=*/nullptr,
5794 /*ForConceptInstantiation=*/true);
5796 Template, MLTAL,
5797 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5800 return true;
5801 }
5802 }
5803
5804 return false;
5805}
5806
5807namespace {
5808 class UnnamedLocalNoLinkageFinder
5809 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5810 {
5811 Sema &S;
5812 SourceRange SR;
5813
5815
5816 public:
5817 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5818
5819 bool Visit(QualType T) {
5820 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5821 }
5822
5823#define TYPE(Class, Parent) \
5824 bool Visit##Class##Type(const Class##Type *);
5825#define ABSTRACT_TYPE(Class, Parent) \
5826 bool Visit##Class##Type(const Class##Type *) { return false; }
5827#define NON_CANONICAL_TYPE(Class, Parent) \
5828 bool Visit##Class##Type(const Class##Type *) { return false; }
5829#include "clang/AST/TypeNodes.inc"
5830
5831 bool VisitTagDecl(const TagDecl *Tag);
5832 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5833 };
5834} // end anonymous namespace
5835
5836bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5837 return false;
5838}
5839
5840bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5841 return Visit(T->getElementType());
5842}
5843
5844bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5845 return Visit(T->getPointeeType());
5846}
5847
5848bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5849 const BlockPointerType* T) {
5850 return Visit(T->getPointeeType());
5851}
5852
5853bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5854 const LValueReferenceType* T) {
5855 return Visit(T->getPointeeType());
5856}
5857
5858bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5859 const RValueReferenceType* T) {
5860 return Visit(T->getPointeeType());
5861}
5862
5863bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5864 const MemberPointerType* T) {
5865 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5866}
5867
5868bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5869 const ConstantArrayType* T) {
5870 return Visit(T->getElementType());
5871}
5872
5873bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5874 const IncompleteArrayType* T) {
5875 return Visit(T->getElementType());
5876}
5877
5878bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5879 const VariableArrayType* T) {
5880 return Visit(T->getElementType());
5881}
5882
5883bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5884 const DependentSizedArrayType* T) {
5885 return Visit(T->getElementType());
5886}
5887
5888bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5890 return Visit(T->getElementType());
5891}
5892
5893bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5894 const DependentSizedMatrixType *T) {
5895 return Visit(T->getElementType());
5896}
5897
5898bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5900 return Visit(T->getPointeeType());
5901}
5902
5903bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5904 return Visit(T->getElementType());
5905}
5906
5907bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5908 const DependentVectorType *T) {
5909 return Visit(T->getElementType());
5910}
5911
5912bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5913 return Visit(T->getElementType());
5914}
5915
5916bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5917 const ConstantMatrixType *T) {
5918 return Visit(T->getElementType());
5919}
5920
5921bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5922 const FunctionProtoType* T) {
5923 for (const auto &A : T->param_types()) {
5924 if (Visit(A))
5925 return true;
5926 }
5927
5928 return Visit(T->getReturnType());
5929}
5930
5931bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5932 const FunctionNoProtoType* T) {
5933 return Visit(T->getReturnType());
5934}
5935
5936bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5937 const UnresolvedUsingType*) {
5938 return false;
5939}
5940
5941bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5942 return false;
5943}
5944
5945bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5946 return Visit(T->getUnmodifiedType());
5947}
5948
5949bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5950 return false;
5951}
5952
5953bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5954 const PackIndexingType *) {
5955 return false;
5956}
5957
5958bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5959 const UnaryTransformType*) {
5960 return false;
5961}
5962
5963bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5964 return Visit(T->getDeducedType());
5965}
5966
5967bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5969 return Visit(T->getDeducedType());
5970}
5971
5972bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5973 return VisitTagDecl(T->getDecl());
5974}
5975
5976bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5977 return VisitTagDecl(T->getDecl());
5978}
5979
5980bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5981 const TemplateTypeParmType*) {
5982 return false;
5983}
5984
5985bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5987 return false;
5988}
5989
5990bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5992 return false;
5993}
5994
5995bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5996 const InjectedClassNameType* T) {
5997 return VisitTagDecl(T->getDecl());
5998}
5999
6000bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6001 const DependentNameType* T) {
6002 return VisitNestedNameSpecifier(T->getQualifier());
6003}
6004
6005bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6007 if (auto *Q = T->getQualifier())
6008 return VisitNestedNameSpecifier(Q);
6009 return false;
6010}
6011
6012bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6013 const PackExpansionType* T) {
6014 return Visit(T->getPattern());
6015}
6016
6017bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6018 return false;
6019}
6020
6021bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6022 const ObjCInterfaceType *) {
6023 return false;
6024}
6025
6026bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6027 const ObjCObjectPointerType *) {
6028 return false;
6029}
6030
6031bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6032 return Visit(T->getValueType());
6033}
6034
6035bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6036 return false;
6037}
6038
6039bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6040 return false;
6041}
6042
6043bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6044 const ArrayParameterType *T) {
6045 return VisitConstantArrayType(T);
6046}
6047
6048bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6049 const DependentBitIntType *T) {
6050 return false;
6051}
6052
6053bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6054 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6055 S.Diag(SR.getBegin(),
6056 S.getLangOpts().CPlusPlus11 ?
6057 diag::warn_cxx98_compat_template_arg_local_type :
6058 diag::ext_template_arg_local_type)
6059 << S.Context.getTypeDeclType(Tag) << SR;
6060 return true;
6061 }
6062
6063 if (!Tag->hasNameForLinkage()) {
6064 S.Diag(SR.getBegin(),
6065 S.getLangOpts().CPlusPlus11 ?
6066 diag::warn_cxx98_compat_template_arg_unnamed_type :
6067 diag::ext_template_arg_unnamed_type) << SR;
6068 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6069 return true;
6070 }
6071
6072 return false;
6073}
6074
6075bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6076 NestedNameSpecifier *NNS) {
6077 assert(NNS);
6078 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6079 return true;
6080
6081 switch (NNS->getKind()) {
6087 return false;
6088
6091 return Visit(QualType(NNS->getAsType(), 0));
6092 }
6093 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6094}
6095
6096bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6098 if (T->hasContainedType() && Visit(T->getContainedType()))
6099 return true;
6100 return Visit(T->getWrappedType());
6101}
6102
6104 assert(ArgInfo && "invalid TypeSourceInfo");
6105 QualType Arg = ArgInfo->getType();
6106 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6107 QualType CanonArg = Context.getCanonicalType(Arg);
6108
6109 if (CanonArg->isVariablyModifiedType()) {
6110 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6112 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6113 }
6114
6115 // C++03 [temp.arg.type]p2:
6116 // A local type, a type with no linkage, an unnamed type or a type
6117 // compounded from any of these types shall not be used as a
6118 // template-argument for a template type-parameter.
6119 //
6120 // C++11 allows these, and even in C++03 we allow them as an extension with
6121 // a warning.
6122 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6123 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6124 (void)Finder.Visit(CanonArg);
6125 }
6126
6127 return false;
6128}
6129
6133 NPV_Error
6135
6136/// Determine whether the given template argument is a null pointer
6137/// value of the appropriate type.
6140 QualType ParamType, Expr *Arg,
6141 Decl *Entity = nullptr) {
6142 if (Arg->isValueDependent() || Arg->isTypeDependent())
6143 return NPV_NotNullPointer;
6144
6145 // dllimport'd entities aren't constant but are available inside of template
6146 // arguments.
6147 if (Entity && Entity->hasAttr<DLLImportAttr>())
6148 return NPV_NotNullPointer;
6149
6150 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6151 llvm_unreachable(
6152 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6153
6154 if (!S.getLangOpts().CPlusPlus11)
6155 return NPV_NotNullPointer;
6156
6157 // Determine whether we have a constant expression.
6159 if (ArgRV.isInvalid())
6160 return NPV_Error;
6161 Arg = ArgRV.get();
6162
6163 Expr::EvalResult EvalResult;
6165 EvalResult.Diag = &Notes;
6166 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6167 EvalResult.HasSideEffects) {
6168 SourceLocation DiagLoc = Arg->getExprLoc();
6169
6170 // If our only note is the usual "invalid subexpression" note, just point
6171 // the caret at its location rather than producing an essentially
6172 // redundant note.
6173 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6174 diag::note_invalid_subexpr_in_const_expr) {
6175 DiagLoc = Notes[0].first;
6176 Notes.clear();
6177 }
6178
6179 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6180 << Arg->getType() << Arg->getSourceRange();
6181 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6182 S.Diag(Notes[I].first, Notes[I].second);
6183
6185 return NPV_Error;
6186 }
6187
6188 // C++11 [temp.arg.nontype]p1:
6189 // - an address constant expression of type std::nullptr_t
6190 if (Arg->getType()->isNullPtrType())
6191 return NPV_NullPointer;
6192
6193 // - a constant expression that evaluates to a null pointer value (4.10); or
6194 // - a constant expression that evaluates to a null member pointer value
6195 // (4.11); or
6196 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6197 (EvalResult.Val.isMemberPointer() &&
6198 !EvalResult.Val.getMemberPointerDecl())) {
6199 // If our expression has an appropriate type, we've succeeded.
6200 bool ObjCLifetimeConversion;
6201 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6202 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6203 ObjCLifetimeConversion))
6204 return NPV_NullPointer;
6205
6206 // The types didn't match, but we know we got a null pointer; complain,
6207 // then recover as if the types were correct.
6208 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6209 << Arg->getType() << ParamType << Arg->getSourceRange();
6211 return NPV_NullPointer;
6212 }
6213
6214 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6215 // We found a pointer that isn't null, but doesn't refer to an object.
6216 // We could just return NPV_NotNullPointer, but we can print a better
6217 // message with the information we have here.
6218 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6219 << EvalResult.Val.getAsString(S.Context, ParamType);
6221 return NPV_Error;
6222 }
6223
6224 // If we don't have a null pointer value, but we do have a NULL pointer
6225 // constant, suggest a cast to the appropriate type.
6227 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6228 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6229 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6231 ")");
6233 return NPV_NullPointer;
6234 }
6235
6236 // FIXME: If we ever want to support general, address-constant expressions
6237 // as non-type template arguments, we should return the ExprResult here to
6238 // be interpreted by the caller.
6239 return NPV_NotNullPointer;
6240}
6241
6242/// Checks whether the given template argument is compatible with its
6243/// template parameter.
6245 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6246 Expr *Arg, QualType ArgType) {
6247 bool ObjCLifetimeConversion;
6248 if (ParamType->isPointerType() &&
6249 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6250 S.IsQualificationConversion(ArgType, ParamType, false,
6251 ObjCLifetimeConversion)) {
6252 // For pointer-to-object types, qualification conversions are
6253 // permitted.
6254 } else {
6255 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6256 if (!ParamRef->getPointeeType()->isFunctionType()) {
6257 // C++ [temp.arg.nontype]p5b3:
6258 // For a non-type template-parameter of type reference to
6259 // object, no conversions apply. The type referred to by the
6260 // reference may be more cv-qualified than the (otherwise
6261 // identical) type of the template- argument. The
6262 // template-parameter is bound directly to the
6263 // template-argument, which shall be an lvalue.
6264
6265 // FIXME: Other qualifiers?
6266 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6267 unsigned ArgQuals = ArgType.getCVRQualifiers();
6268
6269 if ((ParamQuals | ArgQuals) != ParamQuals) {
6270 S.Diag(Arg->getBeginLoc(),
6271 diag::err_template_arg_ref_bind_ignores_quals)
6272 << ParamType << Arg->getType() << Arg->getSourceRange();
6274 return true;
6275 }
6276 }
6277 }
6278
6279 // At this point, the template argument refers to an object or
6280 // function with external linkage. We now need to check whether the
6281 // argument and parameter types are compatible.
6282 if (!S.Context.hasSameUnqualifiedType(ArgType,
6283 ParamType.getNonReferenceType())) {
6284 // We can't perform this conversion or binding.
6285 if (ParamType->isReferenceType())
6286 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6287 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6288 else
6289 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6290 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6292 return true;
6293 }
6294 }
6295
6296 return false;
6297}
6298
6299/// Checks whether the given template argument is the address
6300/// of an object or function according to C++ [temp.arg.nontype]p1.
6302 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6303 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6304 bool Invalid = false;
6305 Expr *Arg = ArgIn;
6306 QualType ArgType = Arg->getType();
6307
6308 bool AddressTaken = false;
6309 SourceLocation AddrOpLoc;
6310 if (S.getLangOpts().MicrosoftExt) {
6311 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6312 // dereference and address-of operators.
6313 Arg = Arg->IgnoreParenCasts();
6314
6315 bool ExtWarnMSTemplateArg = false;
6316 UnaryOperatorKind FirstOpKind;
6317 SourceLocation FirstOpLoc;
6318 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6319 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6320 if (UnOpKind == UO_Deref)
6321 ExtWarnMSTemplateArg = true;
6322 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6323 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6324 if (!AddrOpLoc.isValid()) {
6325 FirstOpKind = UnOpKind;
6326 FirstOpLoc = UnOp->getOperatorLoc();
6327 }
6328 } else
6329 break;
6330 }
6331 if (FirstOpLoc.isValid()) {
6332 if (ExtWarnMSTemplateArg)
6333 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6334 << ArgIn->getSourceRange();
6335
6336 if (FirstOpKind == UO_AddrOf)
6337 AddressTaken = true;
6338 else if (Arg->getType()->isPointerType()) {
6339 // We cannot let pointers get dereferenced here, that is obviously not a
6340 // constant expression.
6341 assert(FirstOpKind == UO_Deref);
6342 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6343 << Arg->getSourceRange();
6344 }
6345 }
6346 } else {
6347 // See through any implicit casts we added to fix the type.
6348 Arg = Arg->IgnoreImpCasts();
6349
6350 // C++ [temp.arg.nontype]p1:
6351 //
6352 // A template-argument for a non-type, non-template
6353 // template-parameter shall be one of: [...]
6354 //
6355 // -- the address of an object or function with external
6356 // linkage, including function templates and function
6357 // template-ids but excluding non-static class members,
6358 // expressed as & id-expression where the & is optional if
6359 // the name refers to a function or array, or if the
6360 // corresponding template-parameter is a reference; or
6361
6362 // In C++98/03 mode, give an extension warning on any extra parentheses.
6363 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6364 bool ExtraParens = false;
6365 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6366 if (!Invalid && !ExtraParens) {
6367 S.Diag(Arg->getBeginLoc(),
6368 S.getLangOpts().CPlusPlus11
6369 ? diag::warn_cxx98_compat_template_arg_extra_parens
6370 : diag::ext_template_arg_extra_parens)
6371 << Arg->getSourceRange();
6372 ExtraParens = true;
6373 }
6374
6375 Arg = Parens->getSubExpr();
6376 }
6377
6378 while (SubstNonTypeTemplateParmExpr *subst =
6379 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6380 Arg = subst->getReplacement()->IgnoreImpCasts();
6381
6382 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6383 if (UnOp->getOpcode() == UO_AddrOf) {
6384 Arg = UnOp->getSubExpr();
6385 AddressTaken = true;
6386 AddrOpLoc = UnOp->getOperatorLoc();
6387 }
6388 }
6389
6390 while (SubstNonTypeTemplateParmExpr *subst =
6391 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6392 Arg = subst->getReplacement()->IgnoreImpCasts();
6393 }
6394
6395 ValueDecl *Entity = nullptr;
6396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6397 Entity = DRE->getDecl();
6398 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6399 Entity = CUE->getGuidDecl();
6400
6401 // If our parameter has pointer type, check for a null template value.
6402 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6403 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6404 Entity)) {
6405 case NPV_NullPointer:
6406 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6407 SugaredConverted = TemplateArgument(ParamType,
6408 /*isNullPtr=*/true);
6409 CanonicalConverted =
6411 /*isNullPtr=*/true);
6412 return false;
6413
6414 case NPV_Error:
6415 return true;
6416
6417 case NPV_NotNullPointer:
6418 break;
6419 }
6420 }
6421
6422 // Stop checking the precise nature of the argument if it is value dependent,
6423 // it should be checked when instantiated.
6424 if (Arg->isValueDependent()) {
6425 SugaredConverted = TemplateArgument(ArgIn);
6426 CanonicalConverted =
6427 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6428 return false;
6429 }
6430
6431 if (!Entity) {
6432 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6433 << Arg->getSourceRange();
6435 return true;
6436 }
6437
6438 // Cannot refer to non-static data members
6439 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6440 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6441 << Entity << Arg->getSourceRange();
6443 return true;
6444 }
6445
6446 // Cannot refer to non-static member functions
6447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6448 if (!Method->isStatic()) {
6449 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6450 << Method << Arg->getSourceRange();
6452 return true;
6453 }
6454 }
6455
6456 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6457 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6458 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6459
6460 // A non-type template argument must refer to an object or function.
6461 if (!Func && !Var && !Guid) {
6462 // We found something, but we don't know specifically what it is.
6463 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6464 << Arg->getSourceRange();
6465 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6466 return true;
6467 }
6468
6469 // Address / reference template args must have external linkage in C++98.
6470 if (Entity->getFormalLinkage() == Linkage::Internal) {
6471 S.Diag(Arg->getBeginLoc(),
6472 S.getLangOpts().CPlusPlus11
6473 ? diag::warn_cxx98_compat_template_arg_object_internal
6474 : diag::ext_template_arg_object_internal)
6475 << !Func << Entity << Arg->getSourceRange();
6476 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6477 << !Func;
6478 } else if (!Entity->hasLinkage()) {
6479 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6480 << !Func << Entity << Arg->getSourceRange();
6481 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6482 << !Func;
6483 return true;
6484 }
6485
6486 if (Var) {
6487 // A value of reference type is not an object.
6488 if (Var->getType()->isReferenceType()) {
6489 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6490 << Var->getType() << Arg->getSourceRange();
6492 return true;
6493 }
6494
6495 // A template argument must have static storage duration.
6496 if (Var->getTLSKind()) {
6497 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6498 << Arg->getSourceRange();
6499 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6500 return true;
6501 }
6502 }
6503
6504 if (AddressTaken && ParamType->isReferenceType()) {
6505 // If we originally had an address-of operator, but the
6506 // parameter has reference type, complain and (if things look
6507 // like they will work) drop the address-of operator.
6508 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6509 ParamType.getNonReferenceType())) {
6510 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6511 << ParamType;
6513 return true;
6514 }
6515
6516 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6517 << ParamType
6518 << FixItHint::CreateRemoval(AddrOpLoc);
6520
6521 ArgType = Entity->getType();
6522 }
6523
6524 // If the template parameter has pointer type, either we must have taken the
6525 // address or the argument must decay to a pointer.
6526 if (!AddressTaken && ParamType->isPointerType()) {
6527 if (Func) {
6528 // Function-to-pointer decay.
6529 ArgType = S.Context.getPointerType(Func->getType());
6530 } else if (Entity->getType()->isArrayType()) {
6531 // Array-to-pointer decay.
6532 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6533 } else {
6534 // If the template parameter has pointer type but the address of
6535 // this object was not taken, complain and (possibly) recover by
6536 // taking the address of the entity.
6537 ArgType = S.Context.getPointerType(Entity->getType());
6538 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6539 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6540 << ParamType;
6542 return true;
6543 }
6544
6545 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6546 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6547
6549 }
6550 }
6551
6552 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6553 Arg, ArgType))
6554 return true;
6555
6556 // Create the template argument.
6557 SugaredConverted = TemplateArgument(Entity, ParamType);
6558 CanonicalConverted =
6559 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6560 S.Context.getCanonicalType(ParamType));
6561 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6562 return false;
6563}
6564
6565/// Checks whether the given template argument is a pointer to
6566/// member constant according to C++ [temp.arg.nontype]p1.
6567static bool
6569 QualType ParamType, Expr *&ResultArg,
6570 TemplateArgument &SugaredConverted,
6571 TemplateArgument &CanonicalConverted) {
6572 bool Invalid = false;
6573
6574 Expr *Arg = ResultArg;
6575 bool ObjCLifetimeConversion;
6576
6577 // C++ [temp.arg.nontype]p1:
6578 //
6579 // A template-argument for a non-type, non-template
6580 // template-parameter shall be one of: [...]
6581 //
6582 // -- a pointer to member expressed as described in 5.3.1.
6583 DeclRefExpr *DRE = nullptr;
6584
6585 // In C++98/03 mode, give an extension warning on any extra parentheses.
6586 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6587 bool ExtraParens = false;
6588 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6589 if (!Invalid && !ExtraParens) {
6590 S.Diag(Arg->getBeginLoc(),
6591 S.getLangOpts().CPlusPlus11
6592 ? diag::warn_cxx98_compat_template_arg_extra_parens
6593 : diag::ext_template_arg_extra_parens)
6594 << Arg->getSourceRange();
6595 ExtraParens = true;
6596 }
6597
6598 Arg = Parens->getSubExpr();
6599 }
6600
6601 while (SubstNonTypeTemplateParmExpr *subst =
6602 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6603 Arg = subst->getReplacement()->IgnoreImpCasts();
6604
6605 // A pointer-to-member constant written &Class::member.
6606 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6607 if (UnOp->getOpcode() == UO_AddrOf) {
6608 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6609 if (DRE && !DRE->getQualifier())
6610 DRE = nullptr;
6611 }
6612 }
6613 // A constant of pointer-to-member type.
6614 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6615 ValueDecl *VD = DRE->getDecl();
6616 if (VD->getType()->isMemberPointerType()) {
6617 if (isa<NonTypeTemplateParmDecl>(VD)) {
6618 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6619 SugaredConverted = TemplateArgument(Arg);
6620 CanonicalConverted =
6621 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6622 } else {
6623 SugaredConverted = TemplateArgument(VD, ParamType);
6624 CanonicalConverted =
6625 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6626 S.Context.getCanonicalType(ParamType));
6627 }
6628 return Invalid;
6629 }
6630 }
6631
6632 DRE = nullptr;
6633 }
6634
6635 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6636
6637 // Check for a null pointer value.
6638 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6639 Entity)) {
6640 case NPV_Error:
6641 return true;
6642 case NPV_NullPointer:
6643 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6644 SugaredConverted = TemplateArgument(ParamType,
6645 /*isNullPtr*/ true);
6646 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6647 /*isNullPtr*/ true);
6648 return false;
6649 case NPV_NotNullPointer:
6650 break;
6651 }
6652
6653 if (S.IsQualificationConversion(ResultArg->getType(),
6654 ParamType.getNonReferenceType(), false,
6655 ObjCLifetimeConversion)) {
6656 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6657 ResultArg->getValueKind())
6658 .get();
6659 } else if (!S.Context.hasSameUnqualifiedType(
6660 ResultArg->getType(), ParamType.getNonReferenceType())) {
6661 // We can't perform this conversion.
6662 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6663 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6665 return true;
6666 }
6667
6668 if (!DRE)
6669 return S.Diag(Arg->getBeginLoc(),
6670 diag::err_template_arg_not_pointer_to_member_form)
6671 << Arg->getSourceRange();
6672
6673 if (isa<FieldDecl>(DRE->getDecl()) ||
6674 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6675 isa<CXXMethodDecl>(DRE->getDecl())) {
6676 assert((isa<FieldDecl>(DRE->getDecl()) ||
6677 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6678 cast<CXXMethodDecl>(DRE->getDecl())
6679 ->isImplicitObjectMemberFunction()) &&
6680 "Only non-static member pointers can make it here");
6681
6682 // Okay: this is the address of a non-static member, and therefore
6683 // a member pointer constant.
6684 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6685 SugaredConverted = TemplateArgument(Arg);
6686 CanonicalConverted =
6687 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6688 } else {
6689 ValueDecl *D = DRE->getDecl();
6690 SugaredConverted = TemplateArgument(D, ParamType);
6691 CanonicalConverted =
6692 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6693 S.Context.getCanonicalType(ParamType));
6694 }
6695 return Invalid;
6696 }
6697
6698 // We found something else, but we don't know specifically what it is.
6699 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6700 << Arg->getSourceRange();
6701 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6702 return true;
6703}
6704
6706 QualType ParamType, Expr *Arg,
6707 TemplateArgument &SugaredConverted,
6708 TemplateArgument &CanonicalConverted,
6710 SourceLocation StartLoc = Arg->getBeginLoc();
6711
6712 // If the parameter type somehow involves auto, deduce the type now.
6713 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6714 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6715 // During template argument deduction, we allow 'decltype(auto)' to
6716 // match an arbitrary dependent argument.
6717 // FIXME: The language rules don't say what happens in this case.
6718 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6719 // expression is merely instantiation-dependent; is this enough?
6720 if (Arg->isTypeDependent()) {
6721 auto *AT = dyn_cast<AutoType>(DeducedT);
6722 if (AT && AT->isDecltypeAuto()) {
6723 SugaredConverted = TemplateArgument(Arg);
6724 CanonicalConverted = TemplateArgument(
6725 Context.getCanonicalTemplateArgument(SugaredConverted));
6726 return Arg;
6727 }
6728 }
6729
6730 // When checking a deduced template argument, deduce from its type even if
6731 // the type is dependent, in order to check the types of non-type template
6732 // arguments line up properly in partial ordering.
6733 Expr *DeductionArg = Arg;
6734 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6735 DeductionArg = PE->getPattern();
6736 TypeSourceInfo *TSI =
6737 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6738 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6739 InitializedEntity Entity =
6742 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6743 Expr *Inits[1] = {DeductionArg};
6744 ParamType =
6745 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6746 if (ParamType.isNull())
6747 return ExprError();
6748 } else {
6749 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6750 Param->getDepth() + 1);
6751 ParamType = QualType();
6753 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6754 /*DependentDeduction=*/true,
6755 // We do not check constraints right now because the
6756 // immediately-declared constraint of the auto type is
6757 // also an associated constraint, and will be checked
6758 // along with the other associated constraints after
6759 // checking the template argument list.
6760 /*IgnoreConstraints=*/true);
6762 if (ParamType.isNull())
6763 return ExprError();
6765 Diag(Arg->getExprLoc(),
6766 diag::err_non_type_template_parm_type_deduction_failure)
6767 << Param->getDeclName() << Param->getType() << Arg->getType()
6768 << Arg->getSourceRange();
6770 return ExprError();
6771 }
6772 }
6773 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6774 // an error. The error message normally references the parameter
6775 // declaration, but here we'll pass the argument location because that's
6776 // where the parameter type is deduced.
6777 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6778 if (ParamType.isNull()) {
6780 return ExprError();
6781 }
6782 }
6783
6784 // We should have already dropped all cv-qualifiers by now.
6785 assert(!ParamType.hasQualifiers() &&
6786 "non-type template parameter type cannot be qualified");
6787
6788 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6789 if (CTAK == CTAK_Deduced &&
6790 (ParamType->isReferenceType()
6792 Arg->getType())
6793 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6794 // FIXME: If either type is dependent, we skip the check. This isn't
6795 // correct, since during deduction we're supposed to have replaced each
6796 // template parameter with some unique (non-dependent) placeholder.
6797 // FIXME: If the argument type contains 'auto', we carry on and fail the
6798 // type check in order to force specific types to be more specialized than
6799 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6800 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6801 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6802 !Arg->getType()->getContainedDeducedType()) {
6803 SugaredConverted = TemplateArgument(Arg);
6804 CanonicalConverted = TemplateArgument(
6805 Context.getCanonicalTemplateArgument(SugaredConverted));
6806 return Arg;
6807 }
6808 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6809 // we should actually be checking the type of the template argument in P,
6810 // not the type of the template argument deduced from A, against the
6811 // template parameter type.
6812 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6813 << Arg->getType()
6814 << ParamType.getUnqualifiedType();
6816 return ExprError();
6817 }
6818
6819 // If either the parameter has a dependent type or the argument is
6820 // type-dependent, there's nothing we can check now.
6821 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6822 // Force the argument to the type of the parameter to maintain invariants.
6823 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6824 if (PE)
6825 Arg = PE->getPattern();
6827 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6828 ParamType->isLValueReferenceType() ? VK_LValue
6829 : ParamType->isRValueReferenceType() ? VK_XValue
6830 : VK_PRValue);
6831 if (E.isInvalid())
6832 return ExprError();
6833 if (PE) {
6834 // Recreate a pack expansion if we unwrapped one.
6835 E = new (Context)
6836 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6837 PE->getNumExpansions());
6838 }
6839 SugaredConverted = TemplateArgument(E.get());
6840 CanonicalConverted = TemplateArgument(
6841 Context.getCanonicalTemplateArgument(SugaredConverted));
6842 return E;
6843 }
6844
6845 QualType CanonParamType = Context.getCanonicalType(ParamType);
6846 // Avoid making a copy when initializing a template parameter of class type
6847 // from a template parameter object of the same type. This is going beyond
6848 // the standard, but is required for soundness: in
6849 // template<A a> struct X { X *p; X<a> *q; };
6850 // ... we need p and q to have the same type.
6851 //
6852 // Similarly, don't inject a call to a copy constructor when initializing
6853 // from a template parameter of the same type.
6854 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6855 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6856 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6857 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6858 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6859
6860 SugaredConverted = TemplateArgument(TPO, ParamType);
6861 CanonicalConverted =
6862 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6863 return Arg;
6864 }
6865 if (isa<NonTypeTemplateParmDecl>(ND)) {
6866 SugaredConverted = TemplateArgument(Arg);
6867 CanonicalConverted =
6868 Context.getCanonicalTemplateArgument(SugaredConverted);
6869 return Arg;
6870 }
6871 }
6872
6873 // The initialization of the parameter from the argument is
6874 // a constant-evaluated context.
6877
6878 bool IsConvertedConstantExpression = true;
6879 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6881 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6882 Expr *Inits[1] = {Arg};
6883 InitializedEntity Entity =
6885 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6886 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6887 if (Result.isInvalid() || !Result.get())
6888 return ExprError();
6890 if (Result.isInvalid() || !Result.get())
6891 return ExprError();
6892 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6893 /*DiscardedValue=*/false,
6894 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6895 .get();
6896 IsConvertedConstantExpression = false;
6897 }
6898
6899 if (getLangOpts().CPlusPlus17) {
6900 // C++17 [temp.arg.nontype]p1:
6901 // A template-argument for a non-type template parameter shall be
6902 // a converted constant expression of the type of the template-parameter.
6903 APValue Value;
6904 ExprResult ArgResult;
6905 if (IsConvertedConstantExpression) {
6906 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6907 CCEK_TemplateArg, Param);
6908 if (ArgResult.isInvalid())
6909 return ExprError();
6910 } else {
6911 ArgResult = Arg;
6912 }
6913
6914 // For a value-dependent argument, CheckConvertedConstantExpression is
6915 // permitted (and expected) to be unable to determine a value.
6916 if (ArgResult.get()->isValueDependent()) {
6917 SugaredConverted = TemplateArgument(ArgResult.get());
6918 CanonicalConverted =
6919 Context.getCanonicalTemplateArgument(SugaredConverted);
6920 return ArgResult;
6921 }
6922
6923 APValue PreNarrowingValue;
6925 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6926 false, PreNarrowingValue);
6927 if (ArgResult.isInvalid())
6928 return ExprError();
6929
6930 if (Value.isLValue()) {
6931 APValue::LValueBase Base = Value.getLValueBase();
6932 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6933 // For a non-type template-parameter of pointer or reference type,
6934 // the value of the constant expression shall not refer to
6935 assert(ParamType->isPointerOrReferenceType() ||
6936 ParamType->isNullPtrType());
6937 // -- a temporary object
6938 // -- a string literal
6939 // -- the result of a typeid expression, or
6940 // -- a predefined __func__ variable
6941 if (Base &&
6942 (!VD ||
6943 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6944 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6945 << Arg->getSourceRange();
6946 return ExprError();
6947 }
6948
6949 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6950 VD->getType()->isArrayType() &&
6951 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6952 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6953 SugaredConverted = TemplateArgument(VD, ParamType);
6954 CanonicalConverted = TemplateArgument(
6955 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6956 return ArgResult.get();
6957 }
6958
6959 // -- a subobject [until C++20]
6960 if (!getLangOpts().CPlusPlus20) {
6961 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6962 Value.isLValueOnePastTheEnd()) {
6963 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6964 << Value.getAsString(Context, ParamType);
6965 return ExprError();
6966 }
6967 assert((VD || !ParamType->isReferenceType()) &&
6968 "null reference should not be a constant expression");
6969 assert((!VD || !ParamType->isNullPtrType()) &&
6970 "non-null value of type nullptr_t?");
6971 }
6972 }
6973
6974 if (Value.isAddrLabelDiff())
6975 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6976
6977 SugaredConverted = TemplateArgument(Context, ParamType, Value);
6978 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6979 return ArgResult.get();
6980 }
6981
6982 // C++ [temp.arg.nontype]p5:
6983 // The following conversions are performed on each expression used
6984 // as a non-type template-argument. If a non-type
6985 // template-argument cannot be converted to the type of the
6986 // corresponding template-parameter then the program is
6987 // ill-formed.
6988 if (ParamType->isIntegralOrEnumerationType()) {
6989 // C++11:
6990 // -- for a non-type template-parameter of integral or
6991 // enumeration type, conversions permitted in a converted
6992 // constant expression are applied.
6993 //
6994 // C++98:
6995 // -- for a non-type template-parameter of integral or
6996 // enumeration type, integral promotions (4.5) and integral
6997 // conversions (4.7) are applied.
6998
6999 if (getLangOpts().CPlusPlus11) {
7000 // C++ [temp.arg.nontype]p1:
7001 // A template-argument for a non-type, non-template template-parameter
7002 // shall be one of:
7003 //
7004 // -- for a non-type template-parameter of integral or enumeration
7005 // type, a converted constant expression of the type of the
7006 // template-parameter; or
7007 llvm::APSInt Value;
7008 ExprResult ArgResult =
7011 if (ArgResult.isInvalid())
7012 return ExprError();
7013
7014 // We can't check arbitrary value-dependent arguments.
7015 if (ArgResult.get()->isValueDependent()) {
7016 SugaredConverted = TemplateArgument(ArgResult.get());
7017 CanonicalConverted =
7018 Context.getCanonicalTemplateArgument(SugaredConverted);
7019 return ArgResult;
7020 }
7021
7022 // Widen the argument value to sizeof(parameter type). This is almost
7023 // always a no-op, except when the parameter type is bool. In
7024 // that case, this may extend the argument from 1 bit to 8 bits.
7025 QualType IntegerType = ParamType;
7026 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7027 IntegerType = Enum->getDecl()->getIntegerType();
7028 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7029 ? Context.getIntWidth(IntegerType)
7030 : Context.getTypeSize(IntegerType));
7031
7032 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7033 CanonicalConverted =
7035 return ArgResult;
7036 }
7037
7038 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7039 if (ArgResult.isInvalid())
7040 return ExprError();
7041 Arg = ArgResult.get();
7042
7043 QualType ArgType = Arg->getType();
7044
7045 // C++ [temp.arg.nontype]p1:
7046 // A template-argument for a non-type, non-template
7047 // template-parameter shall be one of:
7048 //
7049 // -- an integral constant-expression of integral or enumeration
7050 // type; or
7051 // -- the name of a non-type template-parameter; or
7052 llvm::APSInt Value;
7053 if (!ArgType->isIntegralOrEnumerationType()) {
7054 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7055 << ArgType << Arg->getSourceRange();
7057 return ExprError();
7058 } else if (!Arg->isValueDependent()) {
7059 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7060 QualType T;
7061
7062 public:
7063 TmplArgICEDiagnoser(QualType T) : T(T) { }
7064
7065 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7066 SourceLocation Loc) override {
7067 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7068 }
7069 } Diagnoser(ArgType);
7070
7071 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7072 if (!Arg)
7073 return ExprError();
7074 }
7075
7076 // From here on out, all we care about is the unqualified form
7077 // of the argument type.
7078 ArgType = ArgType.getUnqualifiedType();
7079
7080 // Try to convert the argument to the parameter's type.
7081 if (Context.hasSameType(ParamType, ArgType)) {
7082 // Okay: no conversion necessary
7083 } else if (ParamType->isBooleanType()) {
7084 // This is an integral-to-boolean conversion.
7085 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7086 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7087 !ParamType->isEnumeralType()) {
7088 // This is an integral promotion or conversion.
7089 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7090 } else {
7091 // We can't perform this conversion.
7092 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7093 << Arg->getType() << ParamType << Arg->getSourceRange();
7095 return ExprError();
7096 }
7097
7098 // Add the value of this argument to the list of converted
7099 // arguments. We use the bitwidth and signedness of the template
7100 // parameter.
7101 if (Arg->isValueDependent()) {
7102 // The argument is value-dependent. Create a new
7103 // TemplateArgument with the converted expression.
7104 SugaredConverted = TemplateArgument(Arg);
7105 CanonicalConverted =
7106 Context.getCanonicalTemplateArgument(SugaredConverted);
7107 return Arg;
7108 }
7109
7110 QualType IntegerType = ParamType;
7111 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7112 IntegerType = Enum->getDecl()->getIntegerType();
7113 }
7114
7115 if (ParamType->isBooleanType()) {
7116 // Value must be zero or one.
7117 Value = Value != 0;
7118 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7119 if (Value.getBitWidth() != AllowedBits)
7120 Value = Value.extOrTrunc(AllowedBits);
7121 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7122 } else {
7123 llvm::APSInt OldValue = Value;
7124
7125 // Coerce the template argument's value to the value it will have
7126 // based on the template parameter's type.
7127 unsigned AllowedBits = IntegerType->isBitIntType()
7128 ? Context.getIntWidth(IntegerType)
7129 : Context.getTypeSize(IntegerType);
7130 if (Value.getBitWidth() != AllowedBits)
7131 Value = Value.extOrTrunc(AllowedBits);
7132 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7133
7134 // Complain if an unsigned parameter received a negative value.
7135 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7136 (OldValue.isSigned() && OldValue.isNegative())) {
7137 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7138 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7139 << Arg->getSourceRange();
7141 }
7142
7143 // Complain if we overflowed the template parameter's type.
7144 unsigned RequiredBits;
7145 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7146 RequiredBits = OldValue.getActiveBits();
7147 else if (OldValue.isUnsigned())
7148 RequiredBits = OldValue.getActiveBits() + 1;
7149 else
7150 RequiredBits = OldValue.getSignificantBits();
7151 if (RequiredBits > AllowedBits) {
7152 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7153 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7154 << Arg->getSourceRange();
7156 }
7157 }
7158
7159 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7160 SugaredConverted = TemplateArgument(Context, Value, T);
7161 CanonicalConverted =
7163 return Arg;
7164 }
7165
7166 QualType ArgType = Arg->getType();
7167 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7168
7169 // Handle pointer-to-function, reference-to-function, and
7170 // pointer-to-member-function all in (roughly) the same way.
7171 if (// -- For a non-type template-parameter of type pointer to
7172 // function, only the function-to-pointer conversion (4.3) is
7173 // applied. If the template-argument represents a set of
7174 // overloaded functions (or a pointer to such), the matching
7175 // function is selected from the set (13.4).
7176 (ParamType->isPointerType() &&
7177 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7178 // -- For a non-type template-parameter of type reference to
7179 // function, no conversions apply. If the template-argument
7180 // represents a set of overloaded functions, the matching
7181 // function is selected from the set (13.4).
7182 (ParamType->isReferenceType() &&
7183 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7184 // -- For a non-type template-parameter of type pointer to
7185 // member function, no conversions apply. If the
7186 // template-argument represents a set of overloaded member
7187 // functions, the matching member function is selected from
7188 // the set (13.4).
7189 (ParamType->isMemberPointerType() &&
7190 ParamType->castAs<MemberPointerType>()->getPointeeType()
7191 ->isFunctionType())) {
7192
7193 if (Arg->getType() == Context.OverloadTy) {
7194 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7195 true,
7196 FoundResult)) {
7197 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7198 return ExprError();
7199
7200 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7201 if (Res.isInvalid())
7202 return ExprError();
7203 Arg = Res.get();
7204 ArgType = Arg->getType();
7205 } else
7206 return ExprError();
7207 }
7208
7209 if (!ParamType->isMemberPointerType()) {
7211 *this, Param, ParamType, Arg, SugaredConverted,
7212 CanonicalConverted))
7213 return ExprError();
7214 return Arg;
7215 }
7216
7218 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7219 return ExprError();
7220 return Arg;
7221 }
7222
7223 if (ParamType->isPointerType()) {
7224 // -- for a non-type template-parameter of type pointer to
7225 // object, qualification conversions (4.4) and the
7226 // array-to-pointer conversion (4.2) are applied.
7227 // C++0x also allows a value of std::nullptr_t.
7228 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7229 "Only object pointers allowed here");
7230
7232 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7233 return ExprError();
7234 return Arg;
7235 }
7236
7237 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7238 // -- For a non-type template-parameter of type reference to
7239 // object, no conversions apply. The type referred to by the
7240 // reference may be more cv-qualified than the (otherwise
7241 // identical) type of the template-argument. The
7242 // template-parameter is bound directly to the
7243 // template-argument, which must be an lvalue.
7244 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7245 "Only object references allowed here");
7246
7247 if (Arg->getType() == Context.OverloadTy) {
7249 ParamRefType->getPointeeType(),
7250 true,
7251 FoundResult)) {
7252 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7253 return ExprError();
7254 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7255 if (Res.isInvalid())
7256 return ExprError();
7257 Arg = Res.get();
7258 ArgType = Arg->getType();
7259 } else
7260 return ExprError();
7261 }
7262
7264 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7265 return ExprError();
7266 return Arg;
7267 }
7268
7269 // Deal with parameters of type std::nullptr_t.
7270 if (ParamType->isNullPtrType()) {
7271 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7272 SugaredConverted = TemplateArgument(Arg);
7273 CanonicalConverted =
7274 Context.getCanonicalTemplateArgument(SugaredConverted);
7275 return Arg;
7276 }
7277
7278 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7279 case NPV_NotNullPointer:
7280 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7281 << Arg->getType() << ParamType;
7283 return ExprError();
7284
7285 case NPV_Error:
7286 return ExprError();
7287
7288 case NPV_NullPointer:
7289 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7290 SugaredConverted = TemplateArgument(ParamType,
7291 /*isNullPtr=*/true);
7292 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7293 /*isNullPtr=*/true);
7294 return Arg;
7295 }
7296 }
7297
7298 // -- For a non-type template-parameter of type pointer to data
7299 // member, qualification conversions (4.4) are applied.
7300 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7301
7303 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7304 return ExprError();
7305 return Arg;
7306}
7307
7311
7313 TemplateParameterList *Params,
7315 bool IsDeduced) {
7317 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7318 if (!Template) {
7319 // Any dependent template name is fine.
7320 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7321 return false;
7322 }
7323
7324 if (Template->isInvalidDecl())
7325 return true;
7326
7327 // C++0x [temp.arg.template]p1:
7328 // A template-argument for a template template-parameter shall be
7329 // the name of a class template or an alias template, expressed as an
7330 // id-expression. When the template-argument names a class template, only
7331 // primary class templates are considered when matching the
7332 // template template argument with the corresponding parameter;
7333 // partial specializations are not considered even if their
7334 // parameter lists match that of the template template parameter.
7335 //
7336 // Note that we also allow template template parameters here, which
7337 // will happen when we are dealing with, e.g., class template
7338 // partial specializations.
7339 if (!isa<ClassTemplateDecl>(Template) &&
7340 !isa<TemplateTemplateParmDecl>(Template) &&
7341 !isa<TypeAliasTemplateDecl>(Template) &&
7342 !isa<BuiltinTemplateDecl>(Template)) {
7343 assert(isa<FunctionTemplateDecl>(Template) &&
7344 "Only function templates are possible here");
7345 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7346 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7347 << Template;
7348 }
7349
7350 // C++1z [temp.arg.template]p3: (DR 150)
7351 // A template-argument matches a template template-parameter P when P
7352 // is at least as specialized as the template-argument A.
7353 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7354 // Quick check for the common case:
7355 // If P contains a parameter pack, then A [...] matches P if each of A's
7356 // template parameters matches the corresponding template parameter in
7357 // the template-parameter-list of P.
7359 Template->getTemplateParameters(), Params, false,
7361 // If the argument has no associated constraints, then the parameter is
7362 // definitely at least as specialized as the argument.
7363 // Otherwise - we need a more thorough check.
7364 !Template->hasAssociatedConstraints())
7365 return false;
7366
7368 Params, Template, DefaultArgs, Arg.getLocation(), IsDeduced)) {
7369 // P2113
7370 // C++20[temp.func.order]p2
7371 // [...] If both deductions succeed, the partial ordering selects the
7372 // more constrained template (if one exists) as determined below.
7373 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7374 Params->getAssociatedConstraints(ParamsAC);
7375 // C++2a[temp.arg.template]p3
7376 // [...] In this comparison, if P is unconstrained, the constraints on A
7377 // are not considered.
7378 if (ParamsAC.empty())
7379 return false;
7380
7381 Template->getAssociatedConstraints(TemplateAC);
7382
7383 bool IsParamAtLeastAsConstrained;
7384 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7385 IsParamAtLeastAsConstrained))
7386 return true;
7387 if (!IsParamAtLeastAsConstrained) {
7388 Diag(Arg.getLocation(),
7389 diag::err_template_template_parameter_not_at_least_as_constrained)
7390 << Template << Param << Arg.getSourceRange();
7391 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7392 Diag(Template->getLocation(), diag::note_entity_declared_at)
7393 << Template;
7394 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7395 TemplateAC);
7396 return true;
7397 }
7398 return false;
7399 }
7400 // FIXME: Produce better diagnostics for deduction failures.
7401 }
7402
7403 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7404 Params,
7405 true,
7407 Arg.getLocation());
7408}
7409
7411 unsigned HereDiagID,
7412 unsigned ExternalDiagID) {
7413 if (Decl.getLocation().isValid())
7414 return S.Diag(Decl.getLocation(), HereDiagID);
7415
7416 SmallString<128> Str;
7417 llvm::raw_svector_ostream Out(Str);
7419 PP.TerseOutput = 1;
7420 Decl.print(Out, PP);
7421 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7422}
7423
7425 std::optional<SourceRange> ParamRange) {
7427 noteLocation(*this, Decl, diag::note_template_decl_here,
7428 diag::note_template_decl_external);
7429 if (ParamRange && ParamRange->isValid()) {
7430 assert(Decl.getLocation().isValid() &&
7431 "Parameter range has location when Decl does not");
7432 DB << *ParamRange;
7433 }
7434}
7435
7437 noteLocation(*this, Decl, diag::note_template_param_here,
7438 diag::note_template_param_external);
7439}
7440
7442 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7444 // C++ [temp.param]p8:
7445 //
7446 // A non-type template-parameter of type "array of T" or
7447 // "function returning T" is adjusted to be of type "pointer to
7448 // T" or "pointer to function returning T", respectively.
7449 if (ParamType->isArrayType())
7450 ParamType = Context.getArrayDecayedType(ParamType);
7451 else if (ParamType->isFunctionType())
7452 ParamType = Context.getPointerType(ParamType);
7453
7454 // For a NULL non-type template argument, return nullptr casted to the
7455 // parameter's type.
7456 if (Arg.getKind() == TemplateArgument::NullPtr) {
7457 return ImpCastExprToType(
7459 ParamType,
7460 ParamType->getAs<MemberPointerType>()
7461 ? CK_NullToMemberPointer
7462 : CK_NullToPointer);
7463 }
7464 assert(Arg.getKind() == TemplateArgument::Declaration &&
7465 "Only declaration template arguments permitted here");
7466
7467 ValueDecl *VD = Arg.getAsDecl();
7468
7469 CXXScopeSpec SS;
7470 if (ParamType->isMemberPointerType()) {
7471 // If this is a pointer to member, we need to use a qualified name to
7472 // form a suitable pointer-to-member constant.
7473 assert(VD->getDeclContext()->isRecord() &&
7474 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7475 isa<IndirectFieldDecl>(VD)));
7476 QualType ClassType
7477 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7478 NestedNameSpecifier *Qualifier
7479 = NestedNameSpecifier::Create(Context, nullptr, false,
7480 ClassType.getTypePtr());
7481 SS.MakeTrivial(Context, Qualifier, Loc);
7482 }
7483
7485 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7486 if (RefExpr.isInvalid())
7487 return ExprError();
7488
7489 // For a pointer, the argument declaration is the pointee. Take its address.
7490 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7491 if (ParamType->isPointerType() && !ElemT.isNull() &&
7492 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7493 // Decay an array argument if we want a pointer to its first element.
7494 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7495 if (RefExpr.isInvalid())
7496 return ExprError();
7497 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7498 // For any other pointer, take the address (or form a pointer-to-member).
7499 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7500 if (RefExpr.isInvalid())
7501 return ExprError();
7502 } else if (ParamType->isRecordType()) {
7503 assert(isa<TemplateParamObjectDecl>(VD) &&
7504 "arg for class template param not a template parameter object");
7505 // No conversions apply in this case.
7506 return RefExpr;
7507 } else {
7508 assert(ParamType->isReferenceType() &&
7509 "unexpected type for decl template argument");
7510 if (NonTypeTemplateParmDecl *NTTP =
7511 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7512 QualType TemplateParamType = NTTP->getType();
7513 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7514 if (AT && AT->isDecltypeAuto()) {
7516 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7517 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7518 /*PackIndex=*/std::nullopt,
7519 /*RefParam=*/true);
7520 }
7521 }
7522 }
7523
7524 // At this point we should have the right value category.
7525 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7526 "value kind mismatch for non-type template argument");
7527
7528 // The type of the template parameter can differ from the type of the
7529 // argument in various ways; convert it now if necessary.
7530 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7531 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7532 CastKind CK;
7533 QualType Ignored;
7534 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7535 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7536 CK = CK_NoOp;
7537 } else if (ParamType->isVoidPointerType() &&
7538 RefExpr.get()->getType()->isPointerType()) {
7539 CK = CK_BitCast;
7540 } else {
7541 // FIXME: Pointers to members can need conversion derived-to-base or
7542 // base-to-derived conversions. We currently don't retain enough
7543 // information to convert properly (we need to track a cast path or
7544 // subobject number in the template argument).
7545 llvm_unreachable(
7546 "unexpected conversion required for non-type template argument");
7547 }
7548 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7549 RefExpr.get()->getValueKind());
7550 }
7551
7552 return RefExpr;
7553}
7554
7555/// Construct a new expression that refers to the given
7556/// integral template argument with the given source-location
7557/// information.
7558///
7559/// This routine takes care of the mapping from an integral template
7560/// argument (which may have any integral type) to the appropriate
7561/// literal value.
7563 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7564 assert(OrigT->isIntegralOrEnumerationType());
7565
7566 // If this is an enum type that we're instantiating, we need to use an integer
7567 // type the same size as the enumerator. We don't want to build an
7568 // IntegerLiteral with enum type. The integer type of an enum type can be of
7569 // any integral type with C++11 enum classes, make sure we create the right
7570 // type of literal for it.
7571 QualType T = OrigT;
7572 if (const EnumType *ET = OrigT->getAs<EnumType>())
7573 T = ET->getDecl()->getIntegerType();
7574
7575 Expr *E;
7576 if (T->isAnyCharacterType()) {
7578 if (T->isWideCharType())
7580 else if (T->isChar8Type() && S.getLangOpts().Char8)
7582 else if (T->isChar16Type())
7584 else if (T->isChar32Type())
7586 else
7588
7589 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7590 } else if (T->isBooleanType()) {
7591 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7592 } else {
7593 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7594 }
7595
7596 if (OrigT->isEnumeralType()) {
7597 // FIXME: This is a hack. We need a better way to handle substituted
7598 // non-type template parameters.
7599 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7600 nullptr, S.CurFPFeatureOverrides(),
7602 Loc, Loc);
7603 }
7604
7605 return E;
7606}
7607
7609 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7610 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7611 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7612 ILE->setType(T);
7613 return ILE;
7614 };
7615
7616 switch (Val.getKind()) {
7618 // This cannot occur in a template argument at all.
7619 case APValue::Array:
7620 case APValue::Struct:
7621 case APValue::Union:
7622 // These can only occur within a template parameter object, which is
7623 // represented as a TemplateArgument::Declaration.
7624 llvm_unreachable("unexpected template argument value");
7625
7626 case APValue::Int:
7628 Loc);
7629
7630 case APValue::Float:
7631 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7632 T, Loc);
7633
7636 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7637 Val.getFixedPoint().getScale());
7638
7639 case APValue::ComplexInt: {
7640 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7642 S, ElemT, Val.getComplexIntReal(), Loc),
7644 S, ElemT, Val.getComplexIntImag(), Loc)});
7645 }
7646
7647 case APValue::ComplexFloat: {
7648 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7649 return MakeInitList(
7651 ElemT, Loc),
7653 ElemT, Loc)});
7654 }
7655
7656 case APValue::Vector: {
7657 QualType ElemT = T->castAs<VectorType>()->getElementType();
7659 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7661 S, ElemT, Val.getVectorElt(I), Loc));
7662 return MakeInitList(Elts);
7663 }
7664
7665 case APValue::None:
7667 llvm_unreachable("Unexpected APValue kind.");
7668 case APValue::LValue:
7670 // There isn't necessarily a valid equivalent source-level syntax for
7671 // these; in particular, a naive lowering might violate access control.
7672 // So for now we lower to a ConstantExpr holding the value, wrapped around
7673 // an OpaqueValueExpr.
7674 // FIXME: We should have a better representation for this.
7676 if (T->isReferenceType()) {
7677 T = T->getPointeeType();
7678 VK = VK_LValue;
7679 }
7680 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7681 return ConstantExpr::Create(S.Context, OVE, Val);
7682 }
7683 llvm_unreachable("Unhandled APValue::ValueKind enum");
7684}
7685
7689 switch (Arg.getKind()) {
7695 llvm_unreachable("not a non-type template argument");
7696
7698 return Arg.getAsExpr();
7699
7704
7707 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7708
7711 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7712 }
7713 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7714}
7715
7716/// Match two template parameters within template parameter lists.
7718 Sema &S, NamedDecl *New,
7719 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7720 const NamedDecl *OldInstFrom, bool Complain,
7722 // Check the actual kind (type, non-type, template).
7723 if (Old->getKind() != New->getKind()) {
7724 if (Complain) {
7725 unsigned NextDiag = diag::err_template_param_different_kind;
7726 if (TemplateArgLoc.isValid()) {
7727 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7728 NextDiag = diag::note_template_param_different_kind;
7729 }
7730 S.Diag(New->getLocation(), NextDiag)
7731 << (Kind != Sema::TPL_TemplateMatch);
7732 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7733 << (Kind != Sema::TPL_TemplateMatch);
7734 }
7735
7736 return false;
7737 }
7738
7739 // Check that both are parameter packs or neither are parameter packs.
7740 // However, if we are matching a template template argument to a
7741 // template template parameter, the template template parameter can have
7742 // a parameter pack where the template template argument does not.
7743 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7745 Old->isTemplateParameterPack())) {
7746 if (Complain) {
7747 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7748 if (TemplateArgLoc.isValid()) {
7749 S.Diag(TemplateArgLoc,
7750 diag::err_template_arg_template_params_mismatch);
7751 NextDiag = diag::note_template_parameter_pack_non_pack;
7752 }
7753
7754 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7755 : isa<NonTypeTemplateParmDecl>(New)? 1
7756 : 2;
7757 S.Diag(New->getLocation(), NextDiag)
7758 << ParamKind << New->isParameterPack();
7759 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7760 << ParamKind << Old->isParameterPack();
7761 }
7762
7763 return false;
7764 }
7765
7766 // For non-type template parameters, check the type of the parameter.
7767 if (NonTypeTemplateParmDecl *OldNTTP
7768 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7769 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7770
7771 // If we are matching a template template argument to a template
7772 // template parameter and one of the non-type template parameter types
7773 // is dependent, then we must wait until template instantiation time
7774 // to actually compare the arguments.
7776 (!OldNTTP->getType()->isDependentType() &&
7777 !NewNTTP->getType()->isDependentType())) {
7778 // C++20 [temp.over.link]p6:
7779 // Two [non-type] template-parameters are equivalent [if] they have
7780 // equivalent types ignoring the use of type-constraints for
7781 // placeholder types
7782 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7783 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7784 if (!S.Context.hasSameType(OldType, NewType)) {
7785 if (Complain) {
7786 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7787 if (TemplateArgLoc.isValid()) {
7788 S.Diag(TemplateArgLoc,
7789 diag::err_template_arg_template_params_mismatch);
7790 NextDiag = diag::note_template_nontype_parm_different_type;
7791 }
7792 S.Diag(NewNTTP->getLocation(), NextDiag)
7793 << NewNTTP->getType()
7794 << (Kind != Sema::TPL_TemplateMatch);
7795 S.Diag(OldNTTP->getLocation(),
7796 diag::note_template_nontype_parm_prev_declaration)
7797 << OldNTTP->getType();
7798 }
7799
7800 return false;
7801 }
7802 }
7803 }
7804 // For template template parameters, check the template parameter types.
7805 // The template parameter lists of template template
7806 // parameters must agree.
7807 else if (TemplateTemplateParmDecl *OldTTP =
7808 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7809 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7811 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7812 OldTTP->getTemplateParameters(), Complain,
7815 : Kind),
7816 TemplateArgLoc))
7817 return false;
7818 }
7819
7822 !isa<TemplateTemplateParmDecl>(Old)) {
7823 const Expr *NewC = nullptr, *OldC = nullptr;
7824
7825 if (isa<TemplateTypeParmDecl>(New)) {
7826 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7827 NewC = TC->getImmediatelyDeclaredConstraint();
7828 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7829 OldC = TC->getImmediatelyDeclaredConstraint();
7830 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7831 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7832 ->getPlaceholderTypeConstraint())
7833 NewC = E;
7834 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7835 ->getPlaceholderTypeConstraint())
7836 OldC = E;
7837 } else
7838 llvm_unreachable("unexpected template parameter type");
7839
7840 auto Diagnose = [&] {
7841 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7842 diag::err_template_different_type_constraint);
7843 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7844 diag::note_template_prev_declaration) << /*declaration*/0;
7845 };
7846
7847 if (!NewC != !OldC) {
7848 if (Complain)
7849 Diagnose();
7850 return false;
7851 }
7852
7853 if (NewC) {
7854 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7855 NewC)) {
7856 if (Complain)
7857 Diagnose();
7858 return false;
7859 }
7860 }
7861 }
7862
7863 return true;
7864}
7865
7866/// Diagnose a known arity mismatch when comparing template argument
7867/// lists.
7868static
7873 SourceLocation TemplateArgLoc) {
7874 unsigned NextDiag = diag::err_template_param_list_different_arity;
7875 if (TemplateArgLoc.isValid()) {
7876 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7877 NextDiag = diag::note_template_param_list_different_arity;
7878 }
7879 S.Diag(New->getTemplateLoc(), NextDiag)
7880 << (New->size() > Old->size())
7881 << (Kind != Sema::TPL_TemplateMatch)
7882 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7883 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7884 << (Kind != Sema::TPL_TemplateMatch)
7885 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7886}
7887
7889 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7890 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7891 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7892 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7893 if (Complain)
7894 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7895 TemplateArgLoc);
7896
7897 return false;
7898 }
7899
7900 // C++0x [temp.arg.template]p3:
7901 // A template-argument matches a template template-parameter (call it P)
7902 // when each of the template parameters in the template-parameter-list of
7903 // the template-argument's corresponding class template or alias template
7904 // (call it A) matches the corresponding template parameter in the
7905 // template-parameter-list of P. [...]
7906 TemplateParameterList::iterator NewParm = New->begin();
7907 TemplateParameterList::iterator NewParmEnd = New->end();
7908 for (TemplateParameterList::iterator OldParm = Old->begin(),
7909 OldParmEnd = Old->end();
7910 OldParm != OldParmEnd; ++OldParm) {
7912 !(*OldParm)->isTemplateParameterPack()) {
7913 if (NewParm == NewParmEnd) {
7914 if (Complain)
7915 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7916 TemplateArgLoc);
7917
7918 return false;
7919 }
7920
7921 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7922 OldInstFrom, Complain, Kind,
7923 TemplateArgLoc))
7924 return false;
7925
7926 ++NewParm;
7927 continue;
7928 }
7929
7930 // C++0x [temp.arg.template]p3:
7931 // [...] When P's template- parameter-list contains a template parameter
7932 // pack (14.5.3), the template parameter pack will match zero or more
7933 // template parameters or template parameter packs in the
7934 // template-parameter-list of A with the same type and form as the
7935 // template parameter pack in P (ignoring whether those template
7936 // parameters are template parameter packs).
7937 for (; NewParm != NewParmEnd; ++NewParm) {
7938 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7939 OldInstFrom, Complain, Kind,
7940 TemplateArgLoc))
7941 return false;
7942 }
7943 }
7944
7945 // Make sure we exhausted all of the arguments.
7946 if (NewParm != NewParmEnd) {
7947 if (Complain)
7948 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7949 TemplateArgLoc);
7950
7951 return false;
7952 }
7953
7956 const Expr *NewRC = New->getRequiresClause();
7957 const Expr *OldRC = Old->getRequiresClause();
7958
7959 auto Diagnose = [&] {
7960 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7961 diag::err_template_different_requires_clause);
7962 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7963 diag::note_template_prev_declaration) << /*declaration*/0;
7964 };
7965
7966 if (!NewRC != !OldRC) {
7967 if (Complain)
7968 Diagnose();
7969 return false;
7970 }
7971
7972 if (NewRC) {
7973 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7974 NewRC)) {
7975 if (Complain)
7976 Diagnose();
7977 return false;
7978 }
7979 }
7980 }
7981
7982 return true;
7983}
7984
7985bool
7987 if (!S)
7988 return false;
7989
7990 // Find the nearest enclosing declaration scope.
7991 S = S->getDeclParent();
7992
7993 // C++ [temp.pre]p6: [P2096]
7994 // A template, explicit specialization, or partial specialization shall not
7995 // have C linkage.
7996 DeclContext *Ctx = S->getEntity();
7997 if (Ctx && Ctx->isExternCContext()) {
7998 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7999 << TemplateParams->getSourceRange();
8000 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8001 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8002 return true;
8003 }
8004 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8005
8006 // C++ [temp]p2:
8007 // A template-declaration can appear only as a namespace scope or
8008 // class scope declaration.
8009 // C++ [temp.expl.spec]p3:
8010 // An explicit specialization may be declared in any scope in which the
8011 // corresponding primary template may be defined.
8012 // C++ [temp.class.spec]p6: [P2096]
8013 // A partial specialization may be declared in any scope in which the
8014 // corresponding primary template may be defined.
8015 if (Ctx) {
8016 if (Ctx->isFileContext())
8017 return false;
8018 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8019 // C++ [temp.mem]p2:
8020 // A local class shall not have member templates.
8021 if (RD->isLocalClass())
8022 return Diag(TemplateParams->getTemplateLoc(),
8023 diag::err_template_inside_local_class)
8024 << TemplateParams->getSourceRange();
8025 else
8026 return false;
8027 }
8028 }
8029
8030 return Diag(TemplateParams->getTemplateLoc(),
8031 diag::err_template_outside_namespace_or_class_scope)
8032 << TemplateParams->getSourceRange();
8033}
8034
8035/// Determine what kind of template specialization the given declaration
8036/// is.
8038 if (!D)
8039 return TSK_Undeclared;
8040
8041 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8042 return Record->getTemplateSpecializationKind();
8043 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8044 return Function->getTemplateSpecializationKind();
8045 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8046 return Var->getTemplateSpecializationKind();
8047
8048 return TSK_Undeclared;
8049}
8050
8051/// Check whether a specialization is well-formed in the current
8052/// context.
8053///
8054/// This routine determines whether a template specialization can be declared
8055/// in the current context (C++ [temp.expl.spec]p2).
8056///
8057/// \param S the semantic analysis object for which this check is being
8058/// performed.
8059///
8060/// \param Specialized the entity being specialized or instantiated, which
8061/// may be a kind of template (class template, function template, etc.) or
8062/// a member of a class template (member function, static data member,
8063/// member class).
8064///
8065/// \param PrevDecl the previous declaration of this entity, if any.
8066///
8067/// \param Loc the location of the explicit specialization or instantiation of
8068/// this entity.
8069///
8070/// \param IsPartialSpecialization whether this is a partial specialization of
8071/// a class template.
8072///
8073/// \returns true if there was an error that we cannot recover from, false
8074/// otherwise.
8076 NamedDecl *Specialized,
8077 NamedDecl *PrevDecl,
8080 // Keep these "kind" numbers in sync with the %select statements in the
8081 // various diagnostics emitted by this routine.
8082 int EntityKind = 0;
8083 if (isa<ClassTemplateDecl>(Specialized))
8084 EntityKind = IsPartialSpecialization? 1 : 0;
8085 else if (isa<VarTemplateDecl>(Specialized))
8086 EntityKind = IsPartialSpecialization ? 3 : 2;
8087 else if (isa<FunctionTemplateDecl>(Specialized))
8088 EntityKind = 4;
8089 else if (isa<CXXMethodDecl>(Specialized))
8090 EntityKind = 5;
8091 else if (isa<VarDecl>(Specialized))
8092 EntityKind = 6;
8093 else if (isa<RecordDecl>(Specialized))
8094 EntityKind = 7;
8095 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8096 EntityKind = 8;
8097 else {
8098 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8099 << S.getLangOpts().CPlusPlus11;
8100 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8101 return true;
8102 }
8103
8104 // C++ [temp.expl.spec]p2:
8105 // An explicit specialization may be declared in any scope in which
8106 // the corresponding primary template may be defined.
8108 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8109 << Specialized;
8110 return true;
8111 }
8112
8113 // C++ [temp.class.spec]p6:
8114 // A class template partial specialization may be declared in any
8115 // scope in which the primary template may be defined.
8116 DeclContext *SpecializedContext =
8117 Specialized->getDeclContext()->getRedeclContext();
8119
8120 // Make sure that this redeclaration (or definition) occurs in the same
8121 // scope or an enclosing namespace.
8122 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8123 : DC->Equals(SpecializedContext))) {
8124 if (isa<TranslationUnitDecl>(SpecializedContext))
8125 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8126 << EntityKind << Specialized;
8127 else {
8128 auto *ND = cast<NamedDecl>(SpecializedContext);
8129 int Diag = diag::err_template_spec_redecl_out_of_scope;
8130 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8131 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8132 S.Diag(Loc, Diag) << EntityKind << Specialized
8133 << ND << isa<CXXRecordDecl>(ND);
8134 }
8135
8136 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8137
8138 // Don't allow specializing in the wrong class during error recovery.
8139 // Otherwise, things can go horribly wrong.
8140 if (DC->isRecord())
8141 return true;
8142 }
8143
8144 return false;
8145}
8146
8148 if (!E->isTypeDependent())
8149 return SourceLocation();
8150 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8151 Checker.TraverseStmt(E);
8152 if (Checker.MatchLoc.isInvalid())
8153 return E->getSourceRange();
8154 return Checker.MatchLoc;
8155}
8156
8157static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8158 if (!TL.getType()->isDependentType())
8159 return SourceLocation();
8160 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8161 Checker.TraverseTypeLoc(TL);
8162 if (Checker.MatchLoc.isInvalid())
8163 return TL.getSourceRange();
8164 return Checker.MatchLoc;
8165}
8166
8167/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8168/// that checks non-type template partial specialization arguments.
8170 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8171 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8172 for (unsigned I = 0; I != NumArgs; ++I) {
8173 if (Args[I].getKind() == TemplateArgument::Pack) {
8175 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8176 Args[I].pack_size(), IsDefaultArgument))
8177 return true;
8178
8179 continue;
8180 }
8181
8182 if (Args[I].getKind() != TemplateArgument::Expression)
8183 continue;
8184
8185 Expr *ArgExpr = Args[I].getAsExpr();
8186
8187 // We can have a pack expansion of any of the bullets below.
8188 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8189 ArgExpr = Expansion->getPattern();
8190
8191 // Strip off any implicit casts we added as part of type checking.
8192 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8193 ArgExpr = ICE->getSubExpr();
8194
8195 // C++ [temp.class.spec]p8:
8196 // A non-type argument is non-specialized if it is the name of a
8197 // non-type parameter. All other non-type arguments are
8198 // specialized.
8199 //
8200 // Below, we check the two conditions that only apply to
8201 // specialized non-type arguments, so skip any non-specialized
8202 // arguments.
8203 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8204 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8205 continue;
8206
8207 // C++ [temp.class.spec]p9:
8208 // Within the argument list of a class template partial
8209 // specialization, the following restrictions apply:
8210 // -- A partially specialized non-type argument expression
8211 // shall not involve a template parameter of the partial
8212 // specialization except when the argument expression is a
8213 // simple identifier.
8214 // -- The type of a template parameter corresponding to a
8215 // specialized non-type argument shall not be dependent on a
8216 // parameter of the specialization.
8217 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8218 // We implement a compromise between the original rules and DR1315:
8219 // -- A specialized non-type template argument shall not be
8220 // type-dependent and the corresponding template parameter
8221 // shall have a non-dependent type.
8222 SourceRange ParamUseRange =
8223 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8224 if (ParamUseRange.isValid()) {
8225 if (IsDefaultArgument) {
8226 S.Diag(TemplateNameLoc,
8227 diag::err_dependent_non_type_arg_in_partial_spec);
8228 S.Diag(ParamUseRange.getBegin(),
8229 diag::note_dependent_non_type_default_arg_in_partial_spec)
8230 << ParamUseRange;
8231 } else {
8232 S.Diag(ParamUseRange.getBegin(),
8233 diag::err_dependent_non_type_arg_in_partial_spec)
8234 << ParamUseRange;
8235 }
8236 return true;
8237 }
8238
8239 ParamUseRange = findTemplateParameter(
8240 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8241 if (ParamUseRange.isValid()) {
8242 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8243 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8244 << Param->getType();
8246 return true;
8247 }
8248 }
8249
8250 return false;
8251}
8252
8254 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8255 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8256 // We have to be conservative when checking a template in a dependent
8257 // context.
8258 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8259 return false;
8260
8261 TemplateParameterList *TemplateParams =
8262 PrimaryTemplate->getTemplateParameters();
8263 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8265 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8266 if (!Param)
8267 continue;
8268
8269 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8270 Param, &TemplateArgs[I],
8271 1, I >= NumExplicit))
8272 return true;
8273 }
8274
8275 return false;
8276}
8277
8279 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8280 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8282 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8283 assert(TUK != TagUseKind::Reference && "References are not specializations");
8284
8285 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8286 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8287 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8288
8289 // Find the class template we're specializing
8290 TemplateName Name = TemplateId.Template.get();
8292 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8293
8294 if (!ClassTemplate) {
8295 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8296 << (Name.getAsTemplateDecl() &&
8297 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8298 return true;
8299 }
8300
8301 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8302 auto Message = DSA->getMessage();
8303 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8304 << ClassTemplate << !Message.empty() << Message;
8305 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8306 }
8307
8308 if (S->isTemplateParamScope())
8309 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8310
8311 DeclContext *DC = ClassTemplate->getDeclContext();
8312
8313 bool isMemberSpecialization = false;
8314 bool isPartialSpecialization = false;
8315
8316 if (SS.isSet()) {
8317 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8318 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8319 TemplateNameLoc, &TemplateId,
8320 /*IsMemberSpecialization=*/false))
8321 return true;
8322 }
8323
8324 // Check the validity of the template headers that introduce this
8325 // template.
8326 // FIXME: We probably shouldn't complain about these headers for
8327 // friend declarations.
8328 bool Invalid = false;
8329 TemplateParameterList *TemplateParams =
8331 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8332 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8333 if (Invalid)
8334 return true;
8335
8336 // Check that we can declare a template specialization here.
8337 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8338 return true;
8339
8340 if (TemplateParams && DC->isDependentContext()) {
8341 ContextRAII SavedContext(*this, DC);
8343 return true;
8344 }
8345
8346 if (TemplateParams && TemplateParams->size() > 0) {
8347 isPartialSpecialization = true;
8348
8349 if (TUK == TagUseKind::Friend) {
8350 Diag(KWLoc, diag::err_partial_specialization_friend)
8351 << SourceRange(LAngleLoc, RAngleLoc);
8352 return true;
8353 }
8354
8355 // C++ [temp.class.spec]p10:
8356 // The template parameter list of a specialization shall not
8357 // contain default template argument values.
8358 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8359 Decl *Param = TemplateParams->getParam(I);
8360 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8361 if (TTP->hasDefaultArgument()) {
8362 Diag(TTP->getDefaultArgumentLoc(),
8363 diag::err_default_arg_in_partial_spec);
8364 TTP->removeDefaultArgument();
8365 }
8366 } else if (NonTypeTemplateParmDecl *NTTP
8367 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8368 if (NTTP->hasDefaultArgument()) {
8369 Diag(NTTP->getDefaultArgumentLoc(),
8370 diag::err_default_arg_in_partial_spec)
8371 << NTTP->getDefaultArgument().getSourceRange();
8372 NTTP->removeDefaultArgument();
8373 }
8374 } else {
8375 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8376 if (TTP->hasDefaultArgument()) {
8378 diag::err_default_arg_in_partial_spec)
8380 TTP->removeDefaultArgument();
8381 }
8382 }
8383 }
8384 } else if (TemplateParams) {
8385 if (TUK == TagUseKind::Friend)
8386 Diag(KWLoc, diag::err_template_spec_friend)
8388 SourceRange(TemplateParams->getTemplateLoc(),
8389 TemplateParams->getRAngleLoc()))
8390 << SourceRange(LAngleLoc, RAngleLoc);
8391 } else {
8392 assert(TUK == TagUseKind::Friend &&
8393 "should have a 'template<>' for this decl");
8394 }
8395
8396 // Check that the specialization uses the same tag kind as the
8397 // original template.
8399 assert(Kind != TagTypeKind::Enum &&
8400 "Invalid enum tag in class template spec!");
8401 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8402 TUK == TagUseKind::Definition, KWLoc,
8403 ClassTemplate->getIdentifier())) {
8404 Diag(KWLoc, diag::err_use_with_wrong_tag)
8405 << ClassTemplate
8407 ClassTemplate->getTemplatedDecl()->getKindName());
8408 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8409 diag::note_previous_use);
8410 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8411 }
8412
8413 // Translate the parser's template argument list in our AST format.
8414 TemplateArgumentListInfo TemplateArgs =
8415 makeTemplateArgumentListInfo(*this, TemplateId);
8416
8417 // Check for unexpanded parameter packs in any of the template arguments.
8418 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8419 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8420 isPartialSpecialization
8423 return true;
8424
8425 // Check that the template argument list is well-formed for this
8426 // template.
8427 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8428 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8429 /*DefaultArgs=*/{},
8430 /*PartialTemplateArgs=*/false, SugaredConverted,
8431 CanonicalConverted,
8432 /*UpdateArgsWithConversions=*/true))
8433 return true;
8434
8435 // Find the class template (partial) specialization declaration that
8436 // corresponds to these arguments.
8437 if (isPartialSpecialization) {
8439 TemplateArgs.size(),
8440 CanonicalConverted))
8441 return true;
8442
8443 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8444 // also do it during instantiation.
8445 if (!Name.isDependent() &&
8447 TemplateArgs, CanonicalConverted)) {
8448 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8449 << ClassTemplate->getDeclName();
8450 isPartialSpecialization = false;
8451 Invalid = true;
8452 }
8453 }
8454
8455 void *InsertPos = nullptr;
8456 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8457
8458 if (isPartialSpecialization)
8459 PrevDecl = ClassTemplate->findPartialSpecialization(
8460 CanonicalConverted, TemplateParams, InsertPos);
8461 else
8462 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8463
8465
8466 // Check whether we can declare a class template specialization in
8467 // the current scope.
8468 if (TUK != TagUseKind::Friend &&
8470 TemplateNameLoc,
8471 isPartialSpecialization))
8472 return true;
8473
8474 // The canonical type
8475 QualType CanonType;
8476 if (isPartialSpecialization) {
8477 // Build the canonical type that describes the converted template
8478 // arguments of the class template partial specialization.
8479 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8480 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8481 CanonicalConverted);
8482
8483 if (Context.hasSameType(CanonType,
8484 ClassTemplate->getInjectedClassNameSpecialization()) &&
8485 (!Context.getLangOpts().CPlusPlus20 ||
8486 !TemplateParams->hasAssociatedConstraints())) {
8487 // C++ [temp.class.spec]p9b3:
8488 //
8489 // -- The argument list of the specialization shall not be identical
8490 // to the implicit argument list of the primary template.
8491 //
8492 // This rule has since been removed, because it's redundant given DR1495,
8493 // but we keep it because it produces better diagnostics and recovery.
8494 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8495 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8496 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8497 return CheckClassTemplate(
8498 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8499 TemplateNameLoc, Attr, TemplateParams, AS_none,
8500 /*ModulePrivateLoc=*/SourceLocation(),
8501 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8502 TemplateParameterLists.data());
8503 }
8504
8505 // Create a new class template partial specialization declaration node.
8507 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8510 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8511 ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8512 Partial->setTemplateArgsAsWritten(TemplateArgs);
8513 SetNestedNameSpecifier(*this, Partial, SS);
8514 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8516 Context, TemplateParameterLists.drop_back(1));
8517 }
8518
8519 if (!PrevPartial)
8520 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8521 Specialization = Partial;
8522
8523 // If we are providing an explicit specialization of a member class
8524 // template specialization, make a note of that.
8525 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8526 PrevPartial->setMemberSpecialization();
8527
8529 } else {
8530 // Create a new class template specialization declaration node for
8531 // this explicit specialization or friend declaration.
8533 Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8534 CanonicalConverted, PrevDecl);
8535 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8537 if (TemplateParameterLists.size() > 0) {
8538 Specialization->setTemplateParameterListsInfo(Context,
8539 TemplateParameterLists);
8540 }
8541
8542 if (!PrevDecl)
8543 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8544
8546 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8547 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8548 CanonicalConverted);
8549 } else {
8551 }
8552 }
8553
8554 // C++ [temp.expl.spec]p6:
8555 // If a template, a member template or the member of a class template is
8556 // explicitly specialized then that specialization shall be declared
8557 // before the first use of that specialization that would cause an implicit
8558 // instantiation to take place, in every translation unit in which such a
8559 // use occurs; no diagnostic is required.
8560 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8561 bool Okay = false;
8562 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8563 // Is there any previous explicit specialization declaration?
8565 Okay = true;
8566 break;
8567 }
8568 }
8569
8570 if (!Okay) {
8571 SourceRange Range(TemplateNameLoc, RAngleLoc);
8572 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8574
8575 Diag(PrevDecl->getPointOfInstantiation(),
8576 diag::note_instantiation_required_here)
8577 << (PrevDecl->getTemplateSpecializationKind()
8579 return true;
8580 }
8581 }
8582
8583 // If this is not a friend, note that this is an explicit specialization.
8584 if (TUK != TagUseKind::Friend)
8585 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8586
8587 // Check that this isn't a redefinition of this specialization.
8588 if (TUK == TagUseKind::Definition) {
8589 RecordDecl *Def = Specialization->getDefinition();
8590 NamedDecl *Hidden = nullptr;
8591 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8592 SkipBody->ShouldSkip = true;
8593 SkipBody->Previous = Def;
8595 } else if (Def) {
8596 SourceRange Range(TemplateNameLoc, RAngleLoc);
8597 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8598 Diag(Def->getLocation(), diag::note_previous_definition);
8599 Specialization->setInvalidDecl();
8600 return true;
8601 }
8602 }
8603
8606
8607 // Add alignment attributes if necessary; these attributes are checked when
8608 // the ASTContext lays out the structure.
8609 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8612 }
8613
8614 if (ModulePrivateLoc.isValid())
8615 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8616 << (isPartialSpecialization? 1 : 0)
8617 << FixItHint::CreateRemoval(ModulePrivateLoc);
8618
8619 // C++ [temp.expl.spec]p9:
8620 // A template explicit specialization is in the scope of the
8621 // namespace in which the template was defined.
8622 //
8623 // We actually implement this paragraph where we set the semantic
8624 // context (in the creation of the ClassTemplateSpecializationDecl),
8625 // but we also maintain the lexical context where the actual
8626 // definition occurs.
8627 Specialization->setLexicalDeclContext(CurContext);
8628
8629 // We may be starting the definition of this specialization.
8630 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8631 Specialization->startDefinition();
8632
8633 if (TUK == TagUseKind::Friend) {
8634 // Build the fully-sugared type for this class template
8635 // specialization as the user wrote in the specialization
8636 // itself. This means that we'll pretty-print the type retrieved
8637 // from the specialization's declaration the way that the user
8638 // actually wrote the specialization, rather than formatting the
8639 // name based on the "canonical" representation used to store the
8640 // template arguments in the specialization.
8642 Name, TemplateNameLoc, TemplateArgs, CanonType);
8644 TemplateNameLoc,
8645 WrittenTy,
8646 /*FIXME:*/KWLoc);
8647 Friend->setAccess(AS_public);
8649 } else {
8650 // Add the specialization into its lexical context, so that it can
8651 // be seen when iterating through the list of declarations in that
8652 // context. However, specializations are not found by name lookup.
8654 }
8655
8656 if (SkipBody && SkipBody->ShouldSkip)
8657 return SkipBody->Previous;
8658
8659 Specialization->setInvalidDecl(Invalid);
8661 return Specialization;
8662}
8663
8665 MultiTemplateParamsArg TemplateParameterLists,
8666 Declarator &D) {
8667 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8668 ActOnDocumentableDecl(NewDecl);
8669 return NewDecl;
8670}
8671
8673 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8674 const IdentifierInfo *Name, SourceLocation NameLoc) {
8675 DeclContext *DC = CurContext;
8676
8677 if (!DC->getRedeclContext()->isFileContext()) {
8678 Diag(NameLoc,
8679 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8680 return nullptr;
8681 }
8682
8683 if (TemplateParameterLists.size() > 1) {
8684 Diag(NameLoc, diag::err_concept_extra_headers);
8685 return nullptr;
8686 }
8687
8688 TemplateParameterList *Params = TemplateParameterLists.front();
8689
8690 if (Params->size() == 0) {
8691 Diag(NameLoc, diag::err_concept_no_parameters);
8692 return nullptr;
8693 }
8694
8695 // Ensure that the parameter pack, if present, is the last parameter in the
8696 // template.
8697 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8698 ParamEnd = Params->end();
8699 ParamIt != ParamEnd; ++ParamIt) {
8700 Decl const *Param = *ParamIt;
8701 if (Param->isParameterPack()) {
8702 if (++ParamIt == ParamEnd)
8703 break;
8704 Diag(Param->getLocation(),
8705 diag::err_template_param_pack_must_be_last_template_parameter);
8706 return nullptr;
8707 }
8708 }
8709
8710 ConceptDecl *NewDecl =
8711 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8712
8713 if (NewDecl->hasAssociatedConstraints()) {
8714 // C++2a [temp.concept]p4:
8715 // A concept shall not have associated constraints.
8716 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8717 NewDecl->setInvalidDecl();
8718 }
8719
8720 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8721 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8723 LookupName(Previous, S);
8724 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8725 /*AllowInlineNamespace*/ false);
8726
8727 // We cannot properly handle redeclarations until we parse the constraint
8728 // expression, so only inject the name if we are sure we are not redeclaring a
8729 // symbol
8730 if (Previous.empty())
8731 PushOnScopeChains(NewDecl, S, true);
8732
8733 return NewDecl;
8734}
8735
8737 bool Found = false;
8739 while (F.hasNext()) {
8740 NamedDecl *D = F.next();
8741 if (D == C) {
8742 F.erase();
8743 Found = true;
8744 break;
8745 }
8746 }
8747 F.done();
8748 return Found;
8749}
8750
8753 Expr *ConstraintExpr,
8754 const ParsedAttributesView &Attrs) {
8755 assert(!C->hasDefinition() && "Concept already defined");
8756 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8757 return nullptr;
8758 C->setDefinition(ConstraintExpr);
8759 ProcessDeclAttributeList(S, C, Attrs);
8760
8761 // Check for conflicting previous declaration.
8762 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8763 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8765 LookupName(Previous, S);
8766 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8767 /*AllowInlineNamespace*/ false);
8768 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8769 bool AddToScope = true;
8770 CheckConceptRedefinition(C, Previous, AddToScope);
8771
8773 if (!WasAlreadyAdded && AddToScope)
8774 PushOnScopeChains(C, S);
8775
8776 return C;
8777}
8778
8780 LookupResult &Previous, bool &AddToScope) {
8781 AddToScope = true;
8782
8783 if (Previous.empty())
8784 return;
8785
8786 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8787 if (!OldConcept) {
8788 auto *Old = Previous.getRepresentativeDecl();
8789 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8790 << NewDecl->getDeclName();
8791 notePreviousDefinition(Old, NewDecl->getLocation());
8792 AddToScope = false;
8793 return;
8794 }
8795 // Check if we can merge with a concept declaration.
8796 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8797 if (!IsSame) {
8798 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8799 << NewDecl->getDeclName();
8800 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8801 AddToScope = false;
8802 return;
8803 }
8804 if (hasReachableDefinition(OldConcept) &&
8805 IsRedefinitionInModule(NewDecl, OldConcept)) {
8806 Diag(NewDecl->getLocation(), diag::err_redefinition)
8807 << NewDecl->getDeclName();
8808 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8809 AddToScope = false;
8810 return;
8811 }
8812 if (!Previous.isSingleResult()) {
8813 // FIXME: we should produce an error in case of ambig and failed lookups.
8814 // Other decls (e.g. namespaces) also have this shortcoming.
8815 return;
8816 }
8817 // We unwrap canonical decl late to check for module visibility.
8818 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8819}
8820
8823 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8824 Diag(Loc, diag::err_recursive_concept) << Concept;
8825 Diag(Concept->getLocation(), diag::note_declared_at);
8826 return true;
8827 }
8828 return false;
8829}
8830
8831/// \brief Strips various properties off an implicit instantiation
8832/// that has just been explicitly specialized.
8833static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8834 if (MinGW || (isa<FunctionDecl>(D) &&
8835 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8836 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8837
8838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8839 FD->setInlineSpecified(false);
8840}
8841
8842/// Compute the diagnostic location for an explicit instantiation
8843// declaration or definition.
8845 NamedDecl* D, SourceLocation PointOfInstantiation) {
8846 // Explicit instantiations following a specialization have no effect and
8847 // hence no PointOfInstantiation. In that case, walk decl backwards
8848 // until a valid name loc is found.
8849 SourceLocation PrevDiagLoc = PointOfInstantiation;
8850 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8851 Prev = Prev->getPreviousDecl()) {
8852 PrevDiagLoc = Prev->getLocation();
8853 }
8854 assert(PrevDiagLoc.isValid() &&
8855 "Explicit instantiation without point of instantiation?");
8856 return PrevDiagLoc;
8857}
8858
8859bool
8862 NamedDecl *PrevDecl,
8864 SourceLocation PrevPointOfInstantiation,
8865 bool &HasNoEffect) {
8866 HasNoEffect = false;
8867
8868 switch (NewTSK) {
8869 case TSK_Undeclared:
8871 assert(
8872 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8873 "previous declaration must be implicit!");
8874 return false;
8875
8877 switch (PrevTSK) {
8878 case TSK_Undeclared:
8880 // Okay, we're just specializing something that is either already
8881 // explicitly specialized or has merely been mentioned without any
8882 // instantiation.
8883 return false;
8884
8886 if (PrevPointOfInstantiation.isInvalid()) {
8887 // The declaration itself has not actually been instantiated, so it is
8888 // still okay to specialize it.
8890 PrevDecl,
8891 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8892 return false;
8893 }
8894 // Fall through
8895 [[fallthrough]];
8896
8899 assert((PrevTSK == TSK_ImplicitInstantiation ||
8900 PrevPointOfInstantiation.isValid()) &&
8901 "Explicit instantiation without point of instantiation?");
8902
8903 // C++ [temp.expl.spec]p6:
8904 // If a template, a member template or the member of a class template
8905 // is explicitly specialized then that specialization shall be declared
8906 // before the first use of that specialization that would cause an
8907 // implicit instantiation to take place, in every translation unit in
8908 // which such a use occurs; no diagnostic is required.
8909 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8910 // Is there any previous explicit specialization declaration?
8912 return false;
8913 }
8914
8915 Diag(NewLoc, diag::err_specialization_after_instantiation)
8916 << PrevDecl;
8917 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8918 << (PrevTSK != TSK_ImplicitInstantiation);
8919
8920 return true;
8921 }
8922 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8923
8925 switch (PrevTSK) {
8927 // This explicit instantiation declaration is redundant (that's okay).
8928 HasNoEffect = true;
8929 return false;
8930
8931 case TSK_Undeclared:
8933 // We're explicitly instantiating something that may have already been
8934 // implicitly instantiated; that's fine.
8935 return false;
8936
8938 // C++0x [temp.explicit]p4:
8939 // For a given set of template parameters, if an explicit instantiation
8940 // of a template appears after a declaration of an explicit
8941 // specialization for that template, the explicit instantiation has no
8942 // effect.
8943 HasNoEffect = true;
8944 return false;
8945
8947 // C++0x [temp.explicit]p10:
8948 // If an entity is the subject of both an explicit instantiation
8949 // declaration and an explicit instantiation definition in the same
8950 // translation unit, the definition shall follow the declaration.
8951 Diag(NewLoc,
8952 diag::err_explicit_instantiation_declaration_after_definition);
8953
8954 // Explicit instantiations following a specialization have no effect and
8955 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8956 // until a valid name loc is found.
8957 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8958 diag::note_explicit_instantiation_definition_here);
8959 HasNoEffect = true;
8960 return false;
8961 }
8962 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8963
8965 switch (PrevTSK) {
8966 case TSK_Undeclared:
8968 // We're explicitly instantiating something that may have already been
8969 // implicitly instantiated; that's fine.
8970 return false;
8971
8973 // C++ DR 259, C++0x [temp.explicit]p4:
8974 // For a given set of template parameters, if an explicit
8975 // instantiation of a template appears after a declaration of
8976 // an explicit specialization for that template, the explicit
8977 // instantiation has no effect.
8978 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8979 << PrevDecl;
8980 Diag(PrevDecl->getLocation(),
8981 diag::note_previous_template_specialization);
8982 HasNoEffect = true;
8983 return false;
8984
8986 // We're explicitly instantiating a definition for something for which we
8987 // were previously asked to suppress instantiations. That's fine.
8988
8989 // C++0x [temp.explicit]p4:
8990 // For a given set of template parameters, if an explicit instantiation
8991 // of a template appears after a declaration of an explicit
8992 // specialization for that template, the explicit instantiation has no
8993 // effect.
8994 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8995 // Is there any previous explicit specialization declaration?
8997 HasNoEffect = true;
8998 break;
8999 }
9000 }
9001
9002 return false;
9003
9005 // C++0x [temp.spec]p5:
9006 // For a given template and a given set of template-arguments,
9007 // - an explicit instantiation definition shall appear at most once
9008 // in a program,
9009
9010 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9011 Diag(NewLoc, (getLangOpts().MSVCCompat)
9012 ? diag::ext_explicit_instantiation_duplicate
9013 : diag::err_explicit_instantiation_duplicate)
9014 << PrevDecl;
9015 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9016 diag::note_previous_explicit_instantiation);
9017 HasNoEffect = true;
9018 return false;
9019 }
9020 }
9021
9022 llvm_unreachable("Missing specialization/instantiation case?");
9023}
9024
9026 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9028 // Remove anything from Previous that isn't a function template in
9029 // the correct context.
9030 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9031 LookupResult::Filter F = Previous.makeFilter();
9032 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9033 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9034 while (F.hasNext()) {
9036 if (!isa<FunctionTemplateDecl>(D)) {
9037 F.erase();
9038 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9039 continue;
9040 }
9041
9042 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9044 F.erase();
9045 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9046 continue;
9047 }
9048 }
9049 F.done();
9050
9051 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9052 if (Previous.empty()) {
9053 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9054 << IsFriend;
9055 for (auto &P : DiscardedCandidates)
9056 Diag(P.second->getLocation(),
9057 diag::note_dependent_function_template_spec_discard_reason)
9058 << P.first << IsFriend;
9059 return true;
9060 }
9061
9063 ExplicitTemplateArgs);
9064 return false;
9065}
9066
9068 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9069 LookupResult &Previous, bool QualifiedFriend) {
9070 // The set of function template specializations that could match this
9071 // explicit function template specialization.
9072 UnresolvedSet<8> Candidates;
9073 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9074 /*ForTakingAddress=*/false);
9075
9076 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9077 ConvertedTemplateArgs;
9078
9079 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9080 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9081 I != E; ++I) {
9082 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9083 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9084 // Only consider templates found within the same semantic lookup scope as
9085 // FD.
9086 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9088 continue;
9089
9090 QualType FT = FD->getType();
9091 // C++11 [dcl.constexpr]p8:
9092 // A constexpr specifier for a non-static member function that is not
9093 // a constructor declares that member function to be const.
9094 //
9095 // When matching a constexpr member function template specialization
9096 // against the primary template, we don't yet know whether the
9097 // specialization has an implicit 'const' (because we don't know whether
9098 // it will be a static member function until we know which template it
9099 // specializes). This rule was removed in C++14.
9100 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9101 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9102 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9103 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9104 if (OldMD && OldMD->isConst()) {
9105 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9107 EPI.TypeQuals.addConst();
9109 FPT->getParamTypes(), EPI);
9110 }
9111 }
9112
9114 if (ExplicitTemplateArgs)
9115 Args = *ExplicitTemplateArgs;
9116
9117 // C++ [temp.expl.spec]p11:
9118 // A trailing template-argument can be left unspecified in the
9119 // template-id naming an explicit function template specialization
9120 // provided it can be deduced from the function argument type.
9121 // Perform template argument deduction to determine whether we may be
9122 // specializing this template.
9123 // FIXME: It is somewhat wasteful to build
9124 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9125 FunctionDecl *Specialization = nullptr;
9127 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9128 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9130 // Template argument deduction failed; record why it failed, so
9131 // that we can provide nifty diagnostics.
9132 FailedCandidates.addCandidate().set(
9133 I.getPair(), FunTmpl->getTemplatedDecl(),
9134 MakeDeductionFailureInfo(Context, TDK, Info));
9135 (void)TDK;
9136 continue;
9137 }
9138
9139 // Target attributes are part of the cuda function signature, so
9140 // the deduced template's cuda target must match that of the
9141 // specialization. Given that C++ template deduction does not
9142 // take target attributes into account, we reject candidates
9143 // here that have a different target.
9144 if (LangOpts.CUDA &&
9146 /* IgnoreImplicitHDAttr = */ true) !=
9147 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9148 FailedCandidates.addCandidate().set(
9149 I.getPair(), FunTmpl->getTemplatedDecl(),
9152 continue;
9153 }
9154
9155 // Record this candidate.
9156 if (ExplicitTemplateArgs)
9157 ConvertedTemplateArgs[Specialization] = std::move(Args);
9158 Candidates.addDecl(Specialization, I.getAccess());
9159 }
9160 }
9161
9162 // For a qualified friend declaration (with no explicit marker to indicate
9163 // that a template specialization was intended), note all (template and
9164 // non-template) candidates.
9165 if (QualifiedFriend && Candidates.empty()) {
9166 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9167 << FD->getDeclName() << FDLookupContext;
9168 // FIXME: We should form a single candidate list and diagnose all
9169 // candidates at once, to get proper sorting and limiting.
9170 for (auto *OldND : Previous) {
9171 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9172 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9173 }
9174 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9175 return true;
9176 }
9177
9178 // Find the most specialized function template.
9180 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9181 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9182 PDiag(diag::err_function_template_spec_ambiguous)
9183 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9184 PDiag(diag::note_function_template_spec_matched));
9185
9186 if (Result == Candidates.end())
9187 return true;
9188
9189 // Ignore access information; it doesn't figure into redeclaration checking.
9190 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9191
9192 if (const auto *PT = Specialization->getPrimaryTemplate();
9193 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9194 auto Message = DSA->getMessage();
9195 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9196 << PT << !Message.empty() << Message;
9197 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9198 }
9199
9200 // C++23 [except.spec]p13:
9201 // An exception specification is considered to be needed when:
9202 // - [...]
9203 // - the exception specification is compared to that of another declaration
9204 // (e.g., an explicit specialization or an overriding virtual function);
9205 // - [...]
9206 //
9207 // The exception specification of a defaulted function is evaluated as
9208 // described above only when needed; similarly, the noexcept-specifier of a
9209 // specialization of a function template or member function of a class
9210 // template is instantiated only when needed.
9211 //
9212 // The standard doesn't specify what the "comparison with another declaration"
9213 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9214 // not state which properties of an explicit specialization must match the
9215 // primary template.
9216 //
9217 // We assume that an explicit specialization must correspond with (per
9218 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9219 // the declaration produced by substitution into the function template.
9220 //
9221 // Since the determination whether two function declarations correspond does
9222 // not consider exception specification, we only need to instantiate it once
9223 // we determine the primary template when comparing types per
9224 // [basic.link]p11.1.
9225 auto *SpecializationFPT =
9226 Specialization->getType()->castAs<FunctionProtoType>();
9227 // If the function has a dependent exception specification, resolve it after
9228 // we have selected the primary template so we can check whether it matches.
9229 if (getLangOpts().CPlusPlus17 &&
9230 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9231 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9232 return true;
9233
9235 = Specialization->getTemplateSpecializationInfo();
9236 assert(SpecInfo && "Function template specialization info missing?");
9237
9238 // Note: do not overwrite location info if previous template
9239 // specialization kind was explicit.
9241 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9242 Specialization->setLocation(FD->getLocation());
9243 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9244 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9245 // function can differ from the template declaration with respect to
9246 // the constexpr specifier.
9247 // FIXME: We need an update record for this AST mutation.
9248 // FIXME: What if there are multiple such prior declarations (for instance,
9249 // from different modules)?
9250 Specialization->setConstexprKind(FD->getConstexprKind());
9251 }
9252
9253 // FIXME: Check if the prior specialization has a point of instantiation.
9254 // If so, we have run afoul of .
9255
9256 // If this is a friend declaration, then we're not really declaring
9257 // an explicit specialization.
9258 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9259
9260 // Check the scope of this explicit specialization.
9261 if (!isFriend &&
9263 Specialization->getPrimaryTemplate(),
9265 false))
9266 return true;
9267
9268 // C++ [temp.expl.spec]p6:
9269 // If a template, a member template or the member of a class template is
9270 // explicitly specialized then that specialization shall be declared
9271 // before the first use of that specialization that would cause an implicit
9272 // instantiation to take place, in every translation unit in which such a
9273 // use occurs; no diagnostic is required.
9274 bool HasNoEffect = false;
9275 if (!isFriend &&
9280 SpecInfo->getPointOfInstantiation(),
9281 HasNoEffect))
9282 return true;
9283
9284 // Mark the prior declaration as an explicit specialization, so that later
9285 // clients know that this is an explicit specialization.
9286 if (!isFriend) {
9287 // Since explicit specializations do not inherit '=delete' from their
9288 // primary function template - check if the 'specialization' that was
9289 // implicitly generated (during template argument deduction for partial
9290 // ordering) from the most specialized of all the function templates that
9291 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9292 // first check that it was implicitly generated during template argument
9293 // deduction by making sure it wasn't referenced, and then reset the deleted
9294 // flag to not-deleted, so that we can inherit that information from 'FD'.
9295 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9296 !Specialization->getCanonicalDecl()->isReferenced()) {
9297 // FIXME: This assert will not hold in the presence of modules.
9298 assert(
9299 Specialization->getCanonicalDecl() == Specialization &&
9300 "This must be the only existing declaration of this specialization");
9301 // FIXME: We need an update record for this AST mutation.
9302 Specialization->setDeletedAsWritten(false);
9303 }
9304 // FIXME: We need an update record for this AST mutation.
9307 }
9308
9309 // Turn the given function declaration into a function template
9310 // specialization, with the template arguments from the previous
9311 // specialization.
9312 // Take copies of (semantic and syntactic) template argument lists.
9314 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9315 FD->setFunctionTemplateSpecialization(
9316 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9318 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9319
9320 // A function template specialization inherits the target attributes
9321 // of its template. (We require the attributes explicitly in the
9322 // code to match, but a template may have implicit attributes by
9323 // virtue e.g. of being constexpr, and it passes these implicit
9324 // attributes on to its specializations.)
9325 if (LangOpts.CUDA)
9326 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9327
9328 // The "previous declaration" for this function template specialization is
9329 // the prior function template specialization.
9330 Previous.clear();
9331 Previous.addDecl(Specialization);
9332 return false;
9333}
9334
9335bool
9337 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9338 "Only for non-template members");
9339
9340 // Try to find the member we are instantiating.
9341 NamedDecl *FoundInstantiation = nullptr;
9342 NamedDecl *Instantiation = nullptr;
9343 NamedDecl *InstantiatedFrom = nullptr;
9344 MemberSpecializationInfo *MSInfo = nullptr;
9345
9346 if (Previous.empty()) {
9347 // Nowhere to look anyway.
9348 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9349 UnresolvedSet<8> Candidates;
9350 for (NamedDecl *Candidate : Previous) {
9351 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9352 // Ignore any candidates that aren't member functions.
9353 if (!Method)
9354 continue;
9355
9356 QualType Adjusted = Function->getType();
9357 if (!hasExplicitCallingConv(Adjusted))
9358 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9359 // Ignore any candidates with the wrong type.
9360 // This doesn't handle deduced return types, but both function
9361 // declarations should be undeduced at this point.
9362 // FIXME: The exception specification should probably be ignored when
9363 // comparing the types.
9364 if (!Context.hasSameType(Adjusted, Method->getType()))
9365 continue;
9366
9367 // Ignore any candidates with unsatisfied constraints.
9368 if (ConstraintSatisfaction Satisfaction;
9369 Method->getTrailingRequiresClause() &&
9370 (CheckFunctionConstraints(Method, Satisfaction,
9371 /*UsageLoc=*/Member->getLocation(),
9372 /*ForOverloadResolution=*/true) ||
9373 !Satisfaction.IsSatisfied))
9374 continue;
9375
9376 Candidates.addDecl(Candidate);
9377 }
9378
9379 // If we have no viable candidates left after filtering, we are done.
9380 if (Candidates.empty())
9381 return false;
9382
9383 // Find the function that is more constrained than every other function it
9384 // has been compared to.
9385 UnresolvedSetIterator Best = Candidates.begin();
9386 CXXMethodDecl *BestMethod = nullptr;
9387 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9388 I != E; ++I) {
9389 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9390 if (I == Best ||
9391 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9392 Best = I;
9393 BestMethod = Method;
9394 }
9395 }
9396
9397 FoundInstantiation = *Best;
9398 Instantiation = BestMethod;
9399 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9400 MSInfo = BestMethod->getMemberSpecializationInfo();
9401
9402 // Make sure the best candidate is more constrained than all of the others.
9403 bool Ambiguous = false;
9404 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9405 I != E; ++I) {
9406 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9407 if (I != Best &&
9408 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9409 Ambiguous = true;
9410 break;
9411 }
9412 }
9413
9414 if (Ambiguous) {
9415 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9416 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9417 for (NamedDecl *Candidate : Candidates) {
9418 Candidate = Candidate->getUnderlyingDecl();
9419 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9420 << Candidate;
9421 }
9422 return true;
9423 }
9424 } else if (isa<VarDecl>(Member)) {
9425 VarDecl *PrevVar;
9426 if (Previous.isSingleResult() &&
9427 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9428 if (PrevVar->isStaticDataMember()) {
9429 FoundInstantiation = Previous.getRepresentativeDecl();
9430 Instantiation = PrevVar;
9431 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9432 MSInfo = PrevVar->getMemberSpecializationInfo();
9433 }
9434 } else if (isa<RecordDecl>(Member)) {
9435 CXXRecordDecl *PrevRecord;
9436 if (Previous.isSingleResult() &&
9437 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9438 FoundInstantiation = Previous.getRepresentativeDecl();
9439 Instantiation = PrevRecord;
9440 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9441 MSInfo = PrevRecord->getMemberSpecializationInfo();
9442 }
9443 } else if (isa<EnumDecl>(Member)) {
9444 EnumDecl *PrevEnum;
9445 if (Previous.isSingleResult() &&
9446 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9447 FoundInstantiation = Previous.getRepresentativeDecl();
9448 Instantiation = PrevEnum;
9449 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9450 MSInfo = PrevEnum->getMemberSpecializationInfo();
9451 }
9452 }
9453
9454 if (!Instantiation) {
9455 // There is no previous declaration that matches. Since member
9456 // specializations are always out-of-line, the caller will complain about
9457 // this mismatch later.
9458 return false;
9459 }
9460
9461 // A member specialization in a friend declaration isn't really declaring
9462 // an explicit specialization, just identifying a specific (possibly implicit)
9463 // specialization. Don't change the template specialization kind.
9464 //
9465 // FIXME: Is this really valid? Other compilers reject.
9466 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9467 // Preserve instantiation information.
9468 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9469 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9470 cast<CXXMethodDecl>(InstantiatedFrom),
9471 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9472 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9473 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9474 cast<CXXRecordDecl>(InstantiatedFrom),
9475 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9476 }
9477
9478 Previous.clear();
9479 Previous.addDecl(FoundInstantiation);
9480 return false;
9481 }
9482
9483 // Make sure that this is a specialization of a member.
9484 if (!InstantiatedFrom) {
9485 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9486 << Member;
9487 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9488 return true;
9489 }
9490
9491 // C++ [temp.expl.spec]p6:
9492 // If a template, a member template or the member of a class template is
9493 // explicitly specialized then that specialization shall be declared
9494 // before the first use of that specialization that would cause an implicit
9495 // instantiation to take place, in every translation unit in which such a
9496 // use occurs; no diagnostic is required.
9497 assert(MSInfo && "Member specialization info missing?");
9498
9499 bool HasNoEffect = false;
9502 Instantiation,
9504 MSInfo->getPointOfInstantiation(),
9505 HasNoEffect))
9506 return true;
9507
9508 // Check the scope of this explicit specialization.
9510 InstantiatedFrom,
9511 Instantiation, Member->getLocation(),
9512 false))
9513 return true;
9514
9515 // Note that this member specialization is an "instantiation of" the
9516 // corresponding member of the original template.
9517 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9518 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9519 if (InstantiationFunction->getTemplateSpecializationKind() ==
9521 // Explicit specializations of member functions of class templates do not
9522 // inherit '=delete' from the member function they are specializing.
9523 if (InstantiationFunction->isDeleted()) {
9524 // FIXME: This assert will not hold in the presence of modules.
9525 assert(InstantiationFunction->getCanonicalDecl() ==
9526 InstantiationFunction);
9527 // FIXME: We need an update record for this AST mutation.
9528 InstantiationFunction->setDeletedAsWritten(false);
9529 }
9530 }
9531
9532 MemberFunction->setInstantiationOfMemberFunction(
9533 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9534 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9535 MemberVar->setInstantiationOfStaticDataMember(
9536 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9537 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9538 MemberClass->setInstantiationOfMemberClass(
9539 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9540 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9541 MemberEnum->setInstantiationOfMemberEnum(
9542 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9543 } else {
9544 llvm_unreachable("unknown member specialization kind");
9545 }
9546
9547 // Save the caller the trouble of having to figure out which declaration
9548 // this specialization matches.
9549 Previous.clear();
9550 Previous.addDecl(FoundInstantiation);
9551 return false;
9552}
9553
9554/// Complete the explicit specialization of a member of a class template by
9555/// updating the instantiated member to be marked as an explicit specialization.
9556///
9557/// \param OrigD The member declaration instantiated from the template.
9558/// \param Loc The location of the explicit specialization of the member.
9559template<typename DeclT>
9560static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9562 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9563 return;
9564
9565 // FIXME: Inform AST mutation listeners of this AST mutation.
9566 // FIXME: If there are multiple in-class declarations of the member (from
9567 // multiple modules, or a declaration and later definition of a member type),
9568 // should we update all of them?
9569 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9570 OrigD->setLocation(Loc);
9571}
9572
9575 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9576 if (Instantiation == Member)
9577 return;
9578
9579 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9580 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9581 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9582 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9583 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9584 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9585 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9586 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9587 else
9588 llvm_unreachable("unknown member specialization kind");
9589}
9590
9591/// Check the scope of an explicit instantiation.
9592///
9593/// \returns true if a serious error occurs, false otherwise.
9595 SourceLocation InstLoc,
9596 bool WasQualifiedName) {
9598 DeclContext *CurContext = S.CurContext->getRedeclContext();
9599
9600 if (CurContext->isRecord()) {
9601 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9602 << D;
9603 return true;
9604 }
9605
9606 // C++11 [temp.explicit]p3:
9607 // An explicit instantiation shall appear in an enclosing namespace of its
9608 // template. If the name declared in the explicit instantiation is an
9609 // unqualified name, the explicit instantiation shall appear in the
9610 // namespace where its template is declared or, if that namespace is inline
9611 // (7.3.1), any namespace from its enclosing namespace set.
9612 //
9613 // This is DR275, which we do not retroactively apply to C++98/03.
9614 if (WasQualifiedName) {
9615 if (CurContext->Encloses(OrigContext))
9616 return false;
9617 } else {
9618 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9619 return false;
9620 }
9621
9622 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9623 if (WasQualifiedName)
9624 S.Diag(InstLoc,
9625 S.getLangOpts().CPlusPlus11?
9626 diag::err_explicit_instantiation_out_of_scope :
9627 diag::warn_explicit_instantiation_out_of_scope_0x)
9628 << D << NS;
9629 else
9630 S.Diag(InstLoc,
9631 S.getLangOpts().CPlusPlus11?
9632 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9633 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9634 << D << NS;
9635 } else
9636 S.Diag(InstLoc,
9637 S.getLangOpts().CPlusPlus11?
9638 diag::err_explicit_instantiation_must_be_global :
9639 diag::warn_explicit_instantiation_must_be_global_0x)
9640 << D;
9641 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9642 return false;
9643}
9644
9645/// Common checks for whether an explicit instantiation of \p D is valid.
9647 SourceLocation InstLoc,
9648 bool WasQualifiedName,
9650 // C++ [temp.explicit]p13:
9651 // An explicit instantiation declaration shall not name a specialization of
9652 // a template with internal linkage.
9654 D->getFormalLinkage() == Linkage::Internal) {
9655 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9656 return true;
9657 }
9658
9659 // C++11 [temp.explicit]p3: [DR 275]
9660 // An explicit instantiation shall appear in an enclosing namespace of its
9661 // template.
9662 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9663 return true;
9664
9665 return false;
9666}
9667
9668/// Determine whether the given scope specifier has a template-id in it.
9670 if (!SS.isSet())
9671 return false;
9672
9673 // C++11 [temp.explicit]p3:
9674 // If the explicit instantiation is for a member function, a member class
9675 // or a static data member of a class template specialization, the name of
9676 // the class template specialization in the qualified-id for the member
9677 // name shall be a simple-template-id.
9678 //
9679 // C++98 has the same restriction, just worded differently.
9680 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9681 NNS = NNS->getPrefix())
9682 if (const Type *T = NNS->getAsType())
9683 if (isa<TemplateSpecializationType>(T))
9684 return true;
9685
9686 return false;
9687}
9688
9689/// Make a dllexport or dllimport attr on a class template specialization take
9690/// effect.
9693 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9694 assert(A && "dllExportImportClassTemplateSpecialization called "
9695 "on Def without dllexport or dllimport");
9696
9697 // We reject explicit instantiations in class scope, so there should
9698 // never be any delayed exported classes to worry about.
9699 assert(S.DelayedDllExportClasses.empty() &&
9700 "delayed exports present at explicit instantiation");
9702
9703 // Propagate attribute to base class templates.
9704 for (auto &B : Def->bases()) {
9705 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9706 B.getType()->getAsCXXRecordDecl()))
9708 }
9709
9711}
9712
9714 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9715 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9716 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9717 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9718 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9719 // Find the class template we're specializing
9720 TemplateName Name = TemplateD.get();
9721 TemplateDecl *TD = Name.getAsTemplateDecl();
9722 // Check that the specialization uses the same tag kind as the
9723 // original template.
9725 assert(Kind != TagTypeKind::Enum &&
9726 "Invalid enum tag in class template explicit instantiation!");
9727
9728 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9729
9730 if (!ClassTemplate) {
9731 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9732 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9733 << TD << NTK << llvm::to_underlying(Kind);
9734 Diag(TD->getLocation(), diag::note_previous_use);
9735 return true;
9736 }
9737
9738 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9739 Kind, /*isDefinition*/false, KWLoc,
9740 ClassTemplate->getIdentifier())) {
9741 Diag(KWLoc, diag::err_use_with_wrong_tag)
9742 << ClassTemplate
9744 ClassTemplate->getTemplatedDecl()->getKindName());
9745 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9746 diag::note_previous_use);
9747 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9748 }
9749
9750 // C++0x [temp.explicit]p2:
9751 // There are two forms of explicit instantiation: an explicit instantiation
9752 // definition and an explicit instantiation declaration. An explicit
9753 // instantiation declaration begins with the extern keyword. [...]
9754 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9757
9759 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9760 // Check for dllexport class template instantiation declarations,
9761 // except for MinGW mode.
9762 for (const ParsedAttr &AL : Attr) {
9763 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9764 Diag(ExternLoc,
9765 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9766 Diag(AL.getLoc(), diag::note_attribute);
9767 break;
9768 }
9769 }
9770
9771 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9772 Diag(ExternLoc,
9773 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9774 Diag(A->getLocation(), diag::note_attribute);
9775 }
9776 }
9777
9778 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9779 // instantiation declarations for most purposes.
9780 bool DLLImportExplicitInstantiationDef = false;
9783 // Check for dllimport class template instantiation definitions.
9784 bool DLLImport =
9785 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9786 for (const ParsedAttr &AL : Attr) {
9787 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9788 DLLImport = true;
9789 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9790 // dllexport trumps dllimport here.
9791 DLLImport = false;
9792 break;
9793 }
9794 }
9795 if (DLLImport) {
9797 DLLImportExplicitInstantiationDef = true;
9798 }
9799 }
9800
9801 // Translate the parser's template argument list in our AST format.
9802 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9803 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9804
9805 // Check that the template argument list is well-formed for this
9806 // template.
9807 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9808 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9809 /*DefaultArgs=*/{}, false, SugaredConverted,
9810 CanonicalConverted,
9811 /*UpdateArgsWithConversions=*/true))
9812 return true;
9813
9814 // Find the class template specialization declaration that
9815 // corresponds to these arguments.
9816 void *InsertPos = nullptr;
9818 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9819
9820 TemplateSpecializationKind PrevDecl_TSK
9821 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9822
9823 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9824 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9825 // Check for dllexport class template instantiation definitions in MinGW
9826 // mode, if a previous declaration of the instantiation was seen.
9827 for (const ParsedAttr &AL : Attr) {
9828 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9829 Diag(AL.getLoc(),
9830 diag::warn_attribute_dllexport_explicit_instantiation_def);
9831 break;
9832 }
9833 }
9834 }
9835
9836 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9837 SS.isSet(), TSK))
9838 return true;
9839
9841
9842 bool HasNoEffect = false;
9843 if (PrevDecl) {
9844 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9845 PrevDecl, PrevDecl_TSK,
9846 PrevDecl->getPointOfInstantiation(),
9847 HasNoEffect))
9848 return PrevDecl;
9849
9850 // Even though HasNoEffect == true means that this explicit instantiation
9851 // has no effect on semantics, we go on to put its syntax in the AST.
9852
9853 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9854 PrevDecl_TSK == TSK_Undeclared) {
9855 // Since the only prior class template specialization with these
9856 // arguments was referenced but not declared, reuse that
9857 // declaration node as our own, updating the source location
9858 // for the template name to reflect our new declaration.
9859 // (Other source locations will be updated later.)
9860 Specialization = PrevDecl;
9861 Specialization->setLocation(TemplateNameLoc);
9862 PrevDecl = nullptr;
9863 }
9864
9865 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9866 DLLImportExplicitInstantiationDef) {
9867 // The new specialization might add a dllimport attribute.
9868 HasNoEffect = false;
9869 }
9870 }
9871
9872 if (!Specialization) {
9873 // Create a new class template specialization declaration node for
9874 // this explicit specialization.
9876 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9877 ClassTemplate, CanonicalConverted, PrevDecl);
9879
9880 // A MSInheritanceAttr attached to the previous declaration must be
9881 // propagated to the new node prior to instantiation.
9882 if (PrevDecl) {
9883 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9884 auto *Clone = A->clone(getASTContext());
9885 Clone->setInherited(true);
9886 Specialization->addAttr(Clone);
9888 }
9889 }
9890
9891 if (!HasNoEffect && !PrevDecl) {
9892 // Insert the new specialization.
9893 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9894 }
9895 }
9896
9897 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9898
9899 // Set source locations for keywords.
9900 Specialization->setExternKeywordLoc(ExternLoc);
9901 Specialization->setTemplateKeywordLoc(TemplateLoc);
9902 Specialization->setBraceRange(SourceRange());
9903
9904 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9907
9908 // Add the explicit instantiation into its lexical context. However,
9909 // since explicit instantiations are never found by name lookup, we
9910 // just put it into the declaration context directly.
9911 Specialization->setLexicalDeclContext(CurContext);
9913
9914 // Syntax is now OK, so return if it has no other effect on semantics.
9915 if (HasNoEffect) {
9916 // Set the template specialization kind.
9917 Specialization->setTemplateSpecializationKind(TSK);
9918 return Specialization;
9919 }
9920
9921 // C++ [temp.explicit]p3:
9922 // A definition of a class template or class member template
9923 // shall be in scope at the point of the explicit instantiation of
9924 // the class template or class member template.
9925 //
9926 // This check comes when we actually try to perform the
9927 // instantiation.
9929 = cast_or_null<ClassTemplateSpecializationDecl>(
9930 Specialization->getDefinition());
9931 if (!Def)
9933 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9934 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9935 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9936 }
9937
9938 // Instantiate the members of this class template specialization.
9939 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9940 Specialization->getDefinition());
9941 if (Def) {
9943 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9944 // TSK_ExplicitInstantiationDefinition
9945 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9947 DLLImportExplicitInstantiationDef)) {
9948 // FIXME: Need to notify the ASTMutationListener that we did this.
9950
9951 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9953 // An explicit instantiation definition can add a dll attribute to a
9954 // template with a previous instantiation declaration. MinGW doesn't
9955 // allow this.
9956 auto *A = cast<InheritableAttr>(
9958 A->setInherited(true);
9959 Def->addAttr(A);
9961 }
9962 }
9963
9964 // Fix a TSK_ImplicitInstantiation followed by a
9965 // TSK_ExplicitInstantiationDefinition
9966 bool NewlyDLLExported =
9967 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9968 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9970 // An explicit instantiation definition can add a dll attribute to a
9971 // template with a previous implicit instantiation. MinGW doesn't allow
9972 // this. We limit clang to only adding dllexport, to avoid potentially
9973 // strange codegen behavior. For example, if we extend this conditional
9974 // to dllimport, and we have a source file calling a method on an
9975 // implicitly instantiated template class instance and then declaring a
9976 // dllimport explicit instantiation definition for the same template
9977 // class, the codegen for the method call will not respect the dllimport,
9978 // while it will with cl. The Def will already have the DLL attribute,
9979 // since the Def and Specialization will be the same in the case of
9980 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9981 // attribute to the Specialization; we just need to make it take effect.
9982 assert(Def == Specialization &&
9983 "Def and Specialization should match for implicit instantiation");
9985 }
9986
9987 // In MinGW mode, export the template instantiation if the declaration
9988 // was marked dllexport.
9989 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9990 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9991 PrevDecl->hasAttr<DLLExportAttr>()) {
9993 }
9994
9995 // Set the template specialization kind. Make sure it is set before
9996 // instantiating the members which will trigger ASTConsumer callbacks.
9997 Specialization->setTemplateSpecializationKind(TSK);
9998 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9999 } else {
10000
10001 // Set the template specialization kind.
10002 Specialization->setTemplateSpecializationKind(TSK);
10003 }
10004
10005 return Specialization;
10006}
10007
10010 SourceLocation TemplateLoc, unsigned TagSpec,
10011 SourceLocation KWLoc, CXXScopeSpec &SS,
10012 IdentifierInfo *Name, SourceLocation NameLoc,
10013 const ParsedAttributesView &Attr) {
10014
10015 bool Owned = false;
10016 bool IsDependent = false;
10017 Decl *TagD =
10018 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10019 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10020 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10021 false, TypeResult(), /*IsTypeSpecifier*/ false,
10022 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
10023 .get();
10024 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10025
10026 if (!TagD)
10027 return true;
10028
10029 TagDecl *Tag = cast<TagDecl>(TagD);
10030 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10031
10032 if (Tag->isInvalidDecl())
10033 return true;
10034
10035 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10037 if (!Pattern) {
10038 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10040 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10041 return true;
10042 }
10043
10044 // C++0x [temp.explicit]p2:
10045 // If the explicit instantiation is for a class or member class, the
10046 // elaborated-type-specifier in the declaration shall include a
10047 // simple-template-id.
10048 //
10049 // C++98 has the same restriction, just worded differently.
10051 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10052 << Record << SS.getRange();
10053
10054 // C++0x [temp.explicit]p2:
10055 // There are two forms of explicit instantiation: an explicit instantiation
10056 // definition and an explicit instantiation declaration. An explicit
10057 // instantiation declaration begins with the extern keyword. [...]
10061
10062 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10063
10064 // Verify that it is okay to explicitly instantiate here.
10065 CXXRecordDecl *PrevDecl
10066 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10067 if (!PrevDecl && Record->getDefinition())
10068 PrevDecl = Record;
10069 if (PrevDecl) {
10071 bool HasNoEffect = false;
10072 assert(MSInfo && "No member specialization information?");
10073 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10074 PrevDecl,
10076 MSInfo->getPointOfInstantiation(),
10077 HasNoEffect))
10078 return true;
10079 if (HasNoEffect)
10080 return TagD;
10081 }
10082
10083 CXXRecordDecl *RecordDef
10084 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10085 if (!RecordDef) {
10086 // C++ [temp.explicit]p3:
10087 // A definition of a member class of a class template shall be in scope
10088 // at the point of an explicit instantiation of the member class.
10089 CXXRecordDecl *Def
10090 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10091 if (!Def) {
10092 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10093 << 0 << Record->getDeclName() << Record->getDeclContext();
10094 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10095 << Pattern;
10096 return true;
10097 } else {
10098 if (InstantiateClass(NameLoc, Record, Def,
10100 TSK))
10101 return true;
10102
10103 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10104 if (!RecordDef)
10105 return true;
10106 }
10107 }
10108
10109 // Instantiate all of the members of the class.
10110 InstantiateClassMembers(NameLoc, RecordDef,
10112
10114 MarkVTableUsed(NameLoc, RecordDef, true);
10115
10116 // FIXME: We don't have any representation for explicit instantiations of
10117 // member classes. Such a representation is not needed for compilation, but it
10118 // should be available for clients that want to see all of the declarations in
10119 // the source code.
10120 return TagD;
10121}
10122
10124 SourceLocation ExternLoc,
10125 SourceLocation TemplateLoc,
10126 Declarator &D) {
10127 // Explicit instantiations always require a name.
10128 // TODO: check if/when DNInfo should replace Name.
10130 DeclarationName Name = NameInfo.getName();
10131 if (!Name) {
10132 if (!D.isInvalidType())
10133 Diag(D.getDeclSpec().getBeginLoc(),
10134 diag::err_explicit_instantiation_requires_name)
10135 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10136
10137 return true;
10138 }
10139
10140 // Get the innermost enclosing declaration scope.
10141 S = S->getDeclParent();
10142
10143 // Determine the type of the declaration.
10145 QualType R = T->getType();
10146 if (R.isNull())
10147 return true;
10148
10149 // C++ [dcl.stc]p1:
10150 // A storage-class-specifier shall not be specified in [...] an explicit
10151 // instantiation (14.7.2) directive.
10152 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10153 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10154 << Name;
10155 return true;
10156 } else if (D.getDeclSpec().getStorageClassSpec()
10158 // Complain about then remove the storage class specifier.
10159 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10160 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10161
10162 D.getMutableDeclSpec().ClearStorageClassSpecs();
10163 }
10164
10165 // C++0x [temp.explicit]p1:
10166 // [...] An explicit instantiation of a function template shall not use the
10167 // inline or constexpr specifiers.
10168 // Presumably, this also applies to member functions of class templates as
10169 // well.
10170 if (D.getDeclSpec().isInlineSpecified())
10171 Diag(D.getDeclSpec().getInlineSpecLoc(),
10173 diag::err_explicit_instantiation_inline :
10174 diag::warn_explicit_instantiation_inline_0x)
10175 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10176 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10177 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10178 // not already specified.
10179 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10180 diag::err_explicit_instantiation_constexpr);
10181
10182 // A deduction guide is not on the list of entities that can be explicitly
10183 // instantiated.
10184 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10185 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10186 << /*explicit instantiation*/ 0;
10187 return true;
10188 }
10189
10190 // C++0x [temp.explicit]p2:
10191 // There are two forms of explicit instantiation: an explicit instantiation
10192 // definition and an explicit instantiation declaration. An explicit
10193 // instantiation declaration begins with the extern keyword. [...]
10197
10198 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10199 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10200 /*ObjectType=*/QualType());
10201
10202 if (!R->isFunctionType()) {
10203 // C++ [temp.explicit]p1:
10204 // A [...] static data member of a class template can be explicitly
10205 // instantiated from the member definition associated with its class
10206 // template.
10207 // C++1y [temp.explicit]p1:
10208 // A [...] variable [...] template specialization can be explicitly
10209 // instantiated from its template.
10210 if (Previous.isAmbiguous())
10211 return true;
10212
10213 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10214 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10215
10216 if (!PrevTemplate) {
10217 if (!Prev || !Prev->isStaticDataMember()) {
10218 // We expect to see a static data member here.
10219 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10220 << Name;
10221 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10222 P != PEnd; ++P)
10223 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10224 return true;
10225 }
10226
10228 // FIXME: Check for explicit specialization?
10229 Diag(D.getIdentifierLoc(),
10230 diag::err_explicit_instantiation_data_member_not_instantiated)
10231 << Prev;
10232 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10233 // FIXME: Can we provide a note showing where this was declared?
10234 return true;
10235 }
10236 } else {
10237 // Explicitly instantiate a variable template.
10238
10239 // C++1y [dcl.spec.auto]p6:
10240 // ... A program that uses auto or decltype(auto) in a context not
10241 // explicitly allowed in this section is ill-formed.
10242 //
10243 // This includes auto-typed variable template instantiations.
10244 if (R->isUndeducedType()) {
10245 Diag(T->getTypeLoc().getBeginLoc(),
10246 diag::err_auto_not_allowed_var_inst);
10247 return true;
10248 }
10249
10250 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10251 // C++1y [temp.explicit]p3:
10252 // If the explicit instantiation is for a variable, the unqualified-id
10253 // in the declaration shall be a template-id.
10254 Diag(D.getIdentifierLoc(),
10255 diag::err_explicit_instantiation_without_template_id)
10256 << PrevTemplate;
10257 Diag(PrevTemplate->getLocation(),
10258 diag::note_explicit_instantiation_here);
10259 return true;
10260 }
10261
10262 // Translate the parser's template argument list into our AST format.
10263 TemplateArgumentListInfo TemplateArgs =
10264 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10265
10266 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10267 D.getIdentifierLoc(), TemplateArgs);
10268 if (Res.isInvalid())
10269 return true;
10270
10271 if (!Res.isUsable()) {
10272 // We somehow specified dependent template arguments in an explicit
10273 // instantiation. This should probably only happen during error
10274 // recovery.
10275 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10276 return true;
10277 }
10278
10279 // Ignore access control bits, we don't need them for redeclaration
10280 // checking.
10281 Prev = cast<VarDecl>(Res.get());
10282 }
10283
10284 // C++0x [temp.explicit]p2:
10285 // If the explicit instantiation is for a member function, a member class
10286 // or a static data member of a class template specialization, the name of
10287 // the class template specialization in the qualified-id for the member
10288 // name shall be a simple-template-id.
10289 //
10290 // C++98 has the same restriction, just worded differently.
10291 //
10292 // This does not apply to variable template specializations, where the
10293 // template-id is in the unqualified-id instead.
10294 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10295 Diag(D.getIdentifierLoc(),
10296 diag::ext_explicit_instantiation_without_qualified_id)
10297 << Prev << D.getCXXScopeSpec().getRange();
10298
10299 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10300
10301 // Verify that it is okay to explicitly instantiate here.
10304 bool HasNoEffect = false;
10305 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10306 PrevTSK, POI, HasNoEffect))
10307 return true;
10308
10309 if (!HasNoEffect) {
10310 // Instantiate static data member or variable template.
10311 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10312 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10313 VTSD->setExternKeywordLoc(ExternLoc);
10314 VTSD->setTemplateKeywordLoc(TemplateLoc);
10315 }
10316
10317 // Merge attributes.
10318 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10319 if (PrevTemplate)
10320 ProcessAPINotes(Prev);
10321
10323 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10324 }
10325
10326 // Check the new variable specialization against the parsed input.
10327 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10328 Diag(T->getTypeLoc().getBeginLoc(),
10329 diag::err_invalid_var_template_spec_type)
10330 << 0 << PrevTemplate << R << Prev->getType();
10331 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10332 << 2 << PrevTemplate->getDeclName();
10333 return true;
10334 }
10335
10336 // FIXME: Create an ExplicitInstantiation node?
10337 return (Decl*) nullptr;
10338 }
10339
10340 // If the declarator is a template-id, translate the parser's template
10341 // argument list into our AST format.
10342 bool HasExplicitTemplateArgs = false;
10343 TemplateArgumentListInfo TemplateArgs;
10344 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10345 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10346 HasExplicitTemplateArgs = true;
10347 }
10348
10349 // C++ [temp.explicit]p1:
10350 // A [...] function [...] can be explicitly instantiated from its template.
10351 // A member function [...] of a class template can be explicitly
10352 // instantiated from the member definition associated with its class
10353 // template.
10354 UnresolvedSet<8> TemplateMatches;
10355 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10357 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10358 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10359 P != PEnd; ++P) {
10360 NamedDecl *Prev = *P;
10361 if (!HasExplicitTemplateArgs) {
10362 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10363 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10364 /*AdjustExceptionSpec*/true);
10365 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10366 if (Method->getPrimaryTemplate()) {
10367 TemplateMatches.addDecl(Method, P.getAccess());
10368 } else {
10369 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10370 C.FoundDecl = P.getPair();
10371 C.Function = Method;
10372 C.Viable = true;
10374 if (Method->getTrailingRequiresClause() &&
10375 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10376 /*ForOverloadResolution=*/true) ||
10377 !S.IsSatisfied)) {
10378 C.Viable = false;
10380 }
10381 }
10382 }
10383 }
10384 }
10385
10386 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10387 if (!FunTmpl)
10388 continue;
10389
10390 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10391 FunctionDecl *Specialization = nullptr;
10393 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10394 Specialization, Info);
10396 // Keep track of almost-matches.
10397 FailedTemplateCandidates.addCandidate().set(
10398 P.getPair(), FunTmpl->getTemplatedDecl(),
10399 MakeDeductionFailureInfo(Context, TDK, Info));
10400 (void)TDK;
10401 continue;
10402 }
10403
10404 // Target attributes are part of the cuda function signature, so
10405 // the cuda target of the instantiated function must match that of its
10406 // template. Given that C++ template deduction does not take
10407 // target attributes into account, we reject candidates here that
10408 // have a different target.
10409 if (LangOpts.CUDA &&
10411 /* IgnoreImplicitHDAttr = */ true) !=
10412 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10413 FailedTemplateCandidates.addCandidate().set(
10414 P.getPair(), FunTmpl->getTemplatedDecl(),
10417 continue;
10418 }
10419
10420 TemplateMatches.addDecl(Specialization, P.getAccess());
10421 }
10422
10423 FunctionDecl *Specialization = nullptr;
10424 if (!NonTemplateMatches.empty()) {
10425 unsigned Msg = 0;
10426 OverloadCandidateDisplayKind DisplayKind;
10428 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10429 Best)) {
10430 case OR_Success:
10431 case OR_Deleted:
10432 Specialization = cast<FunctionDecl>(Best->Function);
10433 break;
10434 case OR_Ambiguous:
10435 Msg = diag::err_explicit_instantiation_ambiguous;
10436 DisplayKind = OCD_AmbiguousCandidates;
10437 break;
10439 Msg = diag::err_explicit_instantiation_no_candidate;
10440 DisplayKind = OCD_AllCandidates;
10441 break;
10442 }
10443 if (Msg) {
10444 PartialDiagnostic Diag = PDiag(Msg) << Name;
10445 NonTemplateMatches.NoteCandidates(
10446 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10447 {});
10448 return true;
10449 }
10450 }
10451
10452 if (!Specialization) {
10453 // Find the most specialized function template specialization.
10455 TemplateMatches.begin(), TemplateMatches.end(),
10456 FailedTemplateCandidates, D.getIdentifierLoc(),
10457 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10458 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10459 PDiag(diag::note_explicit_instantiation_candidate));
10460
10461 if (Result == TemplateMatches.end())
10462 return true;
10463
10464 // Ignore access control bits, we don't need them for redeclaration checking.
10465 Specialization = cast<FunctionDecl>(*Result);
10466 }
10467
10468 // C++11 [except.spec]p4
10469 // In an explicit instantiation an exception-specification may be specified,
10470 // but is not required.
10471 // If an exception-specification is specified in an explicit instantiation
10472 // directive, it shall be compatible with the exception-specifications of
10473 // other declarations of that function.
10474 if (auto *FPT = R->getAs<FunctionProtoType>())
10475 if (FPT->hasExceptionSpec()) {
10476 unsigned DiagID =
10477 diag::err_mismatched_exception_spec_explicit_instantiation;
10478 if (getLangOpts().MicrosoftExt)
10479 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10481 PDiag(DiagID) << Specialization->getType(),
10482 PDiag(diag::note_explicit_instantiation_here),
10483 Specialization->getType()->getAs<FunctionProtoType>(),
10484 Specialization->getLocation(), FPT, D.getBeginLoc());
10485 // In Microsoft mode, mismatching exception specifications just cause a
10486 // warning.
10487 if (!getLangOpts().MicrosoftExt && Result)
10488 return true;
10489 }
10490
10491 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10492 Diag(D.getIdentifierLoc(),
10493 diag::err_explicit_instantiation_member_function_not_instantiated)
10495 << (Specialization->getTemplateSpecializationKind() ==
10497 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10498 return true;
10499 }
10500
10501 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10502 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10503 PrevDecl = Specialization;
10504
10505 if (PrevDecl) {
10506 bool HasNoEffect = false;
10507 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10508 PrevDecl,
10510 PrevDecl->getPointOfInstantiation(),
10511 HasNoEffect))
10512 return true;
10513
10514 // FIXME: We may still want to build some representation of this
10515 // explicit specialization.
10516 if (HasNoEffect)
10517 return (Decl*) nullptr;
10518 }
10519
10520 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10521 // functions
10522 // valarray<size_t>::valarray(size_t) and
10523 // valarray<size_t>::~valarray()
10524 // that it declared to have internal linkage with the internal_linkage
10525 // attribute. Ignore the explicit instantiation declaration in this case.
10526 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10528 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10529 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10530 RD->isInStdNamespace())
10531 return (Decl*) nullptr;
10532 }
10533
10534 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10536
10537 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10538 // instantiation declarations.
10540 Specialization->hasAttr<DLLImportAttr>() &&
10543
10544 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10545
10546 if (Specialization->isDefined()) {
10547 // Let the ASTConsumer know that this function has been explicitly
10548 // instantiated now, and its linkage might have changed.
10550 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10551 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10552
10553 // C++0x [temp.explicit]p2:
10554 // If the explicit instantiation is for a member function, a member class
10555 // or a static data member of a class template specialization, the name of
10556 // the class template specialization in the qualified-id for the member
10557 // name shall be a simple-template-id.
10558 //
10559 // C++98 has the same restriction, just worded differently.
10560 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10561 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10562 D.getCXXScopeSpec().isSet() &&
10563 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10564 Diag(D.getIdentifierLoc(),
10565 diag::ext_explicit_instantiation_without_qualified_id)
10566 << Specialization << D.getCXXScopeSpec().getRange();
10567
10569 *this,
10570 FunTmpl ? (NamedDecl *)FunTmpl
10571 : Specialization->getInstantiatedFromMemberFunction(),
10572 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10573
10574 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10575 return (Decl*) nullptr;
10576}
10577
10579 const CXXScopeSpec &SS,
10580 const IdentifierInfo *Name,
10581 SourceLocation TagLoc,
10582 SourceLocation NameLoc) {
10583 // This has to hold, because SS is expected to be defined.
10584 assert(Name && "Expected a name in a dependent tag");
10585
10586 NestedNameSpecifier *NNS = SS.getScopeRep();
10587 if (!NNS)
10588 return true;
10589
10591
10592 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10593 Diag(NameLoc, diag::err_dependent_tag_decl)
10594 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10595 << SS.getRange();
10596 return true;
10597 }
10598
10599 // Create the resulting type.
10601 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10602
10603 // Create type-source location information for this type.
10604 TypeLocBuilder TLB;
10606 TL.setElaboratedKeywordLoc(TagLoc);
10608 TL.setNameLoc(NameLoc);
10610}
10611
10613 const CXXScopeSpec &SS,
10614 const IdentifierInfo &II,
10615 SourceLocation IdLoc,
10616 ImplicitTypenameContext IsImplicitTypename) {
10617 if (SS.isInvalid())
10618 return true;
10619
10620 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10621 Diag(TypenameLoc,
10623 diag::warn_cxx98_compat_typename_outside_of_template :
10624 diag::ext_typename_outside_of_template)
10625 << FixItHint::CreateRemoval(TypenameLoc);
10626
10628 TypeSourceInfo *TSI = nullptr;
10629 QualType T =
10630 CheckTypenameType((TypenameLoc.isValid() ||
10631 IsImplicitTypename == ImplicitTypenameContext::Yes)
10634 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10635 /*DeducedTSTContext=*/true);
10636 if (T.isNull())
10637 return true;
10638 return CreateParsedType(T, TSI);
10639}
10640
10643 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10644 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10645 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10646 ASTTemplateArgsPtr TemplateArgsIn,
10647 SourceLocation RAngleLoc) {
10648 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10649 Diag(TypenameLoc,
10651 diag::warn_cxx98_compat_typename_outside_of_template :
10652 diag::ext_typename_outside_of_template)
10653 << FixItHint::CreateRemoval(TypenameLoc);
10654
10655 // Strangely, non-type results are not ignored by this lookup, so the
10656 // program is ill-formed if it finds an injected-class-name.
10657 if (TypenameLoc.isValid()) {
10658 auto *LookupRD =
10659 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10660 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10661 Diag(TemplateIILoc,
10662 diag::ext_out_of_line_qualified_id_type_names_constructor)
10663 << TemplateII << 0 /*injected-class-name used as template name*/
10664 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10665 }
10666 }
10667
10668 // Translate the parser's template argument list in our AST format.
10669 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10670 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10671
10672 TemplateName Template = TemplateIn.get();
10673 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10674 // Construct a dependent template specialization type.
10675 assert(DTN && "dependent template has non-dependent name?");
10676 assert(DTN->getQualifier() == SS.getScopeRep());
10677
10678 if (!DTN->isIdentifier()) {
10679 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10680 NoteAllFoundTemplates(Template);
10681 return true;
10682 }
10683
10685 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10686 DTN->getIdentifier(), TemplateArgs.arguments());
10687
10688 // Create source-location information for this type.
10689 TypeLocBuilder Builder;
10692 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10694 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10695 SpecTL.setTemplateNameLoc(TemplateIILoc);
10696 SpecTL.setLAngleLoc(LAngleLoc);
10697 SpecTL.setRAngleLoc(RAngleLoc);
10698 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10699 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10700 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10701 }
10702
10703 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10704 if (T.isNull())
10705 return true;
10706
10707 // Provide source-location information for the template specialization type.
10708 TypeLocBuilder Builder;
10710 = Builder.push<TemplateSpecializationTypeLoc>(T);
10711 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10712 SpecTL.setTemplateNameLoc(TemplateIILoc);
10713 SpecTL.setLAngleLoc(LAngleLoc);
10714 SpecTL.setRAngleLoc(RAngleLoc);
10715 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10716 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10717
10719 SS.getScopeRep(), T);
10720 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10721 TL.setElaboratedKeywordLoc(TypenameLoc);
10723
10724 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10725 return CreateParsedType(T, TSI);
10726}
10727
10728/// Determine whether this failed name lookup should be treated as being
10729/// disabled by a usage of std::enable_if.
10731 SourceRange &CondRange, Expr *&Cond) {
10732 // We must be looking for a ::type...
10733 if (!II.isStr("type"))
10734 return false;
10735
10736 // ... within an explicitly-written template specialization...
10737 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10738 return false;
10739 TypeLoc EnableIfTy = NNS.getTypeLoc();
10740 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10742 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10743 return false;
10744 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10745
10746 // ... which names a complete class template declaration...
10747 const TemplateDecl *EnableIfDecl =
10748 EnableIfTST->getTemplateName().getAsTemplateDecl();
10749 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10750 return false;
10751
10752 // ... called "enable_if".
10753 const IdentifierInfo *EnableIfII =
10754 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10755 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10756 return false;
10757
10758 // Assume the first template argument is the condition.
10759 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10760
10761 // Dig out the condition.
10762 Cond = nullptr;
10763 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10765 return true;
10766
10767 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10768
10769 // Ignore Boolean literals; they add no value.
10770 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10771 Cond = nullptr;
10772
10773 return true;
10774}
10775
10778 SourceLocation KeywordLoc,
10779 NestedNameSpecifierLoc QualifierLoc,
10780 const IdentifierInfo &II,
10781 SourceLocation IILoc,
10782 TypeSourceInfo **TSI,
10783 bool DeducedTSTContext) {
10784 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10785 DeducedTSTContext);
10786 if (T.isNull())
10787 return QualType();
10788
10790 if (isa<DependentNameType>(T)) {
10792 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10793 TL.setElaboratedKeywordLoc(KeywordLoc);
10794 TL.setQualifierLoc(QualifierLoc);
10795 TL.setNameLoc(IILoc);
10796 } else {
10797 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10798 TL.setElaboratedKeywordLoc(KeywordLoc);
10799 TL.setQualifierLoc(QualifierLoc);
10800 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10801 }
10802 return T;
10803}
10804
10805/// Build the type that describes a C++ typename specifier,
10806/// e.g., "typename T::type".
10809 SourceLocation KeywordLoc,
10810 NestedNameSpecifierLoc QualifierLoc,
10811 const IdentifierInfo &II,
10812 SourceLocation IILoc, bool DeducedTSTContext) {
10813 CXXScopeSpec SS;
10814 SS.Adopt(QualifierLoc);
10815
10816 DeclContext *Ctx = nullptr;
10817 if (QualifierLoc) {
10818 Ctx = computeDeclContext(SS);
10819 if (!Ctx) {
10820 // If the nested-name-specifier is dependent and couldn't be
10821 // resolved to a type, build a typename type.
10822 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10823 return Context.getDependentNameType(Keyword,
10824 QualifierLoc.getNestedNameSpecifier(),
10825 &II);
10826 }
10827
10828 // If the nested-name-specifier refers to the current instantiation,
10829 // the "typename" keyword itself is superfluous. In C++03, the
10830 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10831 // allows such extraneous "typename" keywords, and we retroactively
10832 // apply this DR to C++03 code with only a warning. In any case we continue.
10833
10834 if (RequireCompleteDeclContext(SS, Ctx))
10835 return QualType();
10836 }
10837
10838 DeclarationName Name(&II);
10839 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10840 if (Ctx)
10841 LookupQualifiedName(Result, Ctx, SS);
10842 else
10843 LookupName(Result, CurScope);
10844 unsigned DiagID = 0;
10845 Decl *Referenced = nullptr;
10846 switch (Result.getResultKind()) {
10848 // If we're looking up 'type' within a template named 'enable_if', produce
10849 // a more specific diagnostic.
10850 SourceRange CondRange;
10851 Expr *Cond = nullptr;
10852 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10853 // If we have a condition, narrow it down to the specific failed
10854 // condition.
10855 if (Cond) {
10856 Expr *FailedCond;
10857 std::string FailedDescription;
10858 std::tie(FailedCond, FailedDescription) =
10860
10861 Diag(FailedCond->getExprLoc(),
10862 diag::err_typename_nested_not_found_requirement)
10863 << FailedDescription
10864 << FailedCond->getSourceRange();
10865 return QualType();
10866 }
10867
10868 Diag(CondRange.getBegin(),
10869 diag::err_typename_nested_not_found_enable_if)
10870 << Ctx << CondRange;
10871 return QualType();
10872 }
10873
10874 DiagID = Ctx ? diag::err_typename_nested_not_found
10875 : diag::err_unknown_typename;
10876 break;
10877 }
10878
10880 // We found a using declaration that is a value. Most likely, the using
10881 // declaration itself is meant to have the 'typename' keyword.
10882 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10883 IILoc);
10884 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10885 << Name << Ctx << FullRange;
10886 if (UnresolvedUsingValueDecl *Using
10887 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10888 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10889 Diag(Loc, diag::note_using_value_decl_missing_typename)
10890 << FixItHint::CreateInsertion(Loc, "typename ");
10891 }
10892 }
10893 // Fall through to create a dependent typename type, from which we can recover
10894 // better.
10895 [[fallthrough]];
10896
10898 // Okay, it's a member of an unknown instantiation.
10899 return Context.getDependentNameType(Keyword,
10900 QualifierLoc.getNestedNameSpecifier(),
10901 &II);
10902
10904 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10905 // C++ [class.qual]p2:
10906 // In a lookup in which function names are not ignored and the
10907 // nested-name-specifier nominates a class C, if the name specified
10908 // after the nested-name-specifier, when looked up in C, is the
10909 // injected-class-name of C [...] then the name is instead considered
10910 // to name the constructor of class C.
10911 //
10912 // Unlike in an elaborated-type-specifier, function names are not ignored
10913 // in typename-specifier lookup. However, they are ignored in all the
10914 // contexts where we form a typename type with no keyword (that is, in
10915 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10916 //
10917 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10918 // ignore functions, but that appears to be an oversight.
10919 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10920 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10921 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10922 FoundRD->isInjectedClassName() &&
10923 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10924 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10925 << &II << 1 << 0 /*'typename' keyword used*/;
10926
10927 // We found a type. Build an ElaboratedType, since the
10928 // typename-specifier was just sugar.
10929 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10930 return Context.getElaboratedType(Keyword,
10931 QualifierLoc.getNestedNameSpecifier(),
10933 }
10934
10935 // C++ [dcl.type.simple]p2:
10936 // A type-specifier of the form
10937 // typename[opt] nested-name-specifier[opt] template-name
10938 // is a placeholder for a deduced class type [...].
10939 if (getLangOpts().CPlusPlus17) {
10940 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10941 if (!DeducedTSTContext) {
10942 QualType T(QualifierLoc
10943 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10944 : nullptr, 0);
10945 if (!T.isNull())
10946 Diag(IILoc, diag::err_dependent_deduced_tst)
10948 else
10949 Diag(IILoc, diag::err_deduced_tst)
10952 return QualType();
10953 }
10955 Keyword, QualifierLoc.getNestedNameSpecifier(),
10957 QualType(), false));
10958 }
10959 }
10960
10961 DiagID = Ctx ? diag::err_typename_nested_not_type
10962 : diag::err_typename_not_type;
10963 Referenced = Result.getFoundDecl();
10964 break;
10965
10967 DiagID = Ctx ? diag::err_typename_nested_not_type
10968 : diag::err_typename_not_type;
10969 Referenced = *Result.begin();
10970 break;
10971
10973 return QualType();
10974 }
10975
10976 // If we get here, it's because name lookup did not find a
10977 // type. Emit an appropriate diagnostic and return an error.
10978 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10979 IILoc);
10980 if (Ctx)
10981 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10982 else
10983 Diag(IILoc, DiagID) << FullRange << Name;
10984 if (Referenced)
10985 Diag(Referenced->getLocation(),
10986 Ctx ? diag::note_typename_member_refers_here
10987 : diag::note_typename_refers_here)
10988 << Name;
10989 return QualType();
10990}
10991
10992namespace {
10993 // See Sema::RebuildTypeInCurrentInstantiation
10994 class CurrentInstantiationRebuilder
10995 : public TreeTransform<CurrentInstantiationRebuilder> {
10997 DeclarationName Entity;
10998
10999 public:
11001
11002 CurrentInstantiationRebuilder(Sema &SemaRef,
11004 DeclarationName Entity)
11005 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11006 Loc(Loc), Entity(Entity) { }
11007
11008 /// Determine whether the given type \p T has already been
11009 /// transformed.
11010 ///
11011 /// For the purposes of type reconstruction, a type has already been
11012 /// transformed if it is NULL or if it is not dependent.
11013 bool AlreadyTransformed(QualType T) {
11014 return T.isNull() || !T->isInstantiationDependentType();
11015 }
11016
11017 /// Returns the location of the entity whose type is being
11018 /// rebuilt.
11019 SourceLocation getBaseLocation() { return Loc; }
11020
11021 /// Returns the name of the entity whose type is being rebuilt.
11022 DeclarationName getBaseEntity() { return Entity; }
11023
11024 /// Sets the "base" location and entity when that
11025 /// information is known based on another transformation.
11026 void setBase(SourceLocation Loc, DeclarationName Entity) {
11027 this->Loc = Loc;
11028 this->Entity = Entity;
11029 }
11030
11031 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11032 // Lambdas never need to be transformed.
11033 return E;
11034 }
11035 };
11036} // end anonymous namespace
11037
11040 DeclarationName Name) {
11041 if (!T || !T->getType()->isInstantiationDependentType())
11042 return T;
11043
11044 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11045 return Rebuilder.TransformType(T);
11046}
11047
11049 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11050 DeclarationName());
11051 return Rebuilder.TransformExpr(E);
11052}
11053
11055 if (SS.isInvalid())
11056 return true;
11057
11059 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11060 DeclarationName());
11062 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11063 if (!Rebuilt)
11064 return true;
11065
11066 SS.Adopt(Rebuilt);
11067 return false;
11068}
11069
11071 TemplateParameterList *Params) {
11072 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11073 Decl *Param = Params->getParam(I);
11074
11075 // There is nothing to rebuild in a type parameter.
11076 if (isa<TemplateTypeParmDecl>(Param))
11077 continue;
11078
11079 // Rebuild the template parameter list of a template template parameter.
11081 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11083 TTP->getTemplateParameters()))
11084 return true;
11085
11086 continue;
11087 }
11088
11089 // Rebuild the type of a non-type template parameter.
11090 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11091 TypeSourceInfo *NewTSI
11093 NTTP->getLocation(),
11094 NTTP->getDeclName());
11095 if (!NewTSI)
11096 return true;
11097
11098 if (NewTSI->getType()->isUndeducedType()) {
11099 // C++17 [temp.dep.expr]p3:
11100 // An id-expression is type-dependent if it contains
11101 // - an identifier associated by name lookup with a non-type
11102 // template-parameter declared with a type that contains a
11103 // placeholder type (7.1.7.4),
11104 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11105 }
11106
11107 if (NewTSI != NTTP->getTypeSourceInfo()) {
11108 NTTP->setTypeSourceInfo(NewTSI);
11109 NTTP->setType(NewTSI->getType());
11110 }
11111 }
11112
11113 return false;
11114}
11115
11116std::string
11118 const TemplateArgumentList &Args) {
11119 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11120}
11121
11122std::string
11124 const TemplateArgument *Args,
11125 unsigned NumArgs) {
11126 SmallString<128> Str;
11127 llvm::raw_svector_ostream Out(Str);
11128
11129 if (!Params || Params->size() == 0 || NumArgs == 0)
11130 return std::string();
11131
11132 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11133 if (I >= NumArgs)
11134 break;
11135
11136 if (I == 0)
11137 Out << "[with ";
11138 else
11139 Out << ", ";
11140
11141 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11142 Out << Id->getName();
11143 } else {
11144 Out << '$' << I;
11145 }
11146
11147 Out << " = ";
11148 Args[I].print(getPrintingPolicy(), Out,
11150 getPrintingPolicy(), Params, I));
11151 }
11152
11153 Out << ']';
11154 return std::string(Out.str());
11155}
11156
11158 CachedTokens &Toks) {
11159 if (!FD)
11160 return;
11161
11162 auto LPT = std::make_unique<LateParsedTemplate>();
11163
11164 // Take tokens to avoid allocations
11165 LPT->Toks.swap(Toks);
11166 LPT->D = FnD;
11167 LPT->FPO = getCurFPFeatures();
11168 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11169
11170 FD->setLateTemplateParsed(true);
11171}
11172
11174 if (!FD)
11175 return;
11176 FD->setLateTemplateParsed(false);
11177}
11178
11180 DeclContext *DC = CurContext;
11181
11182 while (DC) {
11183 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11184 const FunctionDecl *FD = RD->isLocalClass();
11185 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11186 } else if (DC->isTranslationUnit() || DC->isNamespace())
11187 return false;
11188
11189 DC = DC->getParent();
11190 }
11191 return false;
11192}
11193
11194namespace {
11195/// Walk the path from which a declaration was instantiated, and check
11196/// that every explicit specialization along that path is visible. This enforces
11197/// C++ [temp.expl.spec]/6:
11198///
11199/// If a template, a member template or a member of a class template is
11200/// explicitly specialized then that specialization shall be declared before
11201/// the first use of that specialization that would cause an implicit
11202/// instantiation to take place, in every translation unit in which such a
11203/// use occurs; no diagnostic is required.
11204///
11205/// and also C++ [temp.class.spec]/1:
11206///
11207/// A partial specialization shall be declared before the first use of a
11208/// class template specialization that would make use of the partial
11209/// specialization as the result of an implicit or explicit instantiation
11210/// in every translation unit in which such a use occurs; no diagnostic is
11211/// required.
11212class ExplicitSpecializationVisibilityChecker {
11213 Sema &S;
11217
11218public:
11219 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11221 : S(S), Loc(Loc), Kind(Kind) {}
11222
11223 void check(NamedDecl *ND) {
11224 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11225 return checkImpl(FD);
11226 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11227 return checkImpl(RD);
11228 if (auto *VD = dyn_cast<VarDecl>(ND))
11229 return checkImpl(VD);
11230 if (auto *ED = dyn_cast<EnumDecl>(ND))
11231 return checkImpl(ED);
11232 }
11233
11234private:
11235 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11236 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11237 : Sema::MissingImportKind::ExplicitSpecialization;
11238 const bool Recover = true;
11239
11240 // If we got a custom set of modules (because only a subset of the
11241 // declarations are interesting), use them, otherwise let
11242 // diagnoseMissingImport intelligently pick some.
11243 if (Modules.empty())
11244 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11245 else
11246 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11247 }
11248
11249 bool CheckMemberSpecialization(const NamedDecl *D) {
11250 return Kind == Sema::AcceptableKind::Visible
11253 }
11254
11255 bool CheckExplicitSpecialization(const NamedDecl *D) {
11256 return Kind == Sema::AcceptableKind::Visible
11259 }
11260
11261 bool CheckDeclaration(const NamedDecl *D) {
11262 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11264 }
11265
11266 // Check a specific declaration. There are three problematic cases:
11267 //
11268 // 1) The declaration is an explicit specialization of a template
11269 // specialization.
11270 // 2) The declaration is an explicit specialization of a member of an
11271 // templated class.
11272 // 3) The declaration is an instantiation of a template, and that template
11273 // is an explicit specialization of a member of a templated class.
11274 //
11275 // We don't need to go any deeper than that, as the instantiation of the
11276 // surrounding class / etc is not triggered by whatever triggered this
11277 // instantiation, and thus should be checked elsewhere.
11278 template<typename SpecDecl>
11279 void checkImpl(SpecDecl *Spec) {
11280 bool IsHiddenExplicitSpecialization = false;
11281 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11282 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11283 ? !CheckMemberSpecialization(Spec)
11284 : !CheckExplicitSpecialization(Spec);
11285 } else {
11286 checkInstantiated(Spec);
11287 }
11288
11289 if (IsHiddenExplicitSpecialization)
11290 diagnose(Spec->getMostRecentDecl(), false);
11291 }
11292
11293 void checkInstantiated(FunctionDecl *FD) {
11294 if (auto *TD = FD->getPrimaryTemplate())
11295 checkTemplate(TD);
11296 }
11297
11298 void checkInstantiated(CXXRecordDecl *RD) {
11299 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11300 if (!SD)
11301 return;
11302
11303 auto From = SD->getSpecializedTemplateOrPartial();
11304 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11305 checkTemplate(TD);
11306 else if (auto *TD =
11307 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11308 if (!CheckDeclaration(TD))
11309 diagnose(TD, true);
11310 checkTemplate(TD);
11311 }
11312 }
11313
11314 void checkInstantiated(VarDecl *RD) {
11315 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11316 if (!SD)
11317 return;
11318
11319 auto From = SD->getSpecializedTemplateOrPartial();
11320 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11321 checkTemplate(TD);
11322 else if (auto *TD =
11323 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11324 if (!CheckDeclaration(TD))
11325 diagnose(TD, true);
11326 checkTemplate(TD);
11327 }
11328 }
11329
11330 void checkInstantiated(EnumDecl *FD) {}
11331
11332 template<typename TemplDecl>
11333 void checkTemplate(TemplDecl *TD) {
11334 if (TD->isMemberSpecialization()) {
11335 if (!CheckMemberSpecialization(TD))
11336 diagnose(TD->getMostRecentDecl(), false);
11337 }
11338 }
11339};
11340} // end anonymous namespace
11341
11343 if (!getLangOpts().Modules)
11344 return;
11345
11346 ExplicitSpecializationVisibilityChecker(*this, Loc,
11348 .check(Spec);
11349}
11350
11352 NamedDecl *Spec) {
11353 if (!getLangOpts().CPlusPlusModules)
11354 return checkSpecializationVisibility(Loc, Spec);
11355
11356 ExplicitSpecializationVisibilityChecker(*this, Loc,
11358 .check(Spec);
11359}
11360
11363 return N->getLocation();
11364 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11366 return FD->getLocation();
11369 return N->getLocation();
11370 }
11371 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11372 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11373 continue;
11374 return CSC.PointOfInstantiation;
11375 }
11376 return N->getLocation();
11377}
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
Expr * E
enum clang::sema::@1712::IndirectLocalPathEntry::EntryKind Kind
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:7584
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
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:13193
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8041
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3003
Whether and why a template name is required in this lookup.
Definition: Sema.h:11083
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11091
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12079
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12109
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7222
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
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:13127
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12636
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2386
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:15491
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8979
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8991
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8986
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19638
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:9293
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:1070
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:17138
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:1658
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:11054
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11628
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11631
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11635
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:908
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:528
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:531
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:690
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:816
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:11044
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:11774
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:11792
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:11803
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11782
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11813
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:11104
@ 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:11037
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:526
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:81
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:13938
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13926
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13935
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:13929
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13953
const LangOptions & getLangOpts() const
Definition: Sema.h:524
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:907
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:14368
const LangOptions & LangOpts
Definition: Sema.h:906
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:20050
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:8971
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:9788
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:1043
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:3835
@ NTK_TypeAliasTemplate
Definition: Sema.h:3843
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:14938
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:9377
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:9994
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:909
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:8409
@ 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:11081
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:11270
@ TPC_ClassTemplate
Definition: Sema.h:11271
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11276
@ TPC_ClassTemplateMember
Definition: Sema.h:11274
@ TPC_FunctionTemplate
Definition: Sema.h:11273
@ TPC_FriendClassTemplate
Definition: Sema.h:11275
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11277
@ TPC_TypeAliasTemplate
Definition: Sema.h:11278
@ TPC_VarTemplate
Definition: Sema.h:11272
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:3861
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5802
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:21152
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:2996
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:11046
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:9302
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12480
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:8261
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:348
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:324
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
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:1255
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1326
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1293
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
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:446
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:310
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:313
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:307
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:364
@ 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:12653
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12760
A stack object to be created when performing template instantiation.
Definition: Sema.h:12838
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12992
NamedDecl * Previous
Definition: Sema.h:351
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.